diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b1fb5f3eb1..ae98672930 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: [ main, develop ] pull_request: - branches: [ main, develop ] types: [opened, synchronize, reopened, edited] workflow_dispatch: @@ -321,6 +320,10 @@ jobs: with: requirements: ${{ (needs.changes.outputs.lightweight_only == 'true' && needs.changes.outputs.design_docs_changed == 'true' && needs.changes.outputs.validation_python_changed != 'true') && 'yaml' || 'ci' }} + - name: 📦 Install bounded wire test dependencies + if: ${{ needs.changes.outputs.lightweight_only != 'true' }} + run: python3 -m pip install --disable-pip-version-check --require-hashes -r config/python/smoke-requirements.txt + - name: 📦 Install cloc if: ${{ needs.changes.outputs.lightweight_only != 'true' }} env: @@ -1012,7 +1015,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/dev-demo.yml b/.github/workflows/dev-demo.yml index 37dc0ecaae..a2f719e60b 100644 --- a/.github/workflows/dev-demo.yml +++ b/.github/workflows/dev-demo.yml @@ -804,6 +804,18 @@ jobs: trap cleanup_bootstrap_resources EXIT trap 'exit 130' INT trap 'exit 143' TERM + # BEGIN gateway port parser + parse_bootstrap_gateway_port() { + local port + port="$(sed -nE 's/^Forwarding from 127[.]0[.]0[.]1:([0-9]{1,5}) -> 8080$/\1/p' "$1" | head -n1)" + if [[ "$port" =~ ^[0-9]{1,5}$ ]] \ + && (( 10#$port >= 1 && 10#$port <= 65535 )); then + printf '%s\n' "$((10#$port))" + return 0 + fi + return 1 + } + # END gateway port parser for credential in DEMO_SMOKE_EMAIL DEMO_SMOKE_PASSWORD DEMO_SMOKE_USERNAME; do if [[ -z "${!credential:-}" ]]; then echo "::error::${credential} is empty; refusing to create dev-demo bootstrap credentials" >&2 @@ -824,10 +836,7 @@ jobs: cat "${BOOTSTRAP_PORT_FORWARD_LOG}" || true exit 1 fi - BOOTSTRAP_GATEWAY_PORT="$({ - sed -nE 's/^Forwarding from 127[.]0[.]0[.]1:([0-9]+) -> 80$/\1/p' \ - "${BOOTSTRAP_PORT_FORWARD_LOG}" || true - } | head -n1)" + BOOTSTRAP_GATEWAY_PORT="$(parse_bootstrap_gateway_port "${BOOTSTRAP_PORT_FORWARD_LOG}" || true)" if [[ "${BOOTSTRAP_GATEWAY_PORT}" =~ ^[0-9]+$ ]] \ && (( BOOTSTRAP_GATEWAY_PORT > 0 && BOOTSTRAP_GATEWAY_PORT <= 65535 )); then break diff --git a/.github/workflows/hosted-identity-request.yml b/.github/workflows/hosted-identity-request.yml index 558087b9a9..c417cdde9a 100644 --- a/.github/workflows/hosted-identity-request.yml +++ b/.github/workflows/hosted-identity-request.yml @@ -1187,6 +1187,13 @@ jobs: contents: read # Check out the trusted default-branch verification implementation. pull-requests: read # Revalidate the pull-request state and exact head before publication. issues: write # GitHub's issue-comment API owns pull-request comments. + env: + # One trusted demo identity/scope feeds both transports; ambient smoke overrides cannot split parity. + HOSTED_PLAYABLE_EMAIL: demo@example.com + HOSTED_PLAYABLE_PASSWORD: swordfish + HOSTED_PLAYABLE_WORLD: demo + HOSTED_PLAYABLE_REALM: production + HOSTED_PLAYABLE_CHARACTER: '' steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: @@ -1198,6 +1205,8 @@ jobs: - name: Set up canonical Python dependencies uses: ./.github/actions/setup-python + with: + requirements: smoke - name: Set up kubectl uses: ./.github/actions/setup-kubectl @@ -1207,6 +1216,22 @@ jobs: with: content: ${{ secrets.TRUSTED_HOSTED_PREVIEW_RUNTIME_KUBECONFIG }} path: ${{ runner.temp }}/preview-runtime.kubeconfig + export-to-github-env: 'false' + + - name: Write trusted namespace-manager kubeconfig + uses: ./.github/actions/write-kubeconfig + with: + content: ${{ secrets.TRUSTED_HOSTED_PREVIEW_NAMESPACE_MANAGER_KUBECONFIG }} + path: ${{ runner.temp }}/preview-namespace-manager.kubeconfig + export-to-github-env: 'false' + + - name: Write requester kubeconfig + if: ${{ needs.validate-target.outputs.certificate_identity_mode == 'hosted-controller' }} + uses: ./.github/actions/write-kubeconfig + with: + content: ${{ secrets.TRUSTED_HOSTED_IDENTITY_REQUESTER_KUBECONFIG }} + path: ${{ runner.temp }}/hosted-identity-requester.kubeconfig + export-to-github-env: 'false' - name: Revalidate open PR before runtime verification env: @@ -1220,6 +1245,7 @@ jobs: - name: Capture exact runtime Namespace UID before verification id: capture-runtime-namespace env: + KUBECONFIG: ${{ runner.temp }}/preview-namespace-manager.kubeconfig PR_NUMBER: ${{ needs.validate-target.outputs.pr_number }} EXPECTED_BASE_SHA: ${{ needs.validate-target.outputs.base_sha }} EXPECTED_HEAD_SHA: ${{ needs.validate-target.outputs.head_sha }} @@ -1293,6 +1319,10 @@ jobs: - name: Wait for exact controller identity projection if: ${{ needs.validate-target.outputs.certificate_identity_mode == 'hosted-controller' }} + env: + KUBECONFIG: ${{ runner.temp }}/preview-runtime.kubeconfig + NAMESPACE_KUBECONFIG: ${{ runner.temp }}/preview-namespace-manager.kubeconfig + IDENTITY_KUBECONFIG: ${{ runner.temp }}/hosted-identity-requester.kubeconfig run: | bash ./dev-tools/hosted/preview/wait-for-hosted-identity.sh \ "pr-${{ needs.validate-target.outputs.pr_number }}" \ @@ -1305,6 +1335,7 @@ jobs: - name: Wait for runtime rollouts env: + KUBECONFIG: ${{ runner.temp }}/preview-runtime.kubeconfig RUNTIME_NAMESPACE: ${{ needs.validate-target.outputs.namespace }} run: | set -euo pipefail @@ -1315,6 +1346,7 @@ jobs: id: runtime-port if: ${{ needs.validate-target.outputs.exposure_mode == 'public' }} env: + KUBECONFIG: ${{ runner.temp }}/preview-runtime.kubeconfig RUNTIME_NAMESPACE: ${{ needs.validate-target.outputs.namespace }} run: | set -euo pipefail @@ -1378,10 +1410,182 @@ jobs: PREVIEW_BASE_URL: https://${{ needs.validate-target.outputs.hostname }} SMOKE_TELNET_HOST: ${{ needs.validate-target.outputs.hostname }} TCP_PORT: ${{ steps.runtime-port.outputs.port }} + CERTIFICATE_IDENTITY_MODE: ${{ needs.validate-target.outputs.certificate_identity_mode }} run: | + set -euo pipefail + umask 077 : "${TCP_PORT:?runtime-port step must provide the allocated NodePort}" + if [[ "$CERTIFICATE_IDENTITY_MODE" == hosted-controller ]]; then + export SMOKE_SEMANTIC_OUT="$RUNNER_TEMP/preview-telnet-semantics.json" + fi + export SMOKE_LOGIN_EMAIL="$HOSTED_PLAYABLE_EMAIL" + export SMOKE_PASSWORD="$HOSTED_PLAYABLE_PASSWORD" + export SMOKE_WORLD="$HOSTED_PLAYABLE_WORLD" + export SMOKE_REALM="$HOSTED_PLAYABLE_REALM" + export SMOKE_CHARACTER="$HOSTED_PLAYABLE_CHARACTER" bash ./dev-tools/hosted/shared/hosted-login-look-smoke.sh + - name: Smoke first-party hosted WSS and compare Telnet LOOK + if: ${{ needs.validate-target.outputs.exposure_mode == 'public' && needs.validate-target.outputs.certificate_identity_mode == 'hosted-controller' }} + env: + PREVIEW_HOSTNAME: ${{ needs.validate-target.outputs.hostname }} + TELNET_SEMANTIC_OUT: ${{ runner.temp }}/preview-telnet-semantics.json + WSS_SEMANTIC_OUT: ${{ runner.temp }}/preview-wss-semantics.json + run: | + set -euo pipefail + umask 077 + room_id="$(jq -er '.lookRoomId | select(type == "string" and length > 0)' "$TELNET_SEMANTIC_OUT")" + python3 ./dev-tools/hosted/shared/hosted-websocket-playable-smoke.py \ + --gateway-base "https://${PREVIEW_HOSTNAME}" \ + --auth-base "https://${PREVIEW_HOSTNAME}" \ + --auth-prefix "/api/account" \ + --websocket-url "wss://${PREVIEW_HOSTNAME}/ws/game" \ + --origin "https://${PREVIEW_HOSTNAME}" \ + --readiness-url "" \ + --revoke-url "" \ + --username "$HOSTED_PLAYABLE_EMAIL" \ + --password "$HOSTED_PLAYABLE_PASSWORD" \ + --world "$HOSTED_PLAYABLE_WORLD" \ + --realm "$HOSTED_PLAYABLE_REALM" \ + --character "$HOSTED_PLAYABLE_CHARACTER" \ + --expected-room-id "$room_id" \ + --reconnect > "$WSS_SEMANTIC_OUT" + jq -e --arg expected "$room_id" \ + '.transport == "first-party-wss" and .classification == "diagnostic-operator-smoke" and .steps == ["LOGIN", "PLAY", "LOOK"] and .lookRoomId == $expected and .sessions == 2 and .logout == false and .reconnect == true and .replayRejected == true' \ + "$WSS_SEMANTIC_OUT" >/dev/null + + - name: Revalidate exact source binding and runtime Namespace UID before diagnostics + env: + GH_TOKEN: ${{ github.token }} + KUBECONFIG: ${{ runner.temp }}/preview-namespace-manager.kubeconfig + PR_NUMBER: ${{ needs.validate-target.outputs.pr_number }} + EXPECTED_HEAD_SHA: ${{ needs.validate-target.outputs.head_sha }} + EXPECTED_BASE_SHA: ${{ needs.validate-target.outputs.base_sha }} + EXPECTED_MERGE_SHA: ${{ needs.validate-target.outputs.merge_sha }} + RUNTIME_NAMESPACE: ${{ needs.validate-target.outputs.namespace }} + EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID: ${{ needs.deploy-runtime.outputs.runtime_namespace_uid }} + CAPTURED_RUNTIME_NAMESPACE_UID: ${{ steps.capture-runtime-namespace.outputs.uid }} + run: | + set -euo pipefail + bash ./dev-tools/hosted/preview/revalidate-preview-source-binding.sh \ + "$PR_NUMBER" "$EXPECTED_HEAD_SHA" "$EXPECTED_BASE_SHA" "$EXPECTED_MERGE_SHA" \ + "before diagnostics" + [[ "$RUNTIME_NAMESPACE" == "pr-${PR_NUMBER}" ]] || { + echo "::error title=Invalid preview runtime namespace::Expected pr-${PR_NUMBER}." >&2 + exit 1 + } + [[ -n "$EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID" ]] || { + echo "::error title=Missing deployed preview runtime Namespace UID::The deploy job did not publish its post-apply Namespace UID." >&2 + exit 1 + } + [[ "$CAPTURED_RUNTIME_NAMESPACE_UID" == "$EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID" ]] || { + echo "::error title=Preview runtime Namespace UID handoff changed::Expected ${EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID}; captured ${CAPTURED_RUNTIME_NAMESPACE_UID:-empty}." >&2 + exit 1 + } + namespace_json="$(kubectl get namespace "$RUNTIME_NAMESPACE" --ignore-not-found -o json)" + [[ -n "$namespace_json" ]] || { + echo "::error title=Preview runtime namespace UID fence failed::Namespace ${RUNTIME_NAMESPACE} is absent." >&2 + exit 1 + } + if ! observed_uid="$(jq -er \ + --arg expected_namespace "$RUNTIME_NAMESPACE" \ + --arg expected_pr_number "$PR_NUMBER" \ + --arg expected_head_sha "$EXPECTED_HEAD_SHA" \ + '( + .metadata as $metadata + | ($metadata.labels // {}) as $labels + | ($metadata.annotations // {}) as $annotations + | select($metadata.name == $expected_namespace) + | select($metadata.uid | type == "string" and length > 0) + | select($labels["firemud.dev/preview"] == "true") + | select($labels["firemud.dev/pr-number"] == $expected_pr_number) + | select($annotations["firemud.dev/requested-preview-head-sha"] == $expected_head_sha) + | select($annotations["firemud.dev/last-preview-head-sha"] == $expected_head_sha) + | $metadata.uid + )' <<<"$namespace_json")"; then + echo "::error title=Preview runtime namespace UID fence failed::Namespace ${RUNTIME_NAMESPACE} is absent or no longer has canonical ownership and head annotations." >&2 + exit 1 + fi + [[ "$observed_uid" == "$EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID" ]] || { + echo "::error title=Preview runtime namespace UID changed::Expected ${EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID}; observed ${observed_uid}." >&2 + exit 1 + } + + - name: Write bounded hosted playable diagnostic evidence + if: ${{ needs.validate-target.outputs.exposure_mode == 'public' && needs.validate-target.outputs.certificate_identity_mode == 'hosted-controller' }} + env: + NAMESPACE_KUBECONFIG: ${{ runner.temp }}/preview-namespace-manager.kubeconfig + IDENTITY_KUBECONFIG: ${{ runner.temp }}/hosted-identity-requester.kubeconfig + RUNTIME_KUBECONFIG: ${{ runner.temp }}/preview-runtime.kubeconfig + PR_NUMBER: ${{ needs.validate-target.outputs.pr_number }} + BASE_SHA: ${{ needs.validate-target.outputs.base_sha }} + HEAD_SHA: ${{ needs.validate-target.outputs.head_sha }} + MERGE_SHA: ${{ needs.validate-target.outputs.merge_sha }} + IMAGE_TAG: ${{ needs.validate-target.outputs.image_tag }} + RUNTIME_NAMESPACE: ${{ needs.validate-target.outputs.namespace }} + run: | + set -euo pipefail + umask 077 + evidence_dir="$(mktemp -d "$RUNNER_TEMP/preview-playable-evidence.XXXXXX")" + trap 'rm -f -- "$evidence_dir/namespace.json" "$evidence_dir/identity.json" "$evidence_dir/pods.json"; rmdir -- "$evidence_dir"' EXIT + kubectl --kubeconfig "$NAMESPACE_KUBECONFIG" get namespace "$RUNTIME_NAMESPACE" -o json > "$evidence_dir/namespace.json" + kubectl --kubeconfig "$IDENTITY_KUBECONFIG" -n firemud-system get hostedenvironmentidentity "$RUNTIME_NAMESPACE" -o json > "$evidence_dir/identity.json" + kubectl --kubeconfig "$RUNTIME_KUBECONFIG" -n "$RUNTIME_NAMESPACE" get pods -o json > "$evidence_dir/pods.json" + python3 ./dev-tools/hosted/preview/write-playable-proof.py \ + --pr-number "$PR_NUMBER" --base-sha "$BASE_SHA" --head-sha "$HEAD_SHA" \ + --merge-sha "$MERGE_SHA" --image-tag "$IMAGE_TAG" \ + --namespace-json "$evidence_dir/namespace.json" \ + --identity-json "$evidence_dir/identity.json" \ + --pods-json "$evidence_dir/pods.json" \ + --telnet-outcome passed --wss-outcome passed \ + > "$RUNNER_TEMP/preview-playable-proof.json" + + - name: Revalidate exact source binding and runtime Namespace UID after diagnostic evidence + env: + GH_TOKEN: ${{ github.token }} + KUBECONFIG: ${{ runner.temp }}/preview-namespace-manager.kubeconfig + PR_NUMBER: ${{ needs.validate-target.outputs.pr_number }} + EXPECTED_HEAD_SHA: ${{ needs.validate-target.outputs.head_sha }} + EXPECTED_BASE_SHA: ${{ needs.validate-target.outputs.base_sha }} + EXPECTED_MERGE_SHA: ${{ needs.validate-target.outputs.merge_sha }} + RUNTIME_NAMESPACE: ${{ needs.validate-target.outputs.namespace }} + EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID: ${{ needs.deploy-runtime.outputs.runtime_namespace_uid }} + IMAGE_TAG: ${{ needs.validate-target.outputs.image_tag }} + run: | + set -euo pipefail + bash ./dev-tools/hosted/preview/revalidate-preview-source-binding.sh \ + "$PR_NUMBER" "$EXPECTED_HEAD_SHA" "$EXPECTED_BASE_SHA" "$EXPECTED_MERGE_SHA" \ + "after diagnostics" + [[ "$RUNTIME_NAMESPACE" == "pr-${PR_NUMBER}" ]] || exit 1 + observed_uid="$(kubectl get namespace "$RUNTIME_NAMESPACE" -o json \ + | jq -er --arg pr "$PR_NUMBER" --arg base "$EXPECTED_BASE_SHA" \ + --arg head "$EXPECTED_HEAD_SHA" --arg merge "$EXPECTED_MERGE_SHA" \ + --arg image "$IMAGE_TAG" \ + '.metadata as $m | select($m.labels["firemud.dev/preview"] == "true") + | select($m.labels["firemud.dev/pr-number"] == $pr) + | select($m.annotations["firemud.dev/requested-preview-base-sha"] == $base) + | select($m.annotations["firemud.dev/requested-preview-head-sha"] == $head) + | select($m.annotations["firemud.dev/requested-preview-merge-sha"] == $merge) + | select($m.annotations["firemud.dev/requested-preview-image-tag"] == $image) + | select($m.annotations["firemud.dev/last-preview-base-sha"] == $base) + | select($m.annotations["firemud.dev/last-preview-head-sha"] == $head) + | select($m.annotations["firemud.dev/last-preview-merge-sha"] == $merge) + | select($m.annotations["firemud.dev/last-preview-image-tag"] == $image) + | $m.uid | select(type == "string" and length > 0)')" + [[ "$observed_uid" == "$EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID" ]] || { + echo "::error title=Preview runtime Namespace UID changed after diagnostics::Expected ${EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID}; observed ${observed_uid}." >&2 + exit 1 + } + + - name: Upload bounded hosted playable diagnostic evidence + if: ${{ needs.validate-target.outputs.exposure_mode == 'public' && needs.validate-target.outputs.certificate_identity_mode == 'hosted-controller' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: hosted-playable-diagnostic-pr-${{ needs.validate-target.outputs.pr_number }}-${{ needs.validate-target.outputs.merge_sha }} + path: ${{ runner.temp }}/preview-playable-proof.json + if-no-files-found: error + retention-days: 7 + - name: Publish trusted preview verification failure if: ${{ !cancelled() && failure() }} uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 @@ -1395,6 +1599,7 @@ jobs: PREVIEW_EXPOSURE_MODE: ${{ needs.validate-target.outputs.exposure_mode }} RUNTIME_NAMESPACE: ${{ needs.validate-target.outputs.namespace }} EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID: ${{ needs.deploy-runtime.outputs.runtime_namespace_uid }} + KUBECONFIG: ${{ runner.temp }}/preview-namespace-manager.kubeconfig with: script: | const { execFileSync } = require("node:child_process"); @@ -1402,7 +1607,6 @@ jobs: `${process.env.GITHUB_WORKSPACE}/dev-tools/hosted/preview/publish-preview-comment.js` ); let namespaceJson = ""; - let kubectlError = null; try { namespaceJson = execFileSync( "kubectl", @@ -1416,43 +1620,67 @@ jobs: ], { encoding: "utf8" }, ); - } catch (error) { - kubectlError = error; + } catch { + core.warning( + "Skipping stale preview verification failure publication because the current Namespace could not be read.", + ); + return; } - if (kubectlError) { + if (!namespaceJson.trim()) { + core.notice( + "Skipping stale preview verification failure publication because the current Namespace is absent.", + ); + return; + } + let namespace; + try { + namespace = JSON.parse(namespaceJson); + } catch { core.warning( - `Unable to compare the current preview Namespace UID before failure publication; preserving failure reporting: ${kubectlError.message}`, + "Skipping stale preview verification failure publication because current Namespace JSON is malformed.", ); - } else if (namespaceJson.trim()) { - let observedUid = ""; - try { - const namespace = JSON.parse(namespaceJson); - observedUid = - typeof namespace?.metadata?.uid === "string" - ? namespace.metadata.uid - : ""; - } catch (error) { - core.warning( - `Current preview Namespace JSON was malformed before failure publication; preserving failure reporting: ${error.message}`, - ); - } - if ( - observedUid && - process.env.EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID && - observedUid !== process.env.EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID - ) { - core.notice( - `Skipping stale preview verification failure publication because current Namespace UID ${observedUid} differs from this deploy's UID ${process.env.EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID}.`, - ); - return; - } + return; + } + const metadata = namespace?.metadata; + const labels = metadata?.labels; + const annotations = metadata?.annotations; + const expectedTuple = { + "firemud.dev/requested-preview-base-sha": process.env.PREVIEW_BASE_SHA, + "firemud.dev/requested-preview-head-sha": process.env.PREVIEW_HEAD_SHA, + "firemud.dev/requested-preview-merge-sha": process.env.PREVIEW_MERGE_SHA, + "firemud.dev/requested-preview-image-tag": process.env.PREVIEW_IMAGE_TAG, + "firemud.dev/last-preview-base-sha": process.env.PREVIEW_BASE_SHA, + "firemud.dev/last-preview-head-sha": process.env.PREVIEW_HEAD_SHA, + "firemud.dev/last-preview-merge-sha": process.env.PREVIEW_MERGE_SHA, + "firemud.dev/last-preview-image-tag": process.env.PREVIEW_IMAGE_TAG, + }; + const expectedNamespace = `pr-${process.env.PREVIEW_PR_NUMBER}`; + const expectedUid = process.env.EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID; + if ( + process.env.RUNTIME_NAMESPACE !== expectedNamespace || + metadata?.name !== expectedNamespace || + typeof metadata?.uid !== "string" || + metadata.uid.length === 0 || + !expectedUid || + metadata.uid !== expectedUid || + labels?.["firemud.dev/preview"] !== "true" || + labels?.["firemud.dev/pr-number"] !== process.env.PREVIEW_PR_NUMBER || + Object.values(expectedTuple).some((value) => typeof value !== "string" || !value) || + Object.entries(expectedTuple).some( + ([key, value]) => annotations?.[key] !== value, + ) + ) { + core.notice( + "Skipping stale preview verification failure publication because the current Namespace UID or requested/deployed source tuple no longer matches this deploy.", + ); + return; } await publishPreviewComment({ github, context, core, mode: "failure", - markerPolicy: "replace", + markerPolicy: "preserve-reclaimed", statePolicy: "expected-open", telnetPort: "unavailable", failureStage: "verify-runtime", @@ -1462,7 +1690,13 @@ jobs: - name: Remove runtime kubeconfig if: ${{ always() }} run: | - rm -f -- "$RUNNER_TEMP/preview-runtime.kubeconfig" + rm -f -- \ + "$RUNNER_TEMP/preview-namespace-manager.kubeconfig" \ + "$RUNNER_TEMP/preview-runtime.kubeconfig" \ + "$RUNNER_TEMP/hosted-identity-requester.kubeconfig" \ + "$RUNNER_TEMP/preview-telnet-semantics.json" \ + "$RUNNER_TEMP/preview-wss-semantics.json" \ + "$RUNNER_TEMP/preview-playable-proof.json" publish-preview-proof: name: Publish Verified Hosted Preview Proof @@ -1621,6 +1855,7 @@ jobs: PREVIEW_IMAGE_TAG: ${{ needs.validate-target.outputs.image_tag }} PREVIEW_HOSTNAME: ${{ needs.validate-target.outputs.hostname }} PREVIEW_EXPOSURE_MODE: ${{ needs.validate-target.outputs.exposure_mode }} + RUNTIME_NAMESPACE: ${{ needs.validate-target.outputs.namespace }} EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID: ${{ needs.deploy-runtime.outputs.runtime_namespace_uid }} with: script: | @@ -1635,41 +1870,74 @@ jobs: [ "get", "namespace", - `pr-${process.env.PREVIEW_PR_NUMBER}`, + process.env.RUNTIME_NAMESPACE, "--ignore-not-found", "-o", "json", ], { encoding: "utf8" }, ); - } catch (error) { + } catch { core.warning( - `Unable to compare the current preview Namespace UID before proof-failure publication; preserving failure reporting: ${error.message}`, + "Skipping stale preview proof failure publication because the current Namespace could not be read.", ); + return; } - if (namespaceJson.trim()) { - try { - const namespace = JSON.parse(namespaceJson); - const observedUid = namespace?.metadata?.uid; - const expectedUid = process.env.EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID; - if (observedUid && expectedUid && observedUid !== expectedUid) { - core.notice( - `Skipping stale preview proof failure publication because current Namespace UID ${observedUid} differs from this deploy's UID ${expectedUid}.`, - ); - return; - } - } catch (error) { - core.warning( - `Current preview Namespace JSON was malformed before proof-failure publication; preserving failure reporting: ${error.message}`, - ); - } + if (!namespaceJson.trim()) { + core.notice( + "Skipping stale preview proof failure publication because the current Namespace is absent.", + ); + return; + } + let namespace; + try { + namespace = JSON.parse(namespaceJson); + } catch { + core.warning( + "Skipping stale preview proof failure publication because current Namespace JSON is malformed.", + ); + return; + } + const metadata = namespace?.metadata; + const labels = metadata?.labels; + const annotations = metadata?.annotations; + const expectedTuple = { + "firemud.dev/requested-preview-base-sha": process.env.PREVIEW_BASE_SHA, + "firemud.dev/requested-preview-head-sha": process.env.PREVIEW_HEAD_SHA, + "firemud.dev/requested-preview-merge-sha": process.env.PREVIEW_MERGE_SHA, + "firemud.dev/requested-preview-image-tag": process.env.PREVIEW_IMAGE_TAG, + "firemud.dev/last-preview-base-sha": process.env.PREVIEW_BASE_SHA, + "firemud.dev/last-preview-head-sha": process.env.PREVIEW_HEAD_SHA, + "firemud.dev/last-preview-merge-sha": process.env.PREVIEW_MERGE_SHA, + "firemud.dev/last-preview-image-tag": process.env.PREVIEW_IMAGE_TAG, + }; + const expectedNamespace = `pr-${process.env.PREVIEW_PR_NUMBER}`; + const expectedUid = process.env.EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID; + if ( + process.env.RUNTIME_NAMESPACE !== expectedNamespace || + metadata?.name !== expectedNamespace || + typeof metadata?.uid !== "string" || + metadata.uid.length === 0 || + !expectedUid || + metadata.uid !== expectedUid || + labels?.["firemud.dev/preview"] !== "true" || + labels?.["firemud.dev/pr-number"] !== process.env.PREVIEW_PR_NUMBER || + Object.values(expectedTuple).some((value) => typeof value !== "string" || !value) || + Object.entries(expectedTuple).some( + ([key, value]) => annotations?.[key] !== value, + ) + ) { + core.notice( + "Skipping stale preview proof failure publication because the current Namespace UID or requested/deployed source tuple no longer matches this deploy.", + ); + return; } await publishPreviewComment({ github, context, core, mode: "failure", - markerPolicy: "replace", + markerPolicy: "preserve-reclaimed", statePolicy: "expected-open", telnetPort: "unavailable", failureStage: "verify-runtime", diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/design/architecture/infrastructure/deployment-environments.md b/design/architecture/infrastructure/deployment-environments.md index 562c9f6907..e3e784e4cc 100644 --- a/design/architecture/infrastructure/deployment-environments.md +++ b/design/architecture/infrastructure/deployment-environments.md @@ -357,7 +357,7 @@ The hosted identity controller's egress boundary is exact-destination and operat - Preview deploys currently reset the namespace before each Helm apply, then reseed the minimum bootstrap state needed for reviewer proof. Within one deployed preview instance, PostgreSQL, MinIO/object storage, and other stateful components persist across normal pod restarts and VM reboot, but preview state does not currently persist across preview redeploys. - Preview state is not backed up and is not durable beyond the single preview node. If the node or its attached storage is lost, preview state is lost. - The initial Hetzner/k3s sizing target is one reliably usable full-stack preview on an 8 GB shared-CPU x86 VM. A second concurrent preview is best-effort only and may fail to deploy if capacity is exhausted. -- Open, mergeable, non-dependency-bot same-repository pull requests targeting `main` or `develop` request preview allocation automatically. A stacked pull request whose base is another current branch in the same repository is eligible only while it carries the maintainer-controlled `preview:priority` label; forks and dependency-bot updates remain ineligible. Ordinary allocation in the bounded two-slot pool is first-come at the serialized allocation boundary while capacity remains available; GitHub's raw job-scheduling order is not itself an allocation guarantee. The priority label lets a later priority request claim a free slot or reclaim the oldest ordinary preview, but never another currently priority-labelled preview. Allocation, deployment, hosted proof, reclaim, and cleanup share one durable bounded non-cancelling lifecycle queue so a running proof is not deleted underneath itself and normal waiting lifecycle work uses GitHub's expanded queue instead of its replaceable single pending slot. Both target and victim label state are re-read immediately before reclaim. Removing the label from an ordinary `main`/`develop` pull request returns its environment to ordinary status; removing it from a stacked pull request makes that preview ineligible and permits trusted cleanup. A displaced pull request keeps its ordinary CI and historical preview result, while its current hosted status reports that no environment is allocated. +- Open, mergeable, non-dependency-bot same-repository pull requests targeting `main` or `develop` request preview allocation automatically. A stacked pull request whose base is another current branch in the same repository is eligible only while it carries the maintainer-controlled `preview:priority` label; forks and dependency-bot updates remain ineligible. Ordinary allocation in the bounded two-slot pool is first-come at the serialized allocation boundary while capacity remains available; GitHub's raw job-scheduling order is not itself an allocation guarantee. The priority label lets a later priority request claim a free slot or reclaim the oldest ordinary preview, but never another currently priority-labelled preview. Allocation, deployment, final proof publication, reclaim, and cleanup share one durable bounded non-cancelling lifecycle queue so the protected final proof mutation is not deleted underneath itself. Post-apply verification and diagnostics run outside that queue and may interleave with lifecycle work under the exact source and Namespace UID fences described in [Hosted identity lifecycle](#hosted-identity-lifecycle). Normal waiting lifecycle work uses GitHub's expanded queue instead of its replaceable single pending slot. Both target and victim label state are re-read immediately before reclaim. Removing the label from an ordinary `main`/`develop` pull request returns its environment to ordinary status; removing it from a stacked pull request makes that preview ineligible and permits trusted cleanup. A displaced pull request keeps its ordinary CI and historical preview result, while its current hosted status reports that no environment is allocated. - Each successfully allocated eligible preview receives its own namespace and holds a bounded renewable visible lease. An ordinary active lease is protected except for the explicit priority rule above; a priority-labelled active lease is not silently evicted, while an expired lease may be reclaimed even if the pull request remains open. A request that is eligible but not allocated, including because capacity is exhausted or every slot is priority-protected, reports `preview_unavailable`, not passed. - Any review claiming hosted proof requires successful evidence for its current base SHA, head SHA, two-parent merge SHA, and selected immutable image tag. A parent advance invalidates the prior proof even when the child head is unchanged. - Preview runtime namespaces are removed when the pull request closes or merges, is explicitly released, or its lease expires; the retained identity namespace remains until the trusted lifecycle explicitly retires it under the exact runtime-`NotFound` rule. diff --git a/design/architecture/microservices/spring-cloud-gateway/README.md b/design/architecture/microservices/spring-cloud-gateway/README.md index 3f30eba183..d386efd828 100644 --- a/design/architecture/microservices/spring-cloud-gateway/README.md +++ b/design/architecture/microservices/spring-cloud-gateway/README.md @@ -32,7 +32,7 @@ An OpenAPI specification for these REST endpoints lives in `services/spring-clou - `readiness` is route-admission safety. For the currently implemented gameplay slice, the gateway is ready only when: - baseline route configuration is loaded; and - the `/ws/game/**` gameplay path can pass the same admission filters, upgrade, and forward to Game Session successfully enough for new gameplay sockets to be admitted. -- Public Gateway readiness remains scoped to public/gameplay route safety. The dedicated TCP Proxy TLS listener has route-specific admission and is proved separately by reaching readiness through that listener; its `tcpProxyTlsListenerReadiness` indicator reports the listener state without making the public readiness group depend on it. Invalid listener, environment, trust-profile, expiry, or TLS-material configuration still fails startup before either listener can serve traffic. +- Public Gateway readiness remains scoped to public/gameplay route safety. The dedicated TCP Proxy TLS listener has route-specific admission and is proved separately by reaching readiness through that listener; its `tcpProxyTlsListenerReadiness` indicator reports the listener state without making the public readiness group depend on it. The Gate 2 candidate returns unavailable for new internal bridge requests and internal-listener readiness when watched TLS material is unhealthy, while liveness and already-established bridges remain separate. Invalid listener, environment, trust-profile, expiry, or startup TLS-material configuration still fails startup before either listener can serve traffic. - The gameplay-route canary is bounded and operation-shaped. It validates the actual `/ws/game/**` upgrade path with an explicit short timeout rather than relying on unrelated ping-style checks or long retry budgets. In player-facing environments, connect-token replay protection is part of admission safety; if the replay-protection store is unavailable and the route would fail closed with `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`, the gameplay route is not ready. - Retry filters are resilience mechanisms, not readiness compensation. A gateway that still needs startup retries to survive ordinary new gameplay admission is not ready. - Readiness transition observability uses the shared contract from [Deployment Environments](../../infrastructure/deployment-environments.md): `firemud.readiness.current`, `firemud.readiness.transitions`, and structured logs keyed by the curated dependency name `gameplayRoute`. @@ -46,7 +46,7 @@ This document describes the behaviour of Spring Cloud Gateway in its target arch | Baseline route authority | The released declarative route catalog is the single player-facing route authority and is imported at startup. | Not converged: current baseline routes are Java-owned in `CanonicalGatewayRoutesConfiguration`; the target `routes.yml` resource and import do not exist yet. | | Dynamic route management | REST and gRPC route mutation APIs are dev/test-only overrides on top of the released route catalog. Player-facing environments reject dynamic mutation configuration at startup; production operators have diagnostics only, and route changes use the separately accepted declarative deployment workflow. Any future production runtime route-control plane requires a new architecture decision and must remain consistent with the [canonical authorization route matrix](../../system-architecture-authz-route-matrix.md). | Not converged: mutation components are currently unconditional and lack the required profile isolation, startup rejection, protected-route validation, and destination/predicate/filter allowlists. | | Rate limiting and Redis wiring | Gateway rate limiting uses Spring Cloud Gateway `RequestRateLimiter` backed by the Cache/Rate-Limit Redis role, with gameplay abuse policy split across Gateway, TCP Proxy, and Game Session. | Implemented. | -| TCP Proxy bridge admission | Traffic from the TCP Proxy Service always targets `/ws/game/**`; player-facing bridge authority requires the exclusive environment-bound mTLS identity contract in [ADR 0169](../../decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md). | Gateway runtime now provides a separately bound TLS listener, requires CA-validated client certificates for certificate-bound profiles, enforces exact URI SAN, expiring DNS migration, expiring leaf fingerprint, or development-only TLS/CIDR selection exclusively, and promotes bridge headers only after the selected trust check. The #2713 Helm candidate wires the private Gateway ↔ TCP Proxy bridge with its dedicated Service, separate Gateway-server/TCP-Proxy-client Secret mounts and environment, and exact-port NetworkPolicy. Private bridge live hosted-preview proof remains pending; controller-owned identity issuance/projection, live peer-handshake, rotation/readiness, emergency withdrawal, and player-facing traffic-authorization proof remain incomplete. Public Telnet TLS and transport-complete/playable hosted proof remain the #2795 delivery slice. TLS material is loaded at listener startup; live renewal reload is not implemented. | +| TCP Proxy bridge admission | Traffic from the TCP Proxy Service always targets `/ws/game/**`; player-facing bridge authority requires the exclusive environment-bound mTLS identity contract in [ADR 0169](../../decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md). | Gateway runtime now provides a separately bound TLS listener, requires CA-validated client certificates for certificate-bound profiles, enforces exact URI SAN, expiring DNS migration, expiring leaf fingerprint, or development-only TLS/CIDR selection exclusively, and promotes bridge headers only after the selected trust check. The #2713 Helm candidate wires the private Gateway ↔ TCP Proxy bridge with its dedicated Service, separate Gateway-server/TCP-Proxy-client Secret mounts and environment, and exact-port NetworkPolicy. The Gate 2 candidate adds watched listener certificate/key and client-CA reload with local tests, but private hosted peer-handshake, served-material convergence/readiness, emergency withdrawal, and player-facing traffic-authorization proof remain incomplete. Public Telnet TLS and transport-complete/playable hosted proof remain the #2795 delivery slice. | | WebSocket close and handshake observability | Target-only typed Game Session → Gateway lifecycle intent feeds Gateway’s sole external WebSocket close-translation owner: `logout`, `session_replaced`, `service_restart`, `idle_timeout`, `policy_violation`, `internal_error`, and `backend_unavailable` are bounded top-level classes; bridge closes also carry `bridge_shutdown_class=planned_drain\|valid_upstream_close\|unattributed_failure` and optional diagnostic subreason. | Partially implemented at the current bridge and first-party handshake boundary. The typed lifecycle-intent contract is not implemented or versioned; unknown or absent intent must fail closed as `internal_error` at the public WebSocket boundary. `session_replaced`/`service_restart` convergence, neutral valid-upstream attribution, ADR 0013's elapsed-time cutoff, bounded input stall/rebind path, and terminal-versus-rebindable upstream classification remain gaps. See [Gateway Architecture](../../system-architecture-gateway.md#canonical-close-translation-matrix). | ## Documentation Map diff --git a/design/architecture/microservices/spring-cloud-gateway/configuration.md b/design/architecture/microservices/spring-cloud-gateway/configuration.md index 736a4bf568..791f165c9d 100644 --- a/design/architecture/microservices/spring-cloud-gateway/configuration.md +++ b/design/architecture/microservices/spring-cloud-gateway/configuration.md @@ -4,7 +4,7 @@ The current Gateway `RequestRateLimiter` derives keys from raw client IP rather than the target versioned opaque subject hash. Canonicalization, shared helper adoption, HMAC key delivery/rotation, privacy and cardinality proof, and legacy-key expiry remain implementation work. -The dedicated TCP Proxy TLS listener and exclusive ADR 0169 trust-profile selection are implemented in Gateway runtime. The #2713 Helm candidate wires the private Gateway ↔ TCP Proxy bridge with the listener Service, credential mounts and environment, TCP Proxy client credential consumption, and exact-port NetworkPolicy. Private bridge live hosted-preview proof remains pending. Controller-owned identity issuance/projection, rotation/readiness, emergency withdrawal evidence, and exact-head hosted peer-handshake proof remain separate incomplete work. Public Telnet TLS and transport-complete/playable hosted proof remain the #2795 delivery slice. Listener TLS material is loaded at startup; live certificate renewal reload is not implemented, and emergency withdrawal still requires deployment-controller proof that every old pod and established bridge was forcibly terminated. +The dedicated TCP Proxy TLS listener and exclusive ADR 0169 trust-profile selection are implemented in Gateway runtime. The #2713 Helm candidate wires the private Gateway ↔ TCP Proxy bridge with the listener Service, credential mounts and environment, TCP Proxy client credential consumption, and exact-port NetworkPolicy. The Gate 2 candidate adds live projected listener certificate/key and client-CA reload for new handshakes with local tests; private bridge live hosted-preview proof remains pending. Controller-owned identity issuance/projection, served rotation/readiness, emergency withdrawal evidence, and exact-head hosted peer-handshake proof remain separate incomplete work. Public Telnet TLS and transport-complete/playable hosted proof remain the #2795 delivery slice. Emergency withdrawal still requires deployment-controller proof that every old pod and established bridge was forcibly terminated. ## Configuration Sources @@ -56,7 +56,7 @@ The hosted Gateway pod also has default-deny egress. Its only permitted destinat Certificate-bound profiles require a peer certificate that chains to the configured client CA, is currently valid, includes the `clientAuth` extended-key usage, and satisfies only the selected identity predicate. Settings for any inactive profile fail startup. `development_cidr` is accepted only for `local-dev` or `isolated-test` without the Spring `prod` profile. The legacy plaintext test-header mode remains limited to explicit `test`, `dev`, or `local` Spring profiles and cannot coexist with the dedicated listener; it is not a hosted fallback. -An explicit certificate-instance revocation, identity removal, or emergency trust withdrawal of otherwise-unexpired material is a disruptive boundary with the current startup-loaded listener. Unlike runtime profile expiry, the deployment controller or authorized control path must terminate every old Gateway pod and its established TCP Proxy bridges even when replacement pods remain unready, so stale in-memory trust cannot continue serving. A rollout request by itself is not proof of withdrawal; completion evidence must show that no old listener process or bridge remains. Ordinary certificate renewal and live trust reload remain unimplemented for this listener. +An explicit certificate-instance revocation, identity removal, or emergency trust withdrawal of otherwise-unexpired material is a disruptive boundary even with the Gate 2 candidate's live projected-material reload: an old process may retain an established bridge or previously accepted trust. Unlike runtime profile expiry, the deployment controller or authorized control path must terminate every old Gateway pod and its established TCP Proxy bridges even when replacement pods remain unready, so stale in-memory trust cannot continue serving. A rollout request by itself is not proof of withdrawal; completion evidence must show that no old listener process or bridge remains. Ordinary renewal reload has local candidate tests, but hosted served-material convergence is not yet proved. ## Route State and Baseline Configuration diff --git a/design/architecture/microservices/tcp-proxy-service/configuration.md b/design/architecture/microservices/tcp-proxy-service/configuration.md index fb513a7807..829e3112a0 100644 --- a/design/architecture/microservices/tcp-proxy-service/configuration.md +++ b/design/architecture/microservices/tcp-proxy-service/configuration.md @@ -107,9 +107,9 @@ In production, the TCP Proxy Service connects to Spring Cloud Gateway over `wss: Ordinary renewal atomically replaces the client used for new bridges and readiness probes while already-negotiated WebSocket sessions finish naturally. This watcher behavior does not implement explicit certificate revocation, identity removal, or emergency trust withdrawal. For emergency withdrawal, the hosted identity controller must first remove the withdrawn identity from Gateway's active trust profile, then disruptively terminate the old Gateway pods and their established bridges, even when replacement credentials or replacement pods are unavailable; requesting a rollout without proving the old bridges stopped is not sufficient. -The aggregate `tlsCertificateReload` remains a default-health and alerting surface, not a wholesale readiness dependency. TCP Proxy’s route-specific `trafficAdmissionReadiness` includes Gateway bridge readiness and fails closed for new Telnet sessions when that path’s watcher or active client material is unusable; unrelated watcher loss does not close this route. Established sessions remain usable while their negotiated path is safe, and controller-owned identity withdrawal remains a disruptive termination boundary. The canonical policy is in [Kubernetes Health Monitoring](../../infrastructure/deployment-environments.md#kubernetes-health-monitoring). +The aggregate `tlsCertificateReload` remains a default-health and alerting surface, not a wholesale readiness dependency. TCP Proxy’s route-specific `trafficAdmissionReadiness` includes Gateway bridge readiness and, for the direct TLS listener, the Telnet server certificate watcher; it fails closed for new Telnet sessions when an admission-critical watcher or active client material is unusable. Unrelated watcher loss does not close this route. Established sessions remain usable while their negotiated path is safe, and controller-owned identity withdrawal remains a disruptive termination boundary. The canonical policy is in [Kubernetes Health Monitoring](../../infrastructure/deployment-environments.md#kubernetes-health-monitoring). -The shared readiness post-processor enables TLS reload gating through `firemud.tls.readiness-gate.enabled`. TCP Proxy’s `application.yml` defaults this property to `false` when `FIREMUD_TLS_READINESS_GATE_ENABLED` is unset because its aggregate watcher health must not gate actuator readiness; its route-specific `trafficAdmissionReadiness` owns the Gateway bridge readiness decision described above. The default can be overridden when an environment explicitly requires aggregate TLS watcher health to gate readiness. +The shared readiness post-processor enables TLS reload gating through `firemud.tls.readiness-gate.enabled`. TCP Proxy’s `application.yml` defaults this property to `false` when `FIREMUD_TLS_READINESS_GATE_ENABLED` is unset because its aggregate watcher health must not gate actuator readiness; its route-specific `trafficAdmissionReadiness` owns the Gateway bridge and direct Telnet listener readiness decisions described above. Hosted values leave the aggregate flag unset, so unrelated watcher failures do not enter the pod readiness decision through the aggregate gate. A Telnet certificate watcher failure makes `trafficAdmissionReadiness` fail and closes new Telnet admission. The WebSocket client certificate must include the `clientAuth` extended key usage; a certificate with no extended-key-usage extension is rejected rather than treated as unrestricted. This is intentionally decoupled from the proxy’s internal gRPC server certificate profile, which must include `serverAuth`. diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index 116b09b690..22d28fd815 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -13,7 +13,7 @@ Unless otherwise noted, this document describes target-state gateway behavior. C - The target-state declarative `routes.yml` catalog has not yet converged as the implemented route authority. The current authority is the Java `CanonicalGatewayRoutesConfiguration`, with route-specific environment overrides `FIREMUD_GATEWAY_ROUTE_SESSION_URI`, `FIREMUD_GATEWAY_ROUTE_ADMIN_URI`, `FIREMUD_GATEWAY_ROUTE_DESIGN_URI`, `FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI`, and `FIREMUD_GATEWAY_ROUTE_SOCIAL_URI`. These are distinct from the `FIREMUD_SERVICES_*` service-discovery variables used by other microservices. See [Environment Variables & Secrets Management](./infrastructure/environment-and-secrets.md#service-discovery). - **Current Game Design route consequence:** the Java route catalog exposes only `GET /api/design/ping` and `GET /api/design/templates`; it has no coarse `/api/design/**` or `/api/design/assets` mutation route, so edge asset writes are denied. The Game Design owner-side Account hosted-terms/currentness gate is still absent. This route restriction makes no readiness claim; official-hosted asset-upload readiness remains unproved pending the exact Account-owned gate and its proof. - Published `/assets/**` delivery is target-only pending a separate approved public origin/provisioner. The current Gateway route catalog has no `/assets/**` route or asset-store route ID, and private MinIO is not public delivery. The reserved `/assets/**` family remains separate from the first-party static-host `/frontend-assets/**` family. -- The current TCP Proxy → Gateway runtime implements the dedicated internal WSS listener, one environment-bound trust profile selected by the exclusive matcher described by [ADR 0169](./decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md), and TCP Proxy client-credential reload for new bridges. The private Helm candidate is owned by #2713; public activation and proof remain owned by #2795. Gateway listener TLS is loaded at startup and does not support live listener reload. Certificate-bound profiles use mTLS with the exact URI SAN for steady-state player-facing traffic, named expiring DNS migration, or named expiring leaf-fingerprint break-glass; development/test-only `development_cidr` uses TLS without client authentication plus the exact configured source-CIDR predicate. Controller issuance/projection, hosted rotation/readiness proof, emergency withdrawal evidence, and exact-head hosted peer-handshake proof remain incomplete boundaries. +- The current TCP Proxy → Gateway runtime implements the dedicated internal WSS listener, one environment-bound trust profile selected by the exclusive matcher described by [ADR 0169](./decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md), and TCP Proxy client-credential reload for new bridges. The private Helm candidate is owned by #2713; public activation and proof remain owned by #2795. The Gate 2 candidate adds a watched projected Gateway listener certificate/key and client CA for new handshakes, preserving established bridges; local reload tests are not hosted served-certificate or convergence proof. Certificate-bound profiles use mTLS with the exact URI SAN for steady-state player-facing traffic, named expiring DNS migration, or named expiring leaf-fingerprint break-glass; development/test-only `development_cidr` uses TLS without client authentication plus the exact configured source-CIDR predicate. Controller issuance/projection, hosted rotation/readiness proof, emergency withdrawal evidence, and exact-head hosted peer-handshake proof remain incomplete boundaries. - The target replay domain is a Gateway-owned Coordination Redis contract defined by the Redis ownership and recovery documents. Gateway carries its non-secret domain pin in `FIREMUD_GATEWAY_REPLAY_DOMAIN`, which must equal exactly `gateway-connect-token-replay-v1` and is rendered as the fixed `{gateway-connect-token-replay-v1}` hash tag. Startup, target preflight, and migration/reset tooling must reject any other value and prove the same tag across Gateway instances and shared Coordination Redis readback. The current `GameplayHandshakeFilter` still writes only a legacy replay marker through the generic Cache-bound client; it has no browser-deny, readiness, or replay-fence writer. This is migration-only drift: before target admission, the named Coordination client/ACL must be cut over, the legacy state must be inventoried and read back under quarantine, the target contract must be verified, and legacy markers must be retained or explicitly cleaned only after their original acceptance windows expire. - Dynamic REST and gRPC route-management APIs remain local/dev/test-only ephemeral capabilities. The current implementation does not yet enforce the target profile, endpoint isolation, validation, or startup boundary, so these APIs must not be treated as production-safe merely because they exist. - Connect-token carrier parsing, required routing claims, expiry, and Redis replay checks are implemented for `/ws/game/**`, but current claims and the emitted signed context do not carry and prove durable `realmId`, the current carrier path still does not reject duplicate header values or duplicate token cookies, and successful cookie authentication strips the connect-token cookie carrier from the forwarded request. The protected-cookie `/ws/game/**` variant and bootstrap-backed bare `LOGIN` handoff are implemented but non-promotable in player-facing environments until the named Gateway readiness evidence is complete: exact selector-to-`{tenantId, realmId}` resolution and claim/context equality, carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence. The target contract also requires explicit future-`iat` tolerance, `exp` tolerance, and the 30-second `iat`-to-`exp` hard maximum; the current shared `JwtUtil` parser uses JJWT defaults (no configured clock skew), and `GameplayHandshakeFilter` does not yet explicitly enforce those target `iat`/lifetime bounds. These readiness gaps do not mean that the existing signature, claim, expiry, carrier, or replay checks are absent. 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 57052f75f1..b016b48179 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -43,7 +43,7 @@ These links add current decision provenance only; implementation and verificatio - `PO-4.2` / `PO-4.3`: [ADR 0160](../../architecture/decisions/adr-0160-staged-profile-aware-player-experience-slo-contract.md), [CAPACITY-01](../design-alignment/consequential-decision-inventory.md#packet-6-p1), and reviewed `TEST-01`/`TEST-03` are linked provenance. Current SLO/capacity evidence remains calibration or non-binding functional evidence; enforceable claims and production-like fault/load proof remain gaps. - `PO-4.4`: [ADR 0161](../../architecture/decisions/adr-0161-profile-aware-isolated-synthetic-player-flow-canaries.md), primary-capability [ADR 0162](../../architecture/decisions/adr-0162-profile-aware-asynchronous-end-to-end-log-queryability-evidence.md), [ADR 0164](../../architecture/decisions/adr-0164-three-boundary-profile-aware-verification-evidence.md), and the [testing owner](../../architecture/system-architecture-testing.md#where-these-checks-run-decision) are linked provenance. [ADR 0178](../../architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md) additionally requires head-bound disposable previews proving both Telnet and deployed-browser public paths. Canary identity/scheduling, asynchronous emit-and-query execution, supported-backend and profile behavior, evidence binding/freshness, browser adapter, lease cleanup, isolation, and failure-mode proof remain incomplete. - `SF-2.1` handoff: [ADR 0163](../../architecture/decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and the [scaling/retention owner](../../architecture/system-architecture-scaling-runbook.md#data-retention-and-high-churn-tables) are linked provenance. Platform operations retains recovery/audit/privacy horizons and cross-service blockers; the owning persistence tracker retains incomplete implementation status. -- `PO-2.1` / `PO-2.2`: [ADR 0169](../../architecture/decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md) owns the authenticated bridge listener and environment-bound trust profile. The dedicated WSS listener, exclusive profile validation, and hosted Helm mTLS wiring have local runtime and render proof. Issued and served certificate identity, consumer convergence, restart-based rotation, emergency withdrawal, and end-to-end hosted player proof remain incomplete. +- `PO-2.1` / `PO-2.2`: [ADR 0169](../../architecture/decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md) owns the authenticated bridge listener and environment-bound trust profile. The dedicated WSS listener, exclusive profile validation, and hosted Helm mTLS wiring have local runtime and render proof. The Gate 2 candidate locally tests projected Gateway listener and Telnet TLS reload for new connections, but issued and served certificate identity, hosted consumer convergence and rotation, emergency withdrawal, and end-to-end hosted player proof remain incomplete. - `PO-2.1` / `PO-2.4`: [ADR 0170](../../architecture/decisions/adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md), together with [ADR 0131](../../architecture/decisions/adr-0131-lifecycle-distinct-gameplay-close-taxonomy.md), owns fenced forwarding and lifecycle-specific recovery behavior. Current routing and retry proof remains partial. - `PO-3.1`: Human review retained [ADR 0097](../../architecture/decisions/adr-0097-git-and-ci-validated-single-operator-promotion-evidence.md)'s no-rebuild promotion boundary and clarified manifest/index, child-digest lineage, and cross-registry copy evidence. [ADR 0177](../../architecture/decisions/adr-0177-exact-plan-authorized-automated-production-deployment.md) owns exact-plan production authorization and execution. Complete lineage, exact-plan automation, short-lived credentials, and focused production proof remain unimplemented. - `PO-3.2`: [ADR 0171](../../architecture/decisions/adr-0171-separated-redis-role-processes-and-owned-keyspaces.md) owns role-separated Redis topology and clients. Current topology is partial; role-specific application clients, credentials, ACL/key/script registration, collision validation, and profile proof remain gaps. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index 714d5cbaf5..9451f7e87e 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -12,8 +12,10 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] ## Current Gaps -- Profile-policy surfaces still accept `HIDDEN_STAFF` and fail closed to `PRIVATE` during projection; reconcile the vocabulary against [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). -- Player-facing presence responses still expose disconnect disposition; reconcile the response shape against [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). +- Gameplay presence role classification now ignores global roles and elevates only from matching tenant-scoped gameplay grants, with focused proof against [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); broader presence/privacy gaps remain below. +- Account and Social profile-policy inputs still accept the legacy `HIDDEN_STAFF` value; Game Session now removes it from player command/output vocabulary and redacts legacy or unknown friend-presence entries. Reconcile the remaining owner surfaces against [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). +- Game Session's player-facing Friends projection now omits disconnect disposition and renders generic last-seen text. It also suppresses world/realm labels and associated playable-state/pointer evidence for `PUBLIC` and `FRIENDS_ONLY` entries pending the viewer-bound location-discoverability check owned by the [Social & Groups Friend Presence Privacy Contract](../../architecture/microservices/social-groups-service/api-contracts.md#friend-presence-privacy-contract). These are local player-output mitigations only; Social's service-local REST/gRPC projection is unchanged, and focused assertions are not live proof. The internal Game Session presence data still carries disposition for owner handoffs; broader private-by-failure and bounded-page proof remains open. +- The player-facing `FRIENDS SUMMARY` now exposes only the linked-friend total, not Social Groups' policy or presence-classification counts. `FRIENDS OFFLINE`, `FRIENDS PUBLIC`, `FRIENDS FRIENDS_ONLY`, `FRIENDS PRIVATE`, `FRIENDS SHARED`, `FRIENDS ISOLATED`, and `FRIENDS UNSPECIFIED_SCOPE` fail closed rather than selecting redacted subjects or disclosing suppressed location scope; `SHARED` and `ISOLATED` remain unavailable pending the viewer-bound discovery projection owned by the [Social & Groups Friend Presence Privacy Contract](../../architecture/microservices/social-groups-service/api-contracts.md#friend-presence-privacy-contract). Focused Game Session text and WebSocket tests cover this local projection boundary; underlying Social Groups privacy and bounded-page proof remains open. ## Capability Status @@ -24,9 +26,9 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] | EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; a focused fresh first-party WebSocket test confirms that a new connect-token context does not read retained screen-buffer rows; it does not exercise successful `LOGOUT`, and durable episode/race-retry proof remains absent. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Fresh first-party `PLAY` does not read retained screen-buffer rows solely from connect-token context; this bounded suppression is independent of successful `LOGOUT`, which remains unavailable until durable episode fencing exists. Concurrent/delayed replay proof remains absent. Full transcript archive/export and raw transport-byte replay remain outside this capability. | | EA-2.1 Chat, private communication, and mail | `partial` - room `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, and mail APIs are live. | `drift-found` - focused Game Session, Game Logic, Social chat, and mail tests cover bounded delivery and persistence, but do not prove the target caller binding or gameplay `WHISPER` scope. | [Social Groups Service API contracts](../../architecture/microservices/social-groups-service/api-contracts.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [CommunicationCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java); [CommunicationAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java); [ChatServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java); [MailServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [mail schema](../../../services/social-groups-service/src/main/resources/db/migration/V2__mail.sql) | [CommunicationCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java); [CommunicationWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java); [CommunicationAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java); [MailServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [EA-2.3](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Offline `TELL`, `SHOUT`, configured topology propagation, richer interception, and complete gameplay mail/player-recipient presentation remain absent. Durable chat/mail history currently lacks the target type-specific retention, hold, safety-evidence disposition, and content-free receipt/idempotency lifecycle; current tests do not prove those behaviors. The live Social proto/DTO/entity/schema/key remain account-keyed and do not match the canonical gameplay `WHISPER` projection scope defined in [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md). Completing that migration requires cross-service proto/DTO/entity/schema/key changes plus same-account/different-character/different-namespace and authorized-view proof; it remains a tracked implementation gap. The Gateway `/api/social/chat` route is removed/unavailable; direct Social service and gRPC caller binding remain nonconformant. | | EA-2.2 Friends, groups, guilds, and social relationships | `partial` - the `FRIENDS` command plus friend, guild, and relationship APIs/storage are live. | `drift-found` - focused Game Session, Social friend, guild, and integration tests cover the bounded command and service paths, including tenant-scoped reciprocal-active reads, but this is legacy tenant-scoped proof and does not establish the target account-pair relationship contract. | [Social Groups Service](../../architecture/microservices/social-groups-service/README.md); [Social Groups API contracts](../../architecture/microservices/social-groups-service/api-contracts.md) | [FriendsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java); [FriendServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java); [GuildServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [social relationship schema](../../../services/social-groups-service/src/main/resources/db/migration/V7__account_friend_links.sql) | [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java); [FriendServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java); [GuildServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java); [FriendControllerTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java); [SocialGroupsApplicationIntegrationTest.java](../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java) | [EA-2.3](./player-experience-commands-and-communication.md); [AA-1.1](./player-access-and-session.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Current direct service-local reads require tenant-scoped reciprocal `active` links; one-way, inactive-reciprocal, and wrong-tenant endpoint cases are covered by integration proof. The player-facing Gateway `/api/social/friends` route is removed/unavailable; the direct service residual retains reciprocal-active filtering for future/non-edge use. Tenant-free migration/disposition and broader social client integration remain target gaps. | -| EA-2.3 Presence, visibility, and availability | `partial` - live/recent canonical presence, AFK state, filtered friend presence, account visibility, and `WHO` substrate are live. | `drift-found` - focused tests cover the shipped bounded substrate, and the gameplay-role classifier no longer treats global `platformAdmin` or legacy global `god` inputs as gameplay grants, while payload/policy surfaces still retain `HIDDEN_STAFF` and player-facing disconnect disposition contrary to ADR 0046. | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md); [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md) | [DefaultGameplayPresenceLifecycleService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java); [GameplayPresenceRoleClassifier.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java); [AccountPresenceQueryServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java); [GameplayPresenceActivityResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolver.java); [PresenceProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PresenceProperties.java); [profile visibility schema](../../../services/account-service/src/main/resources/db/migration/V16__profile_presence_visibility.sql); [Game Session proto](../../../protos/game-session/v1/game_session_service.proto) | [DefaultGameplayPresenceLifecycleServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java); [GameplayPresenceRoleClassifierTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java); [AccountPresenceQueryServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java); [GameplayPresenceActivityResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java); [RedisGameplayPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java); [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java) | [AA-2.2](./player-access-and-session.md); [AA-1.1](./player-access-and-session.md); [EA-2.2](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md) | Complete caller-bound role proof, remove `HIDDEN_STAFF` from account-profile presence policy, suppress disconnect disposition from player responses, add private-by-failure and bounded-page proof, and keep in-world concealment under gameplay policy before calling this capability proven. | +| EA-2.3 Presence, visibility, and availability | `partial` - live/recent canonical presence, AFK state, filtered friend presence, account visibility, and `WHO` substrate are live. | `drift-found` - focused role tests prove global `platformAdmin`, `support`, `billingAdmin`, legacy `god`, and `moderator` claims remain ordinary players, while only matching tenant-scoped gameplay grants elevate. Game Session removes legacy `HIDDEN_STAFF` from player command/output vocabulary and redacts legacy or unknown friend-presence entries; player-facing Friends text/WebSocket output now omits disconnect disposition with focused negative tests. Account and Social profile-policy inputs still accept `HIDDEN_STAFF`; internal Game Session presence data retains disposition for owner handoffs. This does not establish Account end-to-end admission. | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md); [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md) | [DefaultGameplayPresenceLifecycleService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java); [GameplayPresenceRoleClassifier.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java); [AccountPresenceQueryServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java); [GameplayPresenceActivityResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolver.java); [PresenceProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PresenceProperties.java); [profile visibility schema](../../../services/account-service/src/main/resources/db/migration/V16__profile_presence_visibility.sql); [Game Session proto](../../../protos/game-session/v1/game_session_service.proto) | [DefaultGameplayPresenceLifecycleServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java); [GameplayPresenceRoleClassifierTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java); [AccountPresenceQueryServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java); [GameplayPresenceActivityResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java); [RedisGameplayPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java); [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [AA-2.2](./player-access-and-session.md); [AA-1.1](./player-access-and-session.md); [EA-2.2](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md) | Account end-to-end admission remains unproven. Remove `HIDDEN_STAFF` from Account and Social profile-policy inputs, add private-by-failure and bounded-page proof, and keep in-world concealment under gameplay policy before calling this capability proven. | | EA-2.4 Player blocking, reporting, and safety controls | `partial` - bounded internal report persistence and the live synchronous moderation-policy evaluation seam used at enforcement boundaries exist, but owner-local fixed-category restriction state, moderation cases, appeals, and caller-bound player submission remain incomplete; unsafe public administrative report persistence is disabled. | `drift-found` - focused tests prove the bounded internal gRPC persistence and live policy-evaluation seam, plus fail-closed absence of the former public route, not the canonical player-authenticated reporting boundary or target owner-local controls. | [Moderation policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md); [Authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [ReportGrpcService.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcService.java); [ReportServiceImpl.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportServiceImpl.java); [ModerationServiceImpl.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java); [report proto](../../../protos/logging-admin/v1/report_service.proto); [Logging & Admin V1__baseline.sql](../../../services/logging-admin-service/src/main/resources/db/migration/V1__baseline.sql) | [LoggingAdminApplicationIntegrationTest.java](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java); [ReportGrpcServiceTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcServiceTest.java); [ModerationServiceImplTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java) | [PO-1.2](./platform-operations-and-delivery.md); [EA-2.1](./player-experience-commands-and-communication.md); [AA-1.3](./player-access-and-session.md) | The live `BLOCK` command is a combat action-state effect, not social blocking. Player block/mute/ignore and safety UI remain absent; reporting needs canonical administrative authorization/live reference checks before public operator ingress and a distinct player route deriving reporter and tenant identity from authenticated caller context. | -| EA-3.1 Player browser application | `partial` - a React/Vite/MUI/TanStack Query starter and generic WebSocket envelope/JSON consumer that parses payloads as `unknown` exist; Vite now emits the compiled production bundle under the reserved `frontend-assets` asset directory, and an opt-in unprivileged static-host/preview-route slice is prepared but disabled; this is not an independently released player application. Native mobile is deferred pending a later product and compatibility decision. | `audited` - `npm run lint` and `npm run build` passed; the build emitted `dist/frontend-assets/react-*.svg`, `index-*.css`, and `index-*.js`. Opt-in Helm chart lint/render passed; no static image has been published, deployed, or browser-proved. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [FRONT-01](../../architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md) | [App.tsx](../../../web-client/src/App.tsx); [main.tsx](../../../web-client/src/main.tsx); [websocket.ts](../../../web-client/src/websocket.ts); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [vite.config.ts](../../../web-client/vite.config.ts); [web-client package](../../../web-client/package.json); [static host Dockerfile](../../../web-client/Dockerfile); [preview frontend template](../../../k8s/helm/firemud/templates/frontend.yaml) | `npm run lint` and `npm run build` passed and emitted `dist/frontend-assets/`; opt-in Helm lint/render passed, but no image build, running-host checks, or deployed browser journey executed. | [EA-1.2](./player-experience-commands-and-communication.md); [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.1](./player-access-and-session.md); [PO-2.1](./platform-operations-and-delivery.md) | Independent immutable artifact/release metadata, enabled static-host deployment and public routing, non-secret runtime configuration, bootstrap/connect-token flow, richer player UX, mobile surface, independent rollback, and browser automation remain absent. | +| EA-3.1 Player browser application | `partial` - a React/Vite/MUI/TanStack Query starter and generic WebSocket envelope/JSON consumer that parses payloads as `unknown` exist; Vite now emits the compiled production bundle under the reserved `frontend-assets` asset directory, and an opt-in unprivileged static-host/preview-route slice is prepared but disabled; this is not an independently released player application. Native mobile is deferred pending a later product and compatibility decision. | `audited` - `npm run lint` and `npm run build` passed; the build emitted `dist/frontend-assets/react-*.svg`, `index-*.css`, and `index-*.js`. Opt-in Helm chart lint/render passed; no static image has been published, deployed, or browser-proved. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [FRONT-01](../../architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md) | [App.tsx](../../../web-client/src/App.tsx); [main.tsx](../../../web-client/src/main.tsx); [websocket.ts](../../../web-client/src/websocket.ts); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [vite.config.ts](../../../web-client/vite.config.ts); [web-client package](../../../web-client/package.json); [static host Dockerfile](../../../web-client/Dockerfile); [preview frontend template](../../../k8s/helm/firemud/templates/frontend.yaml) | No focused executable proof: `npm run lint` and `npm run build` passed and emitted `dist/frontend-assets/`; opt-in Helm lint/render passed, but no image build, running-host checks, or deployed browser journey executed. | [EA-1.2](./player-experience-commands-and-communication.md); [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.1](./player-access-and-session.md); [PO-2.1](./platform-operations-and-delivery.md) | Independent immutable artifact/release metadata, enabled static-host deployment and public routing, non-secret runtime configuration, bootstrap/connect-token flow, richer player UX, mobile surface, independent rollback, and browser automation remain absent. | | EA-3.4 Shared navigation, accessibility, client state, and interaction foundations | `partial` - shared QueryClient, local feature state, and basic socket lifecycle are present. | `audited` - production scaffolding was inspected; no focused navigation, accessibility, or client-state executable proof was found. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md) | [main.tsx](../../../web-client/src/main.tsx); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [websocket.ts](../../../web-client/src/websocket.ts); [App.tsx](../../../web-client/src/App.tsx) | No focused executable proof: the [web-client package](../../../web-client/package.json) exposes general lint, build, formatting, preview, and accessibility scripts, but no focused navigation, accessibility, or client-state test exists. | [EA-1.2](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Shared navigation, accessibility coverage, semantic structured gameplay client integration, reconnect/error state, and durable interaction foundations remain absent. | ## Canonical Design Sources @@ -68,7 +70,7 @@ The Account JOIN RPC/controller, browser bootstrap facade, and direct-text REALM - Current behavior/proof: `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, mail APIs, friends, guild APIs, presence reads, privacy settings, recipient delivery, and speech normalization are live at bounded service/API seams; focused communication, social, presence, privacy, moderation, and cross-service tests cover those seams. - Local gaps linked to [ADR 0147](../../architecture/decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md), [ADR 0148](../../architecture/decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md), [ADR 0149](../../architecture/decisions/adr-0149-communication-type-specific-history-and-retention.md), and [ADR 0150](../../architecture/decisions/adr-0150-closed-observer-views-and-profile-scoped-shout.md) include offline `TELL`, profile-scoped `SHOUT`, richer topology/interception, type-specific history/acknowledgement, entity-owned social value/attachments, closed observer views, cross-pod delivery, first-party recipient presentation, and the canonical gameplay `WHISPER` recipient-scope migration. These ADR links identify gaps; they do not restate target policy. -- Presence/privacy drift remains tracked against [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md) and [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). Current `gameplaypresence:*` and `accountrecentpresence:*` Redis shapes, partial-write behavior, reset/readback behavior, storage role, and proof of private-by-failure enforcement for missing, stale, partial, or ambiguous evidence remain implementation/proof gaps. The canonical raw-presence/friend-projection ownership and disclosure rules are in the [Social & Groups Friend Presence Privacy Contract](../../architecture/microservices/social-groups-service/api-contracts.md#friend-presence-privacy-contract); canonical owner/reset details also live in the [Redis reset catalog](../../architecture/system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). Global-role inputs, `HIDDEN_STAFF`, and disconnect disposition remain local fixes rather than new design. +- Presence/privacy drift remains tracked against [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md) and [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). Current `gameplaypresence:*` and `accountrecentpresence:*` Redis shapes, partial-write behavior, reset/readback behavior, storage role, and proof of private-by-failure enforcement for missing, stale, partial, or ambiguous evidence remain implementation/proof gaps. The canonical raw-presence/friend-projection ownership and disclosure rules are in the [Social & Groups Friend Presence Privacy Contract](../../architecture/microservices/social-groups-service/api-contracts.md#friend-presence-privacy-contract); canonical owner/reset details also live in the [Redis reset catalog](../../architecture/system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). Global-role and `HIDDEN_STAFF` owner inputs remain local gaps rather than new design; player-facing disconnect disposition is removed while the internal owner handoff retains it. ### First-Party Frontend diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/hosted/preview/wait-for-hosted-identity.sh b/dev-tools/hosted/preview/wait-for-hosted-identity.sh index 268f892dd2..a2f40de7f9 100644 --- a/dev-tools/hosted/preview/wait-for-hosted-identity.sh +++ b/dev-tools/hosted/preview/wait-for-hosted-identity.sh @@ -69,11 +69,17 @@ read_kubectl_json() { local -n transport_retries_ref="$2" local resource_label="$3" local failure_diagnostic="$4" - shift 4 + local kubeconfig_path="$5" + shift 5 + + local -a kubectl_prefix=() + if [[ -n "$kubeconfig_path" ]]; then + kubectl_prefix=(--kubeconfig "$kubeconfig_path") + fi : >"$kubectl_error_file" # shellcheck disable=SC2034 # The assignment targets the caller's nameref. - if output_ref="$(kubectl "$@" 2>"$kubectl_error_file")"; then + if output_ref="$(kubectl "${kubectl_prefix[@]}" "$@" 2>"$kubectl_error_file")"; then transport_retries_ref=0 return 0 else @@ -169,6 +175,7 @@ if [[ "${1:-}" == "--projections" ]]; then transport_retries \ "${runtime_namespace}/${secret_name}" \ "Unable to determine controller projection ${runtime_namespace}/${secret_name}" \ + "" \ -n "$runtime_namespace" get secret "$secret_name" --ignore-not-found -o json; then continue fi @@ -230,6 +237,7 @@ if [[ "${1:-}" == "--retired" ]]; then transport_retries \ "HostedEnvironmentIdentity/${identity_name}" \ "Unable to determine retirement state for HostedEnvironmentIdentity/${identity_name}" \ + "${IDENTITY_KUBECONFIG:-}" \ -n firemud-system get hostedenvironmentidentity "$identity_name" --ignore-not-found -o json; then continue fi @@ -327,6 +335,11 @@ validate_timeout_seconds "$timeout_seconds" validate_identity_runtime_pairing "$identity_name" "$runtime_namespace" initialize_wait_state "$timeout_seconds" +# The active waiter normally uses the caller's KUBECONFIG. Trusted verification +# can provide narrower control-plane credentials for the Namespace and identity +# reads without changing the runtime credential used by other data-plane steps. +namespace_kubeconfig="${NAMESPACE_KUBECONFIG:-}" +identity_kubeconfig="${IDENTITY_KUBECONFIG:-}" # shellcheck disable=SC2034 # Mutated through read_kubectl_json's nameref. namespace_transport_retries=0 # shellcheck disable=SC2034 # Mutated through read_kubectl_json's nameref. @@ -337,6 +350,7 @@ while (( SECONDS < deadline )); do namespace_transport_retries \ "namespace/${runtime_namespace}" \ "Unable to determine runtime namespace ${runtime_namespace}" \ + "$namespace_kubeconfig" \ get namespace "$runtime_namespace" --ignore-not-found -o json; then continue fi @@ -432,6 +446,7 @@ while (( SECONDS < deadline )); do identity_transport_retries \ "HostedEnvironmentIdentity/${identity_name}" \ "Unable to determine HostedEnvironmentIdentity/${identity_name}" \ + "$identity_kubeconfig" \ -n firemud-system get hostedenvironmentidentity "$identity_name" --ignore-not-found -o json; then continue fi diff --git a/dev-tools/hosted/preview/write-playable-proof.py b/dev-tools/hosted/preview/write-playable-proof.py new file mode 100644 index 0000000000..8a396e1a81 --- /dev/null +++ b/dev-tools/hosted/preview/write-playable-proof.py @@ -0,0 +1,461 @@ +#!/usr/bin/env python3 +"""Build a bounded, non-secret record for trusted hosted preview proof.""" + +from __future__ import annotations + +import argparse +import json +import re +import sys +from pathlib import Path +from typing import Any, NoReturn + +SHA_RE = re.compile(r"^[0-9a-fA-F]{40}$") +IMAGE_TAG_RE = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$") +UID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$") +SAFE_REVISION_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:+/-]{0,127}$") +IMAGE_ID_RE = re.compile(r"^(?:[A-Za-z][A-Za-z0-9+.-]*://)?(.+)@sha256:([0-9a-f]{64})$") +SERVICE_IMAGES = ( + "account-service", + "automation-scripting-service", + "entity-management-service", + "game-design-service", + "game-logic-service", + "game-session-service", + "logging-admin-service", + "social-groups-service", + "spring-cloud-gateway", + "tcp-proxy-service", + "world-management-service", +) +APP_IMAGE_PREFIX = "ghcr.io/benhook1013/" +EXPECTED_IMAGE_ANNOTATION = "firemud.dev/last-preview-image-tag" +REQUESTED_HEAD_ANNOTATION = "firemud.dev/requested-preview-head-sha" +DEPLOYED_HEAD_ANNOTATION = "firemud.dev/last-preview-head-sha" +REQUESTED_BASE_ANNOTATION = "firemud.dev/requested-preview-base-sha" +DEPLOYED_BASE_ANNOTATION = "firemud.dev/last-preview-base-sha" +REQUESTED_MERGE_ANNOTATION = "firemud.dev/requested-preview-merge-sha" +DEPLOYED_MERGE_ANNOTATION = "firemud.dev/last-preview-merge-sha" +REQUESTED_IMAGE_ANNOTATION = "firemud.dev/requested-preview-image-tag" +EXPOSURE_LABEL = "firemud.dev/preview-exposure-mode" +PREVIEW_LABEL = "firemud.dev/preview" +PR_NUMBER_LABEL = "firemud.dev/pr-number" +TELNET_PORT_ANNOTATION = "firemud.dev/last-preview-telnet-port" +MAX_INPUT_BYTES = 2 * 1024 * 1024 +MAX_APP_PODS = 128 + + +def fail(message: str) -> NoReturn: + raise ValueError(message) + + +def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + value: dict[str, Any] = {} + for key, item in pairs: + if key in value: + fail("JSON input contains duplicate object keys") + value[key] = item + return value + + +def _mapping(value: object, label: str) -> dict[str, Any]: + if not isinstance(value, dict): + fail(f"{label} must be a JSON object") + return value + + +def _string(value: object, label: str, *, maximum: int = 256) -> str: + if ( + not isinstance(value, str) + or not value + or len(value) > maximum + or value.strip() != value + or any(ord(character) < 0x20 for character in value) + ): + fail(f"{label} must be a bounded nonempty string") + return value + + +def _sha(value: object, label: str) -> str: + if not isinstance(value, str) or SHA_RE.fullmatch(value) is None: + fail(f"{label} must be exactly 40 hexadecimal characters") + return value.lower() + + +def _positive_integer(value: object, label: str) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value <= 0: + fail(f"{label} must be a positive integer") + return value + + +def _metadata(document: object, label: str) -> dict[str, Any]: + return _mapping(_mapping(document, label).get("metadata"), f"{label}.metadata") + + +def _read_json(path: str, label: str, stdin_bytes: bytes | None) -> object: + try: + if path == "-": + if stdin_bytes is None: + fail("only one Kubernetes JSON input may use stdin") + payload = stdin_bytes + else: + with Path(path).open("rb") as stream: + payload = stream.read(MAX_INPUT_BYTES + 1) + except OSError as exc: + raise ValueError(f"could not read {label} JSON input") from exc + if len(payload) > MAX_INPUT_BYTES: + fail(f"{label} JSON input exceeds the size limit") + try: + return json.loads(payload.decode("utf-8"), object_pairs_hook=_unique_object) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ValueError(f"{label} input must be valid UTF-8 JSON") from exc + + +def _validate_expected( + pr_number: object, + base_sha: object, + head_sha: object, + merge_sha: object, + image_tag: object, +) -> dict[str, object]: + if ( + not isinstance(pr_number, str) + or re.fullmatch(r"[1-9][0-9]{0,50}", pr_number) is None + ): + fail("trusted PR number must be a canonical positive decimal integer") + if not isinstance(image_tag, str) or IMAGE_TAG_RE.fullmatch(image_tag) is None: + fail("trusted image tag is malformed") + return { + "prNumber": int(pr_number), + "baseSha": _sha(base_sha, "trusted base SHA"), + "headSha": _sha(head_sha, "trusted head SHA"), + "mergeSha": _sha(merge_sha, "trusted merge SHA"), + "imageTag": image_tag, + } + + +def _validate_namespace(namespace: object, expected: dict[str, object]) -> dict[str, object]: + namespace_obj = _mapping(namespace, "Namespace") + if namespace_obj.get("kind") != "Namespace": + fail("namespace input must be a Kubernetes Namespace") + metadata = _metadata(namespace_obj, "Namespace") + namespace_name = f"pr-{expected['prNumber']}" + if metadata.get("name") != namespace_name: + fail("Namespace name does not match the trusted PR") + namespace_uid = _string(metadata.get("uid"), "Namespace UID", maximum=128) + if UID_RE.fullmatch(namespace_uid) is None: + fail("Namespace UID is malformed") + labels = _mapping(metadata.get("labels", {}), "Namespace labels") + annotations = _mapping(metadata.get("annotations", {}), "Namespace annotations") + if labels.get(PREVIEW_LABEL) != "true": + fail("Namespace is not labeled as a preview") + if labels.get(PR_NUMBER_LABEL) != str(expected["prNumber"]): + fail("Namespace PR label does not match the trusted PR") + exposure = labels.get(EXPOSURE_LABEL) + if exposure != "public": + fail("playable proof requires the public preview exposure mode") + requested_head = _sha( + annotations.get(REQUESTED_HEAD_ANNOTATION), "Namespace requested head SHA" + ) + deployed_head = _sha( + annotations.get(DEPLOYED_HEAD_ANNOTATION), "Namespace deployed head SHA" + ) + if requested_head != expected["headSha"]: + fail("Namespace requested head SHA is stale") + if deployed_head != expected["headSha"]: + fail("Namespace deployed head SHA is stale") + for annotation, expected_field in ( + (REQUESTED_BASE_ANNOTATION, "baseSha"), + (DEPLOYED_BASE_ANNOTATION, "baseSha"), + (REQUESTED_MERGE_ANNOTATION, "mergeSha"), + (DEPLOYED_MERGE_ANNOTATION, "mergeSha"), + ): + if _sha(annotations.get(annotation), f"Namespace {annotation}") != expected[ + expected_field + ]: + fail(f"Namespace {annotation} is stale") + if annotations.get(REQUESTED_IMAGE_ANNOTATION) != expected["imageTag"]: + fail("Namespace requested image tag does not match the trusted image tag") + if annotations.get(EXPECTED_IMAGE_ANNOTATION) != expected["imageTag"]: + fail("Namespace image tag does not match the trusted image tag") + port = annotations.get(TELNET_PORT_ANNOTATION) + if not isinstance(port, str) or re.fullmatch(r"32(?:00[0-9]|01[0-5])", port) is None: + fail("public Namespace Telnet port is malformed or missing") + return { + "name": namespace_name, + "uid": namespace_uid, + "exposureMode": exposure, + "telnetPort": int(port), + } + + +def _validate_identity( + identity: object, + expected: dict[str, object], + namespace_record: dict[str, object], +) -> dict[str, object]: + identity_obj = _mapping(identity, "HostedEnvironmentIdentity") + if ( + identity_obj.get("apiVersion") != "platform.firemud.dev/v1alpha1" + or identity_obj.get("kind") != "HostedEnvironmentIdentity" + ): + fail("identity input must be a HostedEnvironmentIdentity") + metadata = _metadata(identity_obj, "HostedEnvironmentIdentity") + if metadata.get("name") != namespace_record["name"]: + fail("identity name does not match the trusted PR") + generation = _positive_integer(metadata.get("generation"), "identity generation") + status = _mapping(identity_obj.get("status"), "identity status") + if status.get("phase") != "Ready" or status.get("observedGeneration") != generation: + fail("HostedEnvironmentIdentity is not Ready for its current generation") + conditions = status.get("conditions") + if not isinstance(conditions, list): + fail("identity Ready condition is missing") + ready_conditions = [ + condition + for condition in conditions + if isinstance(condition, dict) and condition.get("type") == "Ready" + ] + if len(ready_conditions) != 1: + fail("identity Ready condition is missing or ambiguous") + ready = ready_conditions[0] + if ready.get("status") != "True" or ready.get("observedGeneration") != generation: + fail("identity Ready condition is stale or false") + + profile = _mapping(status.get("profile"), "identity profile") + if profile.get("runtimeNamespaceUid") != namespace_record["uid"]: + fail("identity runtime Namespace UID does not match") + if _sha(profile.get("requestedHeadSha"), "identity requested head SHA") != expected[ + "headSha" + ]: + fail("identity requested head SHA is stale") + if _sha(profile.get("deployedHeadSha"), "identity deployed head SHA") != expected[ + "headSha" + ]: + fail("identity deployed head SHA is stale") + if profile.get("exposureMode") != namespace_record["exposureMode"]: + fail("identity exposure mode does not match the Namespace") + telnet_port = profile.get("telnetPort") + if ( + isinstance(telnet_port, bool) + or not isinstance(telnet_port, int) + or telnet_port != namespace_record["telnetPort"] + ): + fail("identity Telnet port does not match the Namespace") + + revisions: dict[str, str] = {} + for field in ( + "ingress", + "telnet", + "gatewayInternalWs", + "tcpProxyBridge", + "grpc", + ): + projection = _mapping(status.get(field), f"identity {field} projection") + revision = projection.get("revision") + revision = _string(revision, f"identity {field} revision", maximum=128) + if SAFE_REVISION_RE.fullmatch(revision) is None: + fail(f"identity {field} revision is malformed") + revisions[field] = revision + return {"identityName": metadata["name"], "generation": generation, "revisions": revisions} + + +def _parse_declared_image(value: object, service: str, image_tag: str) -> str: + expected = f"{APP_IMAGE_PREFIX}{service}:{image_tag}" + if value != expected: + fail(f"application image for {service} does not match the trusted image tag") + return expected + + +def _validate_image_id(value: object, service: str) -> tuple[str, str]: + image_id = _string(value, f"{service} runtime image ID", maximum=512) + match = IMAGE_ID_RE.fullmatch(image_id) + if match is None: + fail(f"{service} runtime image ID has no identifiable SHA-256 digest") + repository, digest = match.groups() + if repository != f"{APP_IMAGE_PREFIX}{service}": + fail(f"{service} runtime image ID does not match its approved repository") + return image_id, f"sha256:{digest}" + + +def _validate_pods( + pods: object, + expected: dict[str, object], + namespace_record: dict[str, object], +) -> list[dict[str, str]]: + pod_list = _mapping(pods, "Pod list") + if pod_list.get("kind") != "PodList" or not isinstance(pod_list.get("items"), list): + fail("pod input must be a Kubernetes Pod List") + if len(pod_list["items"]) > MAX_APP_PODS: + fail("pod list exceeds the bounded item limit") + + observed: list[dict[str, str]] = [] + services_seen: set[str] = set() + for index, value in enumerate(pod_list["items"]): + pod = _mapping(value, f"pod item {index}") + if pod.get("kind") not in (None, "Pod"): + fail("pod list contains a non-Pod item") + metadata = _metadata(pod, "Pod") + pod_namespace = metadata.get("namespace") + if pod_namespace != namespace_record["name"]: + fail("pod list contains an item outside the trusted Namespace") + labels = _mapping(metadata.get("labels", {}), "Pod labels") + spec = _mapping(pod.get("spec"), "Pod spec") + containers = spec.get("containers") + if not isinstance(containers, list): + fail("pod containers are malformed") + matching: list[tuple[str, dict[str, Any]]] = [] + for container_value in containers: + container = _mapping(container_value, "Pod container") + container_name = container.get("name") + declared_image = container.get("image") + if container_name in SERVICE_IMAGES: + matching.append((container_name, container)) + continue + if ( + isinstance(declared_image, str) + and declared_image.startswith(APP_IMAGE_PREFIX) + ): + service_name = declared_image[len(APP_IMAGE_PREFIX) :].split(":", 1)[0] + if service_name not in SERVICE_IMAGES: + fail("pod contains an unidentifiable application image") + matching.append((service_name, container)) + app_label = labels.get("app") + if app_label in SERVICE_IMAGES and not matching: + fail(f"application pod {app_label} has no identifiable application image") + if not matching: + continue + if len(matching) != 1: + fail("application pod has an ambiguous container identity") + service, container = matching[0] + if app_label != service or container.get("name") != service: + fail(f"application pod identity is inconsistent for {service}") + if metadata.get("deletionTimestamp") is not None: + fail(f"application pod {service} is terminating") + _parse_declared_image(container.get("image"), service, str(expected["imageTag"])) + + status = _mapping(pod.get("status"), "Pod status") + if status.get("phase") != "Running": + fail(f"application pod {service} is not Running") + conditions = status.get("conditions") + if not isinstance(conditions, list): + fail(f"application pod {service} Ready condition is missing") + ready_conditions = [ + condition + for condition in conditions + if isinstance(condition, dict) and condition.get("type") == "Ready" + ] + if len(ready_conditions) != 1 or ready_conditions[0].get("status") != "True": + fail(f"application pod {service} is not Ready") + container_statuses = status.get("containerStatuses") + if not isinstance(container_statuses, list): + fail(f"application pod {service} container status is missing") + matching_statuses = [ + item + for item in container_statuses + if isinstance(item, dict) and item.get("name") == service + ] + if len(matching_statuses) != 1 or matching_statuses[0].get("ready") is not True: + fail(f"application container {service} is not Ready") + image_id, digest = _validate_image_id(matching_statuses[0].get("imageID"), service) + observed.append( + { + "service": service, + "image": f"{APP_IMAGE_PREFIX}{service}:{expected['imageTag']}", + "imageId": image_id, + "digest": digest, + } + ) + services_seen.add(service) + + missing = sorted(set(SERVICE_IMAGES) - services_seen) + if missing: + fail("application pod inventory is incomplete") + observed.sort(key=lambda item: (item["service"], item["digest"])) + return observed + + +def build_record( + *, + pr_number: object, + base_sha: object, + head_sha: object, + merge_sha: object, + image_tag: object, + namespace: object, + identity: object, + pods: object, + telnet_passed: object, + wss_passed: object, +) -> dict[str, object]: + """Validate trusted identity and observed runtime state, then build the allowlisted record.""" + + expected = _validate_expected(pr_number, base_sha, head_sha, merge_sha, image_tag) + if telnet_passed is not True or wss_passed is not True: + fail( + "public Telnet and first-party WSS diagnostic outcomes must be explicitly passed" + ) + namespace_record = _validate_namespace(namespace, expected) + identity_record = _validate_identity(identity, expected, namespace_record) + images = _validate_pods(pods, expected, namespace_record) + return { + "schemaVersion": 1, + "proofType": "hosted-pr-transport-diagnostic", + "identity": expected, + "namespace": namespace_record, + "controller": identity_record, + "runtimeImages": images, + "outcomes": { + "publicTelnetDiagnosticPassed": True, + "firstPartyWssDiagnosticPassed": True, + }, + } + + +def _load_inputs(args: argparse.Namespace) -> tuple[object, object, object]: + paths = (args.namespace_json, args.identity_json, args.pods_json) + if paths.count("-") > 1: + fail("at most one Kubernetes JSON input may use stdin") + stdin_bytes = sys.stdin.buffer.read(MAX_INPUT_BYTES + 1) if "-" in paths else None + return ( + _read_json(args.namespace_json, "Namespace", stdin_bytes if args.namespace_json == "-" else None), + _read_json(args.identity_json, "identity", stdin_bytes if args.identity_json == "-" else None), + _read_json(args.pods_json, "pods", stdin_bytes if args.pods_json == "-" else None), + ) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(allow_abbrev=False) + parser.add_argument("--pr-number", required=True) + parser.add_argument("--base-sha", required=True) + parser.add_argument("--head-sha", required=True) + parser.add_argument("--merge-sha", required=True) + parser.add_argument("--image-tag", required=True) + parser.add_argument("--namespace-json", required=True) + parser.add_argument("--identity-json", required=True) + parser.add_argument("--pods-json", required=True) + parser.add_argument("--telnet-outcome", choices=("passed", "failed"), required=True) + parser.add_argument("--wss-outcome", choices=("passed", "failed"), required=True) + args = parser.parse_args(argv) + try: + namespace, identity, pods = _load_inputs(args) + record = build_record( + pr_number=args.pr_number, + base_sha=args.base_sha, + head_sha=args.head_sha, + merge_sha=args.merge_sha, + image_tag=args.image_tag, + namespace=namespace, + identity=identity, + pods=pods, + telnet_passed=args.telnet_outcome == "passed", + wss_passed=args.wss_outcome == "passed", + ) + except ValueError as exc: + print(f"playable proof rejected: {exc}", file=sys.stderr) + return 1 + print(json.dumps(record, sort_keys=True, separators=(",", ":"))) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/dev-tools/hosted/shared/hosted-login-look-smoke.sh b/dev-tools/hosted/shared/hosted-login-look-smoke.sh index 525629351b..45a7144771 100644 --- a/dev-tools/hosted/shared/hosted-login-look-smoke.sh +++ b/dev-tools/hosted/shared/hosted-login-look-smoke.sh @@ -10,6 +10,8 @@ TCP_PORT=${TCP_PORT:?TCP_PORT is required} SMOKE_LOGIN_EMAIL=${SMOKE_LOGIN_EMAIL:-$DEMO_SMOKE_EMAIL} SMOKE_PASSWORD=${SMOKE_PASSWORD:-$DEMO_SMOKE_PASSWORD} SMOKE_WORLD=${SMOKE_WORLD:-$DEMO_SMOKE_WORLD} +SMOKE_REALM=${SMOKE_REALM:-} +SMOKE_CHARACTER=${SMOKE_CHARACTER:-} SMOKE_TARGET_LABEL=${SMOKE_TARGET_LABEL:-hosted environment} SMOKE_TIMEOUT_SECONDS=${SMOKE_TIMEOUT_SECONDS:-20} SMOKE_WORLDS_EXPECT=${SMOKE_WORLDS_EXPECT:-OK WORLDS} @@ -40,19 +42,22 @@ from pathlib import Path repo_root = Path(os.environ["FIREMUD_REPO_ROOT"]) sys.path.insert(0, str(repo_root / "dev-tools" / "smoke")) -from smoke_common import login_play_look_steps, run_telnet_smoke_session +from smoke_common import login_play_look_steps, run_telnet_smoke_session, telnet_look_room_id host = os.environ["SMOKE_TELNET_HOST"] port = int(os.environ["TCP_PORT"]) login_email = os.environ.get("SMOKE_LOGIN_EMAIL", os.environ["DEMO_SMOKE_EMAIL"]) password = os.environ.get("SMOKE_PASSWORD", os.environ["DEMO_SMOKE_PASSWORD"]) world = os.environ.get("SMOKE_WORLD", os.environ["DEMO_SMOKE_WORLD"]) +realm = os.environ.get("SMOKE_REALM") or None +character = os.environ.get("SMOKE_CHARACTER") or None timeout_seconds = int(os.environ.get("SMOKE_TIMEOUT_SECONDS", "20")) worlds_expect = os.environ.get("SMOKE_WORLDS_EXPECT", "OK WORLDS") login_expect = os.environ.get("SMOKE_LOGIN_EXPECT", "OK LOGIN") play_expect = os.environ.get("SMOKE_PLAY_EXPECT", "OK PLAY") look_expect = os.environ.get("SMOKE_LOOK_EXPECT", "OK LOOK") ca_file = os.environ.get("SMOKE_TELNET_CA_FILE") or None +step_results = [] run_telnet_smoke_session( host, port, @@ -64,6 +69,8 @@ run_telnet_smoke_session( login_expect, play_expect, look_expect, + realm=realm, + character=character, ), timeout_seconds, retry_window_seconds=timeout_seconds, @@ -71,8 +78,27 @@ run_telnet_smoke_session( tls_enabled=True, tls_server_hostname=host, tls_ca_file=ca_file, + step_results=step_results, ) +semantic_out = os.environ.get("SMOKE_SEMANTIC_OUT") +if semantic_out: + import json + import re + + look_responses = [step["response"] for step in step_results if step["label"] == "LOOK"] + if len(look_responses) != 1: + raise RuntimeError("Telnet smoke did not record exactly one LOOK response") + room_id = telnet_look_room_id(look_responses[0]) + if re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", room_id) is None: + raise RuntimeError("Telnet LOOK room ID is malformed") + path = Path(semantic_out) + if not path.is_absolute(): + raise RuntimeError("SMOKE_SEMANTIC_OUT must be an absolute path") + with path.open("x", encoding="utf-8") as output: + json.dump({"transport": "telnet", "lookRoomId": room_id}, output) + output.write("\n") + label = os.environ.get("SMOKE_TARGET_LABEL", "hosted environment") print(f"{label} TCP LOGIN -> PLAY -> LOOK smoke test passed.") PY diff --git a/dev-tools/hosted/shared/hosted-websocket-playable-smoke.py b/dev-tools/hosted/shared/hosted-websocket-playable-smoke.py new file mode 100644 index 0000000000..465db8a457 --- /dev/null +++ b/dev-tools/hosted/shared/hosted-websocket-playable-smoke.py @@ -0,0 +1,963 @@ +#!/usr/bin/env python3 +"""Diagnostic first-party hosted WSS LOGIN -> PLAY -> LOOK smoke. + +This is an operator probe for the deployed public path. It is deliberately +not a synthetic canary and does not emit promotion or release evidence. The +Account bootstrap token is used only to discover a target and mint the +Gateway-owned, first-party ``Firemud-Connect-Token`` cookie; credentials are +never sent over the WebSocket or included in errors. +""" + +from __future__ import annotations + +import argparse +import datetime +import json +import os +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from typing import Any + +DEFAULT_USERNAME = "demo@example.com" +DEFAULT_PASSWORD = "swordfish" +DEFAULT_WORLD = "demo" +DEFAULT_REALM = "production" +DEFAULT_AUTH_PREFIX = "/api/account" +DEFAULT_GATEWAY_BASE = "http://localhost:8080" +MAX_HTTP_RESPONSE_BYTES = 1_048_576 +MAX_WEBSOCKET_FRAME_BYTES = 1_048_576 +MAX_WEBSOCKET_MESSAGE_BYTES = 1_048_576 +MAX_WEBSOCKET_RECEIVE_FRAMES = 256 +MAX_WEBSOCKET_RECEIVE_BYTES = 2 * 1_048_576 +MAX_WEBSOCKET_WAIT_FRAMES = 1_024 +MAX_WEBSOCKET_WAIT_MESSAGES = 256 +MAX_WEBSOCKET_WAIT_BYTES = 2 * 1_048_576 +MAX_WEBSOCKET_CLOSE_SECONDS = 3.0 + + +class HostedWebSocketPlayableSmokeError(RuntimeError): + """A bounded, operator-actionable diagnostic failure.""" + + +@dataclass(frozen=True) +class SmokeConfig: + auth_api_base: str + websocket_url: str + origin: str = "" + auth_api_prefix: str = DEFAULT_AUTH_PREFIX + readiness_url: str | None = None + revoke_url: str | None = None + username: str = DEFAULT_USERNAME + password: str = DEFAULT_PASSWORD + world: str = DEFAULT_WORLD + realm: str = DEFAULT_REALM + character: str | None = None + expected_room_id: str | None = None + timeout_seconds: float = 10.0 + exercise_logout: bool = False + exercise_reconnect: bool = False + + +@dataclass(frozen=True) +class HttpResponse: + status: int + headers: Mapping[str, str] + body: Any + + +HttpRequest = Callable[[str, str, Any, Mapping[str, str], float], HttpResponse] +WebSocketFactory = Callable[[str, float, Sequence[str]], Any] +WEBSOCKET_CLOSE_OPCODE = 0x8 + + +class _WebSocketReceiveLimitExceeded(ValueError): + """An inbound WebSocket frame or receive budget exceeded its local bound.""" + + +def _websocket_payload_size(payload: Any) -> int: + if isinstance(payload, bytes): + return len(payload) + if isinstance(payload, str): + return len(payload.encode("utf-8")) + return 0 + + +def _bounded_websocket_client(websocket: Any) -> type: + """Build the smoke-only bounded adapter for the pinned websocket-client API.""" + # websocket-client 1.9.2 exposes create_connection(class_) but no public + # max-frame/message setting. These two private _abnf hooks are intentionally + # isolated here; the requirements pin must be reviewed with this adapter. + from websocket import _abnf + + class BoundedFrameBuffer(_abnf.frame_buffer): + def __init__( + self, + recv_fn: Callable[[int], bytes], + skip_utf8_validation: bool, + owner: Any, + ): + super().__init__(recv_fn, skip_utf8_validation) + self.owner = owner + + def recv_length(self) -> None: + super().recv_length() + if self.header is None or self.length is None: + raise _WebSocketReceiveLimitExceeded("incomplete WebSocket frame header") + opcode = self.header[4] + maximum = 125 if opcode & 0x8 else MAX_WEBSOCKET_FRAME_BYTES + try: + if self.length > maximum: + raise _WebSocketReceiveLimitExceeded("WebSocket frame exceeds its size limit") + self.owner._reserve_inbound_frame(self.length) + except _WebSocketReceiveLimitExceeded: + self.clear() + self.owner._receive_limit_failed = True + raise + + class BoundedContinuousFrame(_abnf.continuous_frame): + def add(self, frame: Any) -> None: + if frame.opcode in (_abnf.ABNF.OPCODE_TEXT, _abnf.ABNF.OPCODE_BINARY): + previous_size = len(self.cont_data[1]) if self.cont_data else 0 + if previous_size + len(frame.data) > MAX_WEBSOCKET_MESSAGE_BYTES: + raise _WebSocketReceiveLimitExceeded("WebSocket message exceeds its size limit") + elif frame.opcode == _abnf.ABNF.OPCODE_CONT and self.cont_data: + if len(self.cont_data[1]) + len(frame.data) > MAX_WEBSOCKET_MESSAGE_BYTES: + raise _WebSocketReceiveLimitExceeded("WebSocket message exceeds its size limit") + super().add(frame) + + class BoundedWebSocket(websocket.WebSocket): + def __init__(self, *args: Any, **kwargs: Any): + super().__init__(*args, **kwargs) + self._receive_deadline: float | None = None + self._receive_operation_active = False + self._receive_operation_frames = 0 + self._receive_operation_bytes = 0 + self._last_receive_usage = (0, 0) + self._receive_limit_failed = False + self.frame_buffer = BoundedFrameBuffer( + self._recv, + self.frame_buffer.skip_utf8_validation, + self, + ) + self.cont_frame = BoundedContinuousFrame( + self.cont_frame.fire_cont_frame, + self.cont_frame.skip_utf8_validation, + ) + + def set_receive_deadline(self, deadline: float | None) -> None: + self._receive_deadline = deadline + + def _reserve_inbound_frame(self, payload_bytes: int) -> None: + if self._receive_operation_frames + 1 > MAX_WEBSOCKET_RECEIVE_FRAMES: + raise _WebSocketReceiveLimitExceeded("WebSocket receive frame budget exceeded") + if self._receive_operation_bytes + payload_bytes > MAX_WEBSOCKET_RECEIVE_BYTES: + raise _WebSocketReceiveLimitExceeded("WebSocket receive byte budget exceeded") + self._receive_operation_frames += 1 + self._receive_operation_bytes += payload_bytes + + def _begin_receive_operation(self) -> bool: + if self._receive_operation_active: + return False + self._receive_operation_active = True + self._receive_operation_frames = 0 + self._receive_operation_bytes = 0 + return True + + def _end_receive_operation(self, started: bool) -> None: + if started: + self._last_receive_usage = ( + self._receive_operation_frames, + self._receive_operation_bytes, + ) + self._receive_operation_active = False + + def last_receive_usage(self) -> tuple[int, int]: + return self._last_receive_usage + + def _recv(self, bufsize: int) -> bytes: + deadline = self._receive_deadline + if deadline is not None: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError("WebSocket receive deadline expired") + if self.sock is not None: + self.sock.settimeout(remaining) + result = super()._recv(bufsize) + if deadline is not None and time.monotonic() >= deadline: + raise TimeoutError("WebSocket receive deadline expired") + return result + + def recv_frame(self) -> Any: + started = self._begin_receive_operation() + try: + return super().recv_frame() + except _WebSocketReceiveLimitExceeded: + self._receive_limit_failed = True + raise + finally: + self._end_receive_operation(started) + + def recv_data_frame(self, control_frame: bool = False) -> tuple: + started = self._begin_receive_operation() + try: + return super().recv_data_frame(control_frame) + except _WebSocketReceiveLimitExceeded: + self._receive_limit_failed = True + raise + finally: + self._end_receive_operation(started) + + def close( + self, + status: int = 1000, + reason: str | bytes = b"", + timeout: float | None = 3, + ) -> None: + if self._receive_limit_failed or not self.connected: + self.shutdown() + return + close_timeout = ( + MAX_WEBSOCKET_CLOSE_SECONDS + if timeout is None + else min(max(0.0, float(timeout)), MAX_WEBSOCKET_CLOSE_SECONDS) + ) + previous_deadline = self._receive_deadline + self._receive_deadline = time.monotonic() + close_timeout + started = self._begin_receive_operation() + try: + if self.sock is not None: + self.sock.settimeout(close_timeout) + super().close(status=status, reason=reason, timeout=close_timeout) + finally: + self.shutdown() + self._receive_deadline = previous_deadline + self._end_receive_operation(started) + + return BoundedWebSocket + + +def redact_credentials(value: Any, username: str, password: str) -> str: + text = str(value) + for secret in (password, username): + if secret: + text = text.replace(secret, "") + return text + + +def _fail(message: str, config: SmokeConfig) -> HostedWebSocketPlayableSmokeError: + return HostedWebSocketPlayableSmokeError(redact_credentials(message, config.username, config.password)) + + +def _join_url(base: str, path: str) -> str: + return base.rstrip("/") + "/" + path.lstrip("/") + + +def _quote(value: str) -> str: + return urllib.parse.quote(value, safe="") + + +def _valid_character_name(value: object) -> bool: + return ( + isinstance(value, str) + and bool(value) + and value == value.strip() + and not any(ord(character) < 0x20 or ord(character) == 0x7F for character in value) + ) + + +def _header(headers: Mapping[str, str], name: str) -> str: + wanted = name.lower() + for key, value in headers.items(): + if key.lower() == wanted: + return value + return "" + + +def _decode_json(body: Any, description: str, config: SmokeConfig) -> Any: + if isinstance(body, (bytes, bytearray)): + body = body.decode("utf-8", errors="replace") + if isinstance(body, (dict, list)): + return body + try: + return json.loads(str(body)) + except (TypeError, json.JSONDecodeError) as exc: + raise _fail(f"{description} returned malformed JSON", config) from exc + + +def _require_success(response: HttpResponse, description: str, config: SmokeConfig) -> Any: + if not 200 <= response.status < 300: + raise _fail(f"{description} returned HTTP {response.status}", config) + return _decode_json(response.body, description, config) + + +def _require_envelope(response: HttpResponse, description: str, config: SmokeConfig) -> Any: + payload = _require_success(response, description, config) + if not isinstance(payload, dict) or "data" not in payload: + raise _fail(f"{description} returned a malformed response envelope", config) + return payload["data"] + + +class _RejectRedirectHandler(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + # Returning None leaves the original 3xx response for the normal status + # check; no second request can carry bootstrap authority or cookies. + return None + + +def _read_http_body(response: Any) -> tuple[bytes, bool]: + # Socket timeouts bound stalls, not bytes; the sentinel independently caps + # memory use and JSON input while allowing an exactly-at-limit response. + body = response.read(MAX_HTTP_RESPONSE_BYTES + 1) + return body[:MAX_HTTP_RESPONSE_BYTES], len(body) > MAX_HTTP_RESPONSE_BYTES + + +def _default_http_request( + method: str, + url: str, + payload: Any, + headers: Mapping[str, str], + timeout: float, +) -> HttpResponse: + body = None if payload is None else json.dumps(payload).encode("utf-8") + request = urllib.request.Request(url, data=body, method=method, headers=dict(headers)) + opener = urllib.request.build_opener(_RejectRedirectHandler()) + try: + with opener.open(request, timeout=timeout) as response: + response_body, oversized = _read_http_body(response) + if oversized: + raise HostedWebSocketPlayableSmokeError( + f"{method} returned HTTP {response.status} with a response body exceeding " + f"{MAX_HTTP_RESPONSE_BYTES} bytes" + ) + return HttpResponse( + response.status, + dict(response.headers.items()), + response_body, + ) + except urllib.error.HTTPError as exc: + try: + response_body, _ = _read_http_body(exc) + return HttpResponse(exc.code, dict(exc.headers.items()), response_body) + finally: + exc.close() + except (OSError, urllib.error.URLError) as exc: + raise HostedWebSocketPlayableSmokeError(f"{method} {url} failed: {exc.__class__.__name__}") from exc + + +def _request( + http_request: HttpRequest, + config: SmokeConfig, + method: str, + url: str, + *, + payload: Any = None, + headers: Mapping[str, str] | None = None, +) -> HttpResponse: + try: + return http_request( + method, + url, + payload, + headers or {}, + config.timeout_seconds, + ) + except HostedWebSocketPlayableSmokeError: + raise + except Exception as exc: + raise _fail(f"{method} {url} transport failed: {exc.__class__.__name__}", config) from exc + + +def _auth_url(config: SmokeConfig, path: str) -> str: + return _join_url(_join_url(config.auth_api_base, config.auth_api_prefix), path) + + +def _validate_origin(config: SmokeConfig) -> None: + parsed = urllib.parse.urlparse(config.origin) + if ( + parsed.scheme not in {"http", "https"} + or not parsed.hostname + or parsed.path != "" + or parsed.params + or parsed.query + or parsed.fragment + ): + raise _fail( + "a valid first-party Origin (for example https://frontend.example) is required", + config, + ) + + +def _bootstrap(config: SmokeConfig, http_request: HttpRequest) -> str: + data = _require_envelope( + _request( + http_request, + config, + "POST", + _auth_url(config, "/auth/player-bootstrap"), + payload={"accountIdentifier": config.username, "secret": config.password}, + headers={"Content-Type": "application/json"}, + ), + "player bootstrap", + config, + ) + if not isinstance(data, dict) or not isinstance(data.get("bootstrapToken"), str): + raise _fail("player bootstrap returned no bootstrap token", config) + if not data["bootstrapToken"]: + raise _fail("player bootstrap returned an empty bootstrap token", config) + return data["bootstrapToken"] + + +def _discover_target( + config: SmokeConfig, + http_request: HttpRequest, + bootstrap_token: str, +) -> tuple[str, str | None]: + headers = {"Authorization": f"Bearer {bootstrap_token}"} + worlds = _require_envelope( + _request(http_request, config, "GET", _auth_url(config, "/auth/bootstrap/worlds"), headers=headers), + "bootstrap worlds", + config, + ) + if not isinstance(worlds, list) or not any( + isinstance(world, dict) and world.get("worldSlug") == config.world for world in worlds + ): + raise _fail(f"world {config.world!r} was not visible during bootstrap discovery", config) + + realms_url = _auth_url(config, f"/auth/bootstrap/worlds/{_quote(config.world)}/realms") + realms = _require_envelope( + _request(http_request, config, "GET", realms_url, headers=headers), + "bootstrap realms", + config, + ) + realm = ( + next( + ( + candidate + for candidate in realms + if isinstance(candidate, dict) and candidate.get("realmSlug") == config.realm + ), + None, + ) + if isinstance(realms, list) + else None + ) + if not isinstance(realm, dict) or not isinstance(realm.get("connectScopeId"), str): + raise _fail(f"realm {config.realm!r} was not visible during bootstrap discovery", config) + connect_scope_id = realm["connectScopeId"] + if not connect_scope_id: + raise _fail("bootstrap realm returned an empty connect scope", config) + + query = urllib.parse.urlencode({"connectScopeId": connect_scope_id}) + characters_url = _auth_url( + config, + f"/auth/bootstrap/worlds/{_quote(config.world)}/realms/{_quote(config.realm)}/characters?{query}", + ) + characters = _require_envelope( + _request(http_request, config, "GET", characters_url, headers=headers), + "bootstrap characters", + config, + ) + if not isinstance(characters, list): + raise _fail("bootstrap characters returned a malformed list", config) + if config.character: + if not _valid_character_name(config.character): + raise _fail("configured character name is malformed", config) + if not any( + isinstance(candidate, dict) + and _valid_character_name(candidate.get("characterName")) + and candidate.get("characterName") == config.character + for candidate in characters + ): + raise _fail("configured character was not visible during bootstrap discovery", config) + return connect_scope_id, config.character + if len(characters) > 1: + raise _fail( + "bootstrap character discovery returned multiple characters; configure an explicit character", + config, + ) + if not characters: + raise _fail( + "bootstrap character discovery returned no valid current character", + config, + ) + first = characters[0] + if not isinstance(first, dict): + raise _fail("bootstrap characters returned a malformed entry", config) + character = first.get("characterName") + if not _valid_character_name(character): + raise _fail("bootstrap characters returned a malformed name", config) + return connect_scope_id, character + + +def _connect_context( + config: SmokeConfig, + http_request: HttpRequest, + bootstrap_token: str, + request_id: str, +) -> tuple[str, str | None]: + # Discovery and connect-token issuance intentionally happen together for + # reconnect: each fresh WSS admission receives a fresh one-use cookie. + scope, character = _discover_target(config, http_request, bootstrap_token) + response = _request( + http_request, + config, + "POST", + _auth_url(config, "/auth/connect-token"), + payload={"connectScopeId": scope, "requestId": request_id}, + headers={ + "Authorization": f"Bearer {bootstrap_token}", + "Content-Type": "application/json", + }, + ) + metadata = _require_envelope(response, "connect-token issuance", config) + set_cookie = _header(response.headers, "Set-Cookie") + cookie_parts = [part.strip() for part in set_cookie.split(";")] + pair = cookie_parts[0] if cookie_parts else "" + name, separator, value = pair.partition("=") + if separator != "=" or name != "Firemud-Connect-Token" or not value: + raise _fail( + "connect-token issuance did not return a valid Firemud-Connect-Token cookie", + config, + ) + attributes: dict[str, list[str | None]] = {} + for part in cookie_parts[1:]: + attribute, equals, attribute_value = part.partition("=") + attribute = attribute.strip().lower() + if not attribute: + raise _fail("connect-token cookie protections are malformed", config) + attributes.setdefault(attribute, []).append(attribute_value.strip() if equals else None) + + def require_flag(attribute: str) -> bool: + return attributes.get(attribute) == [None] + + if not require_flag("httponly") or not require_flag("secure"): + raise _fail("connect-token cookie protections are incomplete", config) + same_site_values = attributes.get("samesite") + if ( + same_site_values is None + or len(same_site_values) != 1 + or not isinstance(same_site_values[0], str) + or same_site_values[0].casefold() != "strict" + ): + raise _fail("connect-token cookie protections are incomplete", config) + if attributes.get("path") != ["/ws/game"]: + raise _fail("connect-token cookie protections are incomplete", config) + + max_age_values = attributes.get("max-age") + if max_age_values is None or len(max_age_values) != 1: + raise _fail("connect-token cookie lifetime is invalid", config) + max_age = max_age_values[0] + if not isinstance(max_age, str) or not max_age.isascii() or not max_age.isdecimal() or max_age.startswith("0"): + raise _fail("connect-token cookie lifetime is invalid", config) + if not isinstance(metadata, dict): + raise _fail("connect-token response metadata is malformed", config) + issued_at = metadata.get("issuedAt") + expires_at = metadata.get("expiresAt") + if not isinstance(issued_at, str) or not isinstance(expires_at, str): + raise _fail("connect-token response metadata is malformed", config) + try: + issued = datetime.datetime.fromisoformat(issued_at.replace("Z", "+00:00")) + expires = datetime.datetime.fromisoformat(expires_at.replace("Z", "+00:00")) + ttl_seconds = (expires - issued).total_seconds() + cookie_seconds = int(max_age) + except (OverflowError, TypeError, ValueError): + raise _fail("connect-token response metadata is malformed", config) from None + if ( + issued.utcoffset() is None + or expires.utcoffset() is None + or ttl_seconds <= 0 + or cookie_seconds <= 0 + or cookie_seconds > ttl_seconds + ): + raise _fail("connect-token cookie lifetime exceeds its token lifetime", config) + return f"Firemud-Connect-Token={value}", character + + +def _set_receive_deadline(ws: Any, deadline: float) -> None: + setter = getattr(ws, "set_receive_deadline", None) + if callable(setter): + setter(deadline) + + +def _receive_usage(ws: Any, payload: Any) -> tuple[int, int]: + getter = getattr(ws, "last_receive_usage", None) + usage = getter() if callable(getter) else None + if ( + isinstance(usage, tuple) + and len(usage) == 2 + and all(isinstance(value, int) and not isinstance(value, bool) and value >= 0 for value in usage) + ): + return usage + return 1, _websocket_payload_size(payload) + + +def _await_command_result(ws: Any, command_type: str, config: SmokeConfig) -> dict[str, Any]: + deadline = time.monotonic() + config.timeout_seconds + received_messages = 0 + received_frames = 0 + received_bytes = 0 + while time.monotonic() < deadline: + if received_messages >= MAX_WEBSOCKET_WAIT_MESSAGES: + raise _fail(f"WebSocket receive budget exceeded while waiting for {command_type}", config) + ws.settimeout(max(0.01, deadline - time.monotonic())) + _set_receive_deadline(ws, deadline) + try: + payload = ws.recv() + except _WebSocketReceiveLimitExceeded as exc: + raise _fail( + f"WebSocket receive limits exceeded while waiting for {command_type}", + config, + ) from exc + except Exception as exc: + raise _fail(f"WebSocket closed while waiting for {command_type}", config) from exc + received_messages += 1 + frame_count, byte_count = _receive_usage(ws, payload) + received_frames += frame_count + received_bytes += byte_count + if received_frames > MAX_WEBSOCKET_WAIT_FRAMES or received_bytes > MAX_WEBSOCKET_WAIT_BYTES: + raise _fail(f"WebSocket receive budget exceeded while waiting for {command_type}", config) + try: + parsed = json.loads(payload) + except (TypeError, json.JSONDecodeError): + continue + if not isinstance(parsed, dict): + continue + if parsed.get("eventType") != "command_result" or parsed.get("commandType") != command_type: + continue + if parsed.get("accepted") is not True: + raise _fail(f"{command_type} was rejected by the first-party gameplay session", config) + return parsed + raise _fail(f"timed out waiting for structured {command_type} result", config) + + +def _require_look_view(response: dict[str, Any], config: SmokeConfig) -> tuple[str, str]: + outputs = response.get("outputs") + if not isinstance(outputs, list): + raise _fail("LOOK accepted without an authoritative LOOK view", config) + for output in outputs: + if not isinstance(output, dict) or output.get("payloadType") != "look_view": + continue + payload = output.get("payload") + if not isinstance(payload, dict): + continue + room_id = payload.get("roomId") + room_name = payload.get("roomName") + if not (isinstance(room_id, str) and room_id.strip() and isinstance(room_name, str) and room_name.strip()): + continue + if config.expected_room_id is not None and room_id != config.expected_room_id: + raise _fail("LOOK room ID did not match the expected Telnet parity room ID", config) + return room_id, room_name + raise _fail("LOOK accepted without an authoritative LOOK view", config) + + +def _await_websocket_close(ws: Any, config: SmokeConfig) -> None: + """Require websocket-client's documented close-control-frame observation.""" + recv_data = getattr(ws, "recv_data", None) + if not callable(recv_data): + raise _fail( + "first-party WSS close observation is unavailable; expected a WebSocket close opcode", + config, + ) + + deadline = time.monotonic() + config.timeout_seconds + received_messages = 0 + received_frames = 0 + received_bytes = 0 + while time.monotonic() < deadline: + if received_messages >= MAX_WEBSOCKET_WAIT_MESSAGES: + raise _fail("WebSocket receive budget exceeded while waiting for close", config) + ws.settimeout(max(0.01, deadline - time.monotonic())) + _set_receive_deadline(ws, deadline) + try: + observation = recv_data(control_frame=True) + except _WebSocketReceiveLimitExceeded as exc: + raise _fail( + "WebSocket receive limits exceeded while waiting for close", + config, + ) from exc + except Exception as exc: + raise _fail( + "first-party WSS close observation failed after LOGOUT", + config, + ) from exc + if not isinstance(observation, tuple) or len(observation) != 2 or not isinstance(observation[0], int): + raise _fail( + "first-party WSS close observation returned a malformed frame", + config, + ) + received_messages += 1 + frame_count, byte_count = _receive_usage(ws, observation[1]) + received_frames += frame_count + received_bytes += byte_count + if received_frames > MAX_WEBSOCKET_WAIT_FRAMES or received_bytes > MAX_WEBSOCKET_WAIT_BYTES: + raise _fail("WebSocket receive budget exceeded while waiting for close", config) + if observation[0] == WEBSOCKET_CLOSE_OPCODE: + return + + raise _fail( + "first-party WSS session did not receive a WebSocket close opcode after LOGOUT", + config, + ) + + +def _run_gameplay_session( + config: SmokeConfig, + websocket_factory: WebSocketFactory, + cookie: str, + character: str | None, + *, + logout: bool | None = None, +) -> dict[str, str]: + try: + ws = websocket_factory( + config.websocket_url, + config.timeout_seconds, + [f"Cookie: {cookie}", f"Origin: {config.origin}"], + ) + except Exception as exc: + raise _fail("first-party WSS connection failed", config) from exc + perform_logout = config.exercise_logout if logout is None else logout + look_room: tuple[str, str] | None = None + try: + for command in ( + "LOGIN", + f"PLAY {config.world} {config.realm} {character}" if character else f"PLAY {config.world} {config.realm}", + "LOOK", + ): + ws.send(command) + response = _await_command_result(ws, command.split(" ", 1)[0], config) + if command == "LOOK": + look_room = _require_look_view(response, config) + if perform_logout: + ws.send("LOGOUT") + _await_command_result(ws, "LOGOUT", config) + # Game Session closes the first-party transport after the accepted + # LOGOUT result. A timeout or unrelated receive error is not proof. + _await_websocket_close(ws, config) + finally: + close = getattr(ws, "close", None) + if callable(close): + close() + if look_room is None: + raise _fail("LOOK did not produce an authoritative room view", config) + return {"lookRoomId": look_room[0], "lookRoomName": look_room[1]} + + +def _require_replayed_cookie_rejected( + config: SmokeConfig, + websocket_factory: WebSocketFactory, + cookie: str, +) -> None: + """Require Gateway to reject reuse of the consumed one-use cookie.""" + try: + replay_socket = websocket_factory( + config.websocket_url, + config.timeout_seconds, + [f"Cookie: {cookie}", f"Origin: {config.origin}"], + ) + except Exception as exc: + # websocket-client exposes the failed HTTP upgrade as + # WebSocketBadStatusException.status_code/resp_headers. Never render + # the exception itself: its message can contain request details. + status_code = getattr(exc, "status_code", None) + response_headers = getattr(exc, "resp_headers", None) + error_class = ( + _header(response_headers, "X-Firemud-Handshake-Error-Class") + if isinstance(response_headers, Mapping) + else "" + ) + if status_code == 403 and error_class == "CONNECT_TOKEN_REPLAYED": + return + raise _fail( + "replayed connect-token handshake was not rejected as CONNECT_TOKEN_REPLAYED", + config, + ) from exc + close = getattr(replay_socket, "close", None) + if callable(close): + try: + close() + except Exception as exc: + raise _fail("replayed connect-token handshake was accepted", config) from exc + raise _fail("replayed connect-token handshake was accepted", config) + + +def _check_readiness(config: SmokeConfig, http_request: HttpRequest) -> None: + if not config.readiness_url: + return + response = _request(http_request, config, "GET", config.readiness_url) + payload = _require_success(response, "gateway readiness", config) + if not isinstance(payload, dict) or payload.get("status") != "UP": + raise _fail("gateway readiness returned a malformed or non-UP response", config) + + +def run_smoke( + config: SmokeConfig, + *, + http_request: HttpRequest = _default_http_request, + websocket_factory: WebSocketFactory | None = None, +) -> dict[str, Any]: + """Run the diagnostic flow; injected transports keep tests offline.""" + _validate_origin(config) + _check_readiness(config, http_request) + if websocket_factory is None: + try: + import websocket + except ImportError as exc: + raise _fail("the websocket-client package is required for WSS smoke", config) from exc + bounded_websocket = _bounded_websocket_client(websocket) + + def websocket_factory(url: str, timeout: float, headers: Sequence[str]) -> Any: + # websocket-client emits its own Origin unless the dedicated + # option is set. Keep Origin out of the raw header list so the + # handshake contains exactly one operator-supplied Origin. + return websocket.create_connection( + url, + timeout=timeout, + class_=bounded_websocket, + header=[header for header in headers if not header.lower().startswith("origin:")], + origin=config.origin, + ) + + bootstrap_token = _bootstrap(config, http_request) + sessions: list[dict[str, str]] = [] + cookie, character = _connect_context( + config, + http_request, + bootstrap_token, + f"hosted-websocket-playable-smoke-{uuid.uuid4()}", + ) + sessions.append( + _run_gameplay_session( + config, + websocket_factory, + cookie, + character, + logout=False if config.exercise_reconnect else None, + ) + ) + if config.exercise_reconnect: + _require_replayed_cookie_rejected(config, websocket_factory, cookie) + second_bootstrap = _bootstrap(config, http_request) + cookie, second_character = _connect_context( + config, + http_request, + second_bootstrap, + f"hosted-websocket-playable-reconnect-{uuid.uuid4()}", + ) + sessions.append( + _run_gameplay_session( + config, + websocket_factory, + cookie, + second_character, + logout=config.exercise_logout, + ) + ) + if config.revoke_url: + response = _request( + http_request, + config, + "POST", + config.revoke_url, + headers={ + "Cookie": cookie, + "Origin": config.origin, + "Content-Type": "application/json", + }, + ) + _require_success(response, "connect-token revocation", config) + return { + "transport": "first-party-wss", + "classification": "diagnostic-operator-smoke", + "steps": ["LOGIN", "PLAY", "LOOK"], + "sessions": len(sessions), + "logout": config.exercise_logout, + "reconnect": config.exercise_reconnect, + "replayRejected": config.exercise_reconnect, + "lookRoomId": sessions[-1]["lookRoomId"], + "lookRoomName": sessions[-1]["lookRoomName"], + } + + +def _config_from_args(args: argparse.Namespace) -> SmokeConfig: + gateway = args.gateway_base.rstrip("/") + auth_base = args.auth_base or gateway + websocket_url = args.websocket_url or ( + gateway.replace("https://", "wss://", 1).replace("http://", "ws://", 1) + "/ws/game" + ) + return SmokeConfig( + auth_api_base=auth_base, + websocket_url=websocket_url, + origin=args.origin, + auth_api_prefix=args.auth_prefix, + readiness_url=args.readiness_url, + revoke_url=args.revoke_url, + username=args.username, + password=args.password, + world=args.world, + realm=args.realm, + character=args.character, + expected_room_id=args.expected_room_id, + timeout_seconds=args.timeout, + exercise_logout=args.logout, + exercise_reconnect=args.reconnect, + ) + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--gateway-base", default=os.environ.get("SMOKE_GATEWAY_API_BASE", DEFAULT_GATEWAY_BASE)) + parser.add_argument("--auth-base", default=os.environ.get("PLAYER_EXPERIENCE_AUTH_API_BASE")) + parser.add_argument( + "--auth-prefix", default=os.environ.get("PLAYER_EXPERIENCE_AUTH_API_PREFIX", DEFAULT_AUTH_PREFIX) + ) + parser.add_argument("--websocket-url", default=os.environ.get("PLAYER_EXPERIENCE_WEBSOCKET_URL")) + parser.add_argument( + "--origin", + default=os.environ.get( + "SMOKE_FIRST_PARTY_ORIGIN", + os.environ.get("PLAYER_EXPERIENCE_ORIGIN", ""), + ), + help="Exact allowlisted first-party Origin sent on the WSS upgrade", + ) + parser.add_argument("--readiness-url", default=os.environ.get("SMOKE_GATEWAY_READINESS_URL")) + parser.add_argument("--revoke-url", default=os.environ.get("SMOKE_GATEWAY_CONNECT_TOKEN_REVOKE_URL")) + parser.add_argument("--username", default=os.environ.get("SMOKE_USERNAME", DEFAULT_USERNAME)) + parser.add_argument("--password", default=os.environ.get("SMOKE_PASSWORD", DEFAULT_PASSWORD)) + parser.add_argument("--world", default=os.environ.get("PLAYER_EXPERIENCE_WORLD", DEFAULT_WORLD)) + parser.add_argument("--realm", default=os.environ.get("PLAYER_EXPERIENCE_REALM", DEFAULT_REALM)) + parser.add_argument("--character", default=os.environ.get("PLAYER_EXPERIENCE_CHARACTER")) + parser.add_argument( + "--expected-room-id", + default=os.environ.get("SMOKE_EXPECTED_ROOM_ID", os.environ.get("PLAYER_EXPERIENCE_EXPECTED_ROOM_ID")), + help="Optional room ID from the trusted Telnet probe for live parity", + ) + parser.add_argument("--timeout", type=float, default=float(os.environ.get("SMOKE_TIMEOUT_SECONDS", "10"))) + parser.add_argument( + "--logout", + action="store_true", + help="Opt into LOGOUT diagnostics (currently expected to fail with LOGOUT_UNAVAILABLE)", + ) + parser.add_argument("--reconnect", action="store_true") + args = parser.parse_args(argv) + config = _config_from_args(args) + try: + result = run_smoke(config) + except HostedWebSocketPlayableSmokeError as exc: + print( + f"Hosted first-party WSS smoke failed: {redact_credentials(exc, config.username, config.password)}", + file=sys.stderr, + ) + return 1 + print(json.dumps(result, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/dev-tools/hosted/trust-bootstrap/verify-live-admission-boundary.py b/dev-tools/hosted/trust-bootstrap/verify-live-admission-boundary.py new file mode 100644 index 0000000000..f608fabf36 --- /dev/null +++ b/dev-tools/hosted/trust-bootstrap/verify-live-admission-boundary.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +"""Compare the live trust-bootstrap admission specs with checked-in authority.""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +import subprocess +import sys +from pathlib import Path +from typing import Any + +try: + import yaml +except ImportError: + print( + "trust-bootstrap admission verifier: PyYAML is required", + file=sys.stderr, + ) + raise SystemExit(1) + + +REPOSITORY_ROOT = Path(__file__).resolve().parents[3] +MANIFESTS = ( + Path("k8s/trust-bootstrap/issuance-admission.yaml"), + Path("k8s/trust-bootstrap/recovery-admission.yaml"), + Path("k8s/trust-bootstrap/deployment-admission.yaml"), +) +POLICY_NAMES = ( + "firemud-trust-bootstrap-certificaterequest", + "firemud-trust-bootstrap-certificaterequest-subresources", + "firemud-trust-bootstrap-certificate", + "firemud-trust-bootstrap-certificate-status", + "firemud-trust-bootstrap-ca-issuers", + "firemud-trust-ca-secret-boundary", + "firemud-trust-runtime-namespace-boundary", + "firemud-trust-runtime-binding-boundary", +) +API_VERSION = "admissionregistration.k8s.io/v1" +POLICY_KIND = "ValidatingAdmissionPolicy" +BINDING_KIND = "ValidatingAdmissionPolicyBinding" +RESOURCE_BY_KIND = { + POLICY_KIND: "validatingadmissionpolicy", + BINDING_KIND: "validatingadmissionpolicybinding", +} + + +class UniqueKeyLoader(yaml.SafeLoader): + def construct_mapping(self, node: Any, deep: bool = False) -> dict[str, Any]: + mapping: dict[str, Any] = {} + for key_node, value_node in node.value: + key = self.construct_object(key_node, deep=deep) + if key in mapping: + raise ValueError("duplicate mapping key") + mapping[key] = self.construct_object(value_node, deep=deep) + return mapping + + +UniqueKeyLoader.add_constructor( + yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, + UniqueKeyLoader.construct_mapping, +) + + +class ProofError(Exception): + def __init__(self, result: str, *, kind: str = "", name: str = "") -> None: + super().__init__(result) + self.result = result + self.kind = kind + self.name = name + + +def expected_keys() -> set[tuple[str, str]]: + return {(kind, name) for kind in (POLICY_KIND, BINDING_KIND) for name in POLICY_NAMES} + + +def load_expected_specs() -> dict[tuple[str, str], dict[str, Any]]: + expected: dict[tuple[str, str], dict[str, Any]] = {} + for relative_path in MANIFESTS: + path = REPOSITORY_ROOT / relative_path + try: + documents = yaml.load_all( + path.read_text(encoding="utf-8"), + Loader=UniqueKeyLoader, + ) + for document in documents: + if not isinstance(document, dict): + raise TypeError("manifest document is not a mapping") + kind = document.get("kind") + metadata = document.get("metadata") + spec = document.get("spec") + if ( + document.get("apiVersion") != API_VERSION + or kind not in RESOURCE_BY_KIND + or not isinstance(metadata, dict) + or not isinstance(metadata.get("name"), str) + or not isinstance(spec, dict) + ): + raise ValueError("manifest admission object is incomplete") + key = (kind, metadata["name"]) + if key not in expected_keys() or key in expected: + raise ValueError("manifest admission object set is invalid") + expected[key] = spec + except (OSError, TypeError, ValueError, yaml.YAMLError) as error: + raise ProofError("source-error", name=relative_path.as_posix()) from error + + if set(expected) != expected_keys(): + raise ProofError("source-object-set-error") + return expected + + +def empty_label_selector(value: Any) -> bool: + if value is None or value == {}: + return True + if not isinstance(value, dict): + return False + if set(value) - {"matchLabels", "matchExpressions"}: + return False + labels = value.get("matchLabels") + expressions = value.get("matchExpressions") + return labels in (None, {}) and expressions in (None, []) + + +def normalize_empty_selectors(kind: str, spec: dict[str, Any]) -> dict[str, Any]: + normalized = copy.deepcopy(spec) + parent_name = "matchConstraints" if kind == POLICY_KIND else "matchResources" + parent = normalized.get(parent_name) + if isinstance(parent, dict): + for selector_name in ("namespaceSelector", "objectSelector"): + if selector_name in parent and empty_label_selector(parent[selector_name]): + parent.pop(selector_name) + if kind == BINDING_KIND and not parent: + normalized.pop(parent_name) + elif kind == BINDING_KIND and parent is None: + normalized.pop(parent_name, None) + return normalized + + +def digest(value: Any) -> str: + encoded = json.dumps( + value, + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + ).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + +def read_live_spec(context: str, kind: str, name: str) -> dict[str, Any]: + resource = RESOURCE_BY_KIND[kind] + try: + result = subprocess.run( + [ + "kubectl", + "--context", + context, + "get", + resource, + name, + "-o", + "json", + ], + capture_output=True, + check=False, + text=True, + ) + except OSError as error: + raise ProofError("api-unavailable", kind=kind, name=name) from error + if result.returncode != 0: + raise ProofError("api-error", kind=kind, name=name) + try: + live = json.loads(result.stdout) + except (json.JSONDecodeError, TypeError) as error: + raise ProofError("invalid-json", kind=kind, name=name) from error + if ( + not isinstance(live, dict) + or live.get("apiVersion") != API_VERSION + or live.get("kind") != kind + or not isinstance(live.get("metadata"), dict) + or live["metadata"].get("name") != name + or not isinstance(live.get("spec"), dict) + ): + raise ProofError("invalid-object", kind=kind, name=name) + return live["spec"] + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--context", required=True) + arguments = parser.parse_args() + if not arguments.context.strip(): + print( + "trust-bootstrap admission verifier: context is required", + file=sys.stderr, + ) + return 1 + + try: + expected = load_expected_specs() + except ProofError as error: + label = f" source={error.name}" if error.name else "" + print( + f"admission-boundary=result={error.result}{label}", + file=sys.stderr, + ) + return 1 + + combined: list[tuple[str, str, str]] = [] + for kind, name in sorted(expected): + try: + live_spec = normalize_empty_selectors( + kind, + read_live_spec(arguments.context, kind, name), + ) + except ProofError as error: + print( + f"admission-object={kind}/{name} result={error.result}", + file=sys.stderr, + ) + return 1 + + expected_spec = normalize_empty_selectors(kind, expected[(kind, name)]) + expected_digest = digest(expected_spec) + live_digest = digest(live_spec) + if live_digest != expected_digest: + print( + f"admission-object={kind}/{name} result=spec-mismatch " + f"expected_sha256={expected_digest} observed_sha256={live_digest}", + file=sys.stderr, + ) + return 1 + print(f"admission-object={kind}/{name} result=match sha256={live_digest}") + combined.append((kind, name, live_digest)) + + summary = digest(combined) + print(f"admission-specs=pass objects={len(combined)} sha256={summary}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index 7a972e2437..c77e79b455 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -20,11 +20,28 @@ class TransientUpstreamSmokeFailure(ProbeOperationalFailure): """A startup-time upstream error that a bounded smoke retry may retry.""" +class _NoRedirectHandler(urllib.request.HTTPRedirectHandler): + def redirect_request(self, _request, _response, _code, _message, _headers, _url): + return None + + RETRYABLE_STARTUP_COMMAND_LABELS = frozenset({"WORLDS", "LOGIN"}) INVALID_COMMAND_LINE_ERROR = "commands must not contain embedded CR or LF" PLAINTEXT_TELNET_HOST_ERROR = ( "tls_enabled=False requires a localhost-equivalent Telnet host" ) +LOOK_ROOM_ID_RE = re.compile(r"(?m)^Room: .+ \(ID: ([A-Za-z0-9._:-]{1,128})\)\r?$") +ANSI_SGR_RE = re.compile(r"\x1b\[[0-9;]*m") + + +def telnet_look_room_id(response): + """Extract the authoritative room ID from the rendered LOOK view.""" + if not isinstance(response, str): + raise ProbeOperationalFailure("Telnet LOOK response is not text") + match = LOOK_ROOM_ID_RE.search(ANSI_SGR_RE.sub("", response)) + if match is None: + raise ProbeOperationalFailure("Telnet LOOK response has no canonical room ID") + return match.group(1) def is_localhost_equivalent(host): @@ -168,10 +185,13 @@ def wait_for_account_schema(startup_wait_seconds, timeout_seconds): def http_readiness_up(readiness_url, timeout_seconds): try: - with urllib.request.urlopen(readiness_url, timeout=timeout_seconds) as response: - body = response.read().decode("utf-8", errors="ignore") - return response.status < 500 and "\"status\":\"UP\"" in body.replace(" ", "") - except (urllib.error.URLError, OSError): + opener = urllib.request.build_opener(_NoRedirectHandler()) + with opener.open(readiness_url, timeout=timeout_seconds) as response: + if not 200 <= response.status < 300: + return False + body = json.loads(response.read().decode("utf-8")) + return isinstance(body, dict) and body.get("status") == "UP" + except (urllib.error.URLError, OSError, UnicodeError, ValueError): return False diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/dev-demo-workflow-contract.sh b/dev-tools/tests/dev-demo-workflow-contract.sh index b3203b830e..5dbc9d7c79 100644 --- a/dev-tools/tests/dev-demo-workflow-contract.sh +++ b/dev-tools/tests/dev-demo-workflow-contract.sh @@ -158,6 +158,53 @@ if extract_source_range "$range_fixture" '^start$' '^end$' \ exit 1 fi +# Execute the parser copied from the actual dev-demo bootstrap step. The +# ClusterIP Service exposes port 80 but forwards to the Gateway pod on 8080. +gateway_port_parser_test="$fixture_dir/test-gateway-port-parser.sh" +{ + extract_source_range "$workflow" '^ # BEGIN gateway port parser$' '^ # END gateway port parser$' \ + | sed '1d; s/^ //' + cat <<'EOF' +expect_gateway_port() { + local line="$1" + local expected="$2" + local output status + printf '%s\n' "$line" >"$PORT_FORWARD_LOG" + if output="$(parse_bootstrap_gateway_port "$PORT_FORWARD_LOG" 2>/dev/null)"; then + status=0 + else + status=$? + fi + if [[ "$expected" == reject ]]; then + [[ "$status" -ne 0 && -z "$output" ]] || { + echo "Gateway port parser accepted an invalid forwarding line: $line" >&2 + exit 1 + } + else + [[ "$status" -eq 0 && "$output" == "$expected" ]] || { + echo "Gateway port parser returned '$output' for '$line', expected '$expected'" >&2 + exit 1 + } + fi +} + +expect_gateway_port 'Forwarding from 127.0.0.1:49152 -> 8080' 49152 +expect_gateway_port 'Forwarding from 127.0.0.1:1 -> 8080' 1 +expect_gateway_port 'Forwarding from 127.0.0.1:65535 -> 8080' 65535 +expect_gateway_port 'Forwarding from 127.0.0.1:00008 -> 8080' 8 +expect_gateway_port 'Forwarding from 127.0.0.1:49152 -> 80' reject +expect_gateway_port 'Forwarding from 127.0.0.1:49152 -> 8081' reject +expect_gateway_port 'Forwarding from 0.0.0.0:49152 -> 8080' reject +expect_gateway_port 'Forwarding from [::1]:49152 -> 8080' reject +expect_gateway_port 'Forwarding from 127.0.0.1:not-a-port -> 8080' reject +expect_gateway_port 'Forwarding from 127.0.0.1:0 -> 8080' reject +expect_gateway_port 'Forwarding from 127.0.0.1:65536 -> 8080' reject +expect_gateway_port 'Forwarding from 127.0.0.1:999999 -> 8080' reject +expect_gateway_port 'arbitrary kubectl output' reject +EOF +} >"$gateway_port_parser_test" +PORT_FORWARD_LOG="$fixture_dir/gateway-port-forward.log" bash "$gateway_port_parser_test" + # Exercise the certificate workspace setup and EXIT cleanup directly. A caller # supplied root may contain unrelated files, so only the private child created # for this invocation may be removed. diff --git a/dev-tools/tests/hosted-gateway-bridge-contract.sh b/dev-tools/tests/hosted-gateway-bridge-contract.sh index 63a94ffbd8..ddf2e008b2 100644 --- a/dev-tools/tests/hosted-gateway-bridge-contract.sh +++ b/dev-tools/tests/hosted-gateway-bridge-contract.sh @@ -200,6 +200,11 @@ gateway_deployment = named("Deployment", "spring-cloud-gateway") proxy_deployment = named("Deployment", "tcp-proxy-service") gateway, gateway_env = env_map(gateway_deployment) proxy, proxy_env = env_map(proxy_deployment) +shared_config = named("ConfigMap", "firemud-config").get("data") or {} +if shared_config.get("FIREMUD_GRPC_TLS_RELOAD_ENABLED") != "true": + raise SystemExit( + "hosted shared configuration must enable gRPC TLS reload watchers for managed renewal" + ) if proxy_deployment["spec"].get("strategy") != {"type": "Recreate"}: raise SystemExit("preview TCP Proxy Deployment must use the Recreate strategy") postgres_deployment = named("Deployment", "postgres") @@ -281,12 +286,20 @@ expected_gateway = { for key, value in expected_gateway.items(): if gateway_env.get(key) != value: raise SystemExit(f"Gateway env {key} did not render as {value!r}: {gateway_env.get(key)!r}") +if "FIREMUD_TLS_READINESS_GATE_ENABLED" in gateway_env: + raise SystemExit( + "hosted Gateway must not inherit the TCP Proxy TLS readiness gate through its explicit env" + ) expected_proxy = { "GATEWAY_WS_URL": "wss://spring-cloud-gateway-mtls.pr-42.svc.cluster.local:443/ws/game", "FIREMUD_GATEWAY_WS_CLIENT_CERT_CHAIN_PATH": "/gateway-ws-client-tls/tls.crt", "FIREMUD_GATEWAY_WS_CLIENT_PRIVATE_KEY_PATH": "/gateway-ws-client-tls/tls.key", "FIREMUD_GATEWAY_WS_CA_CERT_PATH": "/gateway-ws-client-tls/ca.crt", } +if "FIREMUD_TLS_READINESS_GATE_ENABLED" in proxy_env: + raise SystemExit( + "hosted TCP Proxy must use route-specific TLS readiness instead of aggregate TLS gating" + ) for key, value in expected_proxy.items(): if proxy_env.get(key) != value: raise SystemExit(f"Proxy env {key} did not render as {value!r}: {proxy_env.get(key)!r}") diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index 4c55ceafe6..83f977983a 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -651,6 +651,12 @@ contains "$waiter" 'get secret "$secret_name" --ignore-not-found -o json' contains "$waiter" 'get namespace "$runtime_namespace" --ignore-not-found -o json' # shellcheck disable=SC2016 # Match literal shell source in the waiter. contains "$waiter" 'get hostedenvironmentidentity "$identity_name" --ignore-not-found -o json' +# shellcheck disable=SC2016 # Match literal shell source in the waiter. +contains "$waiter" 'namespace_kubeconfig="${NAMESPACE_KUBECONFIG:-}"' +# shellcheck disable=SC2016 # Match literal shell source in the waiter. +contains "$waiter" 'identity_kubeconfig="${IDENTITY_KUBECONFIG:-}"' +# shellcheck disable=SC2016 # Match literal shell source in the waiter. +contains "$waiter" 'kubectl_prefix=(--kubeconfig "$kubeconfig_path")' contains "$waiter" 'Unable to determine controller projection' contains "$waiter" 'Unable to determine runtime namespace' contains "$waiter" 'Unable to determine HostedEnvironmentIdentity' @@ -1762,7 +1768,6 @@ assert deploy_steps.index(active_request) < deploy_steps.index(deploy_requester_ assert "Remember preview runtime kubeconfig" not in deploy_by_name assert "Restore preview runtime kubeconfig" not in deploy_by_name runtime_kubeconfig_path = "${{ runner.temp }}/preview-runtime.kubeconfig" -runtime_kubeconfig_cleanup = 'rm -f -- "$RUNNER_TEMP/preview-runtime.kubeconfig"\n' runtime_kubeconfig_marker = '"$RUNNER_TEMP/preview-runtime.kubeconfig"' manager_kubeconfig_path = "${{ runner.temp }}/preview-namespace-manager.kubeconfig" manager_kubeconfig_cleanup = 'rm -f -- "$RUNNER_TEMP/preview-namespace-manager.kubeconfig"' @@ -1787,7 +1792,13 @@ for job_name, job in jobs.items(): assert runtime_kubeconfig_marker in cleanup["run"], job_name assert manager_kubeconfig_marker in cleanup["run"], job_name else: - assert cleanup["run"] == runtime_kubeconfig_cleanup, job_name + for expected_cleanup_file in ( + "preview-runtime.kubeconfig", + "preview-telnet-semantics.json", + "preview-wss-semantics.json", + "preview-playable-proof.json", + ): + assert f'"$RUNNER_TEMP/{expected_cleanup_file}"' in cleanup["run"], job_name assert steps[-1] == cleanup, job_name assert runtime_kubeconfig_jobs == {"deploy-runtime", "verify-runtime"} manager_kubeconfig_jobs = set() @@ -1812,7 +1823,7 @@ for job_name, job in jobs.items(): else: assert manager_kubeconfig_marker in cleanup["run"], job_name assert manager_kubeconfig_jobs == { - "deploy-runtime", "publish-preview-proof", "destroy-runtime" + "deploy-runtime", "verify-runtime", "publish-preview-proof", "destroy-runtime" } assert "Set up Helm" not in deploy_by_name assert not any( @@ -2139,7 +2150,7 @@ assert apply_run.count(revalidate_target) == 2 source_binding_helper = ( "bash ./dev-tools/hosted/preview/revalidate-preview-source-binding.sh" ) -assert trusted_source.count(source_binding_helper) == 9 +assert trusted_source.count(source_binding_helper) == 11 assert trusted_source.count('pull_request_json="$(gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}")"') == 1 assert "current_pull_request_json" not in trusted_source assert "(.head.repo.full_name == $repository)" not in trusted_source @@ -2289,9 +2300,37 @@ assert "Wait for exact controller identity readiness" not in deploy_by_name assert "Wait for runtime rollouts before operator validation" not in deploy_by_name verify_steps = jobs["verify-runtime"]["steps"] +assert jobs["verify-runtime"]["env"] == { + "HOSTED_PLAYABLE_EMAIL": "demo@example.com", + "HOSTED_PLAYABLE_PASSWORD": "swordfish", + "HOSTED_PLAYABLE_WORLD": "demo", + "HOSTED_PLAYABLE_REALM": "production", + "HOSTED_PLAYABLE_CHARACTER": "", +} verify_by_name = { step.get("name"): step for step in verify_steps if isinstance(step, dict) } +verify_runtime_write = verify_by_name["Write runtime kubeconfig"] +verify_manager_write = verify_by_name["Write trusted namespace-manager kubeconfig"] +verify_requester_write = verify_by_name["Write requester kubeconfig"] +assert verify_runtime_write["with"] == { + "content": "${{ secrets.TRUSTED_HOSTED_PREVIEW_RUNTIME_KUBECONFIG }}", + "path": "${{ runner.temp }}/preview-runtime.kubeconfig", + "export-to-github-env": "false", +} +assert verify_manager_write["with"] == { + "content": "${{ secrets.TRUSTED_HOSTED_PREVIEW_NAMESPACE_MANAGER_KUBECONFIG }}", + "path": "${{ runner.temp }}/preview-namespace-manager.kubeconfig", + "export-to-github-env": "false", +} +assert verify_requester_write["if"] == ( + "${{ needs.validate-target.outputs.certificate_identity_mode == 'hosted-controller' }}" +) +assert verify_requester_write["with"] == { + "content": "${{ secrets.TRUSTED_HOSTED_IDENTITY_REQUESTER_KUBECONFIG }}", + "path": "${{ runner.temp }}/hosted-identity-requester.kubeconfig", + "export-to-github-env": "false", +} proof_steps = jobs["publish-preview-proof"]["steps"] proof_by_name = { step.get("name"): step for step in proof_steps if isinstance(step, dict) @@ -2323,9 +2362,13 @@ capture_uid_step_index = next( capture_uid_step = verify_by_name[ "Capture exact runtime Namespace UID before verification" ] -assert capture_uid_step_index == verify_head_step_index + 1 +assert verify_steps.index(verify_runtime_write) < verify_steps.index(verify_manager_write) +assert verify_steps.index(verify_manager_write) < verify_steps.index(verify_requester_write) +assert verify_steps.index(verify_requester_write) < verify_head_step_index +assert verify_steps.index(verify_requester_write) < capture_uid_step_index assert capture_uid_step["id"] == "capture-runtime-namespace" assert capture_uid_step["env"] == { + "KUBECONFIG": "${{ runner.temp }}/preview-namespace-manager.kubeconfig", "PR_NUMBER": "${{ needs.validate-target.outputs.pr_number }}", "EXPECTED_BASE_SHA": "${{ needs.validate-target.outputs.base_sha }}", "EXPECTED_HEAD_SHA": "${{ needs.validate-target.outputs.head_sha }}", @@ -2357,9 +2400,12 @@ runtime_port_run = verify_by_name["Read allocated TCP port"]["run"] assert verify_by_name["Read allocated TCP port"]["if"] == ( "${{ needs.validate-target.outputs.exposure_mode == 'public' }}" ) +assert verify_by_name["Read allocated TCP port"]["env"]["KUBECONFIG"] == ( + "${{ runner.temp }}/preview-runtime.kubeconfig" +) assert "::error title=Invalid runtime Telnet port::" in runtime_port_run assert "actual value was ${port:-empty}." in runtime_port_run -verify_success_index = next( +proof_success_index = next( index for index, step in enumerate(proof_steps) if step.get("name") == "Publish trusted preview success" @@ -2369,8 +2415,8 @@ verify_failure_index = next( for index, step in enumerate(verify_steps) if step.get("name") == "Publish trusted preview verification failure" ) -verify_success = proof_steps[verify_success_index] -assert verify_success["if"] == "${{ success() }}" +proof_success = proof_steps[proof_success_index] +assert proof_success["if"] == "${{ success() }}" assert "needs.validate-target.outputs.exposure_mode == 'public'" in verify_by_name[ "Smoke hosted preview over TCP" ]["if"] @@ -2378,18 +2424,23 @@ controller_wait = verify_by_name["Wait for exact controller identity projection" assert controller_wait["if"] == ( "${{ needs.validate-target.outputs.certificate_identity_mode == 'hosted-controller' }}" ) +assert controller_wait["env"] == { + "KUBECONFIG": "${{ runner.temp }}/preview-runtime.kubeconfig", + "NAMESPACE_KUBECONFIG": "${{ runner.temp }}/preview-namespace-manager.kubeconfig", + "IDENTITY_KUBECONFIG": "${{ runner.temp }}/hosted-identity-requester.kubeconfig", +} assert '"${{ needs.validate-target.outputs.exposure_mode }}"' in controller_wait["run"] -final_uid_step_index = next( +proof_final_uid_step_index = next( index for index, step in enumerate(proof_steps) if step.get("name") == "Revalidate exact source binding and runtime Namespace UID before proof publication" ) -final_uid_step = proof_by_name[ +proof_final_uid_step = proof_by_name[ "Revalidate exact source binding and runtime Namespace UID before proof publication" ] -assert final_uid_step_index + 1 == verify_success_index -assert final_uid_step["env"] == { +assert proof_final_uid_step_index + 1 == proof_success_index +assert proof_final_uid_step["env"] == { "GH_TOKEN": "${{ github.token }}", "KUBECONFIG": "${{ runner.temp }}/preview-namespace-manager.kubeconfig", "PR_NUMBER": "${{ needs.validate-target.outputs.pr_number }}", @@ -2405,12 +2456,12 @@ assert final_uid_step["env"] == { "${{ needs.verify-runtime.outputs.runtime_namespace_uid }}" ), } -final_uid_run = final_uid_step["run"] -source_revalidation_position = final_uid_run.index(source_binding_helper) -namespace_lookup_position = final_uid_run.index( +proof_final_uid_run = proof_final_uid_step["run"] +source_revalidation_position = proof_final_uid_run.index(source_binding_helper) +namespace_lookup_position = proof_final_uid_run.index( 'kubectl get namespace "$RUNTIME_NAMESPACE" --ignore-not-found -o json' ) -uid_comparison_position = final_uid_run.index( +uid_comparison_position = proof_final_uid_run.index( 'IFS=\'|\' read -r namespace_uid namespace_resource_version <<<"$namespace_identity"' ) assert source_revalidation_position < namespace_lookup_position < uid_comparison_position @@ -2423,29 +2474,158 @@ for required in ( '::error title=Missing deployed preview Namespace UID::The deploy job did not publish its Namespace UID.', '::error title=Preview runtime proof fence failed::', ): - assert required in final_uid_run, required -proof_tuple_step = proof_by_name[ - "Revalidate exact source binding and runtime Namespace UID before proof publication" + assert required in proof_final_uid_run, required +gate2_final_uid_step_index = next( + index + for index, step in enumerate(verify_steps) + if step.get("name") + == "Revalidate exact source binding and runtime Namespace UID after diagnostic evidence" +) +gate2_final_uid_step = verify_by_name[ + "Revalidate exact source binding and runtime Namespace UID after diagnostic evidence" ] -assert proof_tuple_step["env"] == { - "KUBECONFIG": "${{ runner.temp }}/preview-namespace-manager.kubeconfig", +assert gate2_final_uid_step["env"] == { "GH_TOKEN": "${{ github.token }}", + "KUBECONFIG": "${{ runner.temp }}/preview-namespace-manager.kubeconfig", "PR_NUMBER": "${{ needs.validate-target.outputs.pr_number }}", - "EXPECTED_BASE_SHA": "${{ needs.validate-target.outputs.base_sha }}", "EXPECTED_HEAD_SHA": "${{ needs.validate-target.outputs.head_sha }}", + "EXPECTED_BASE_SHA": "${{ needs.validate-target.outputs.base_sha }}", "EXPECTED_MERGE_SHA": "${{ needs.validate-target.outputs.merge_sha }}", - "EXPECTED_IMAGE_TAG": "${{ needs.validate-target.outputs.image_tag }}", "RUNTIME_NAMESPACE": "${{ needs.validate-target.outputs.namespace }}", "EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID": ( "${{ needs.deploy-runtime.outputs.runtime_namespace_uid }}" ), - "CAPTURED_RUNTIME_NAMESPACE_UID": ( - "${{ needs.verify-runtime.outputs.runtime_namespace_uid }}" - ), + "IMAGE_TAG": "${{ needs.validate-target.outputs.image_tag }}", } -proof_tuple_run = proof_tuple_step["run"] +gate2_final_uid_run = gate2_final_uid_step["run"] +gate2_source_revalidation_position = gate2_final_uid_run.index(source_binding_helper) +gate2_namespace_lookup_position = gate2_final_uid_run.index( + 'kubectl get namespace "$RUNTIME_NAMESPACE" -o json' +) +gate2_uid_comparison_position = gate2_final_uid_run.index( + '[[ "$observed_uid" == "$EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID" ]] || {' +) +assert ( + gate2_source_revalidation_position + < gate2_namespace_lookup_position + < gate2_uid_comparison_position +) for required in ( - 'kubectl get namespace "$RUNTIME_NAMESPACE" --ignore-not-found -o json', + '"firemud.dev/preview"', + '"firemud.dev/pr-number"', + "firemud.dev/requested-preview-base-sha", + "firemud.dev/requested-preview-merge-sha", + "firemud.dev/last-preview-base-sha", + "firemud.dev/last-preview-merge-sha", + "firemud.dev/last-preview-image-tag", + "firemud.dev/last-preview-head-sha", + "EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID", + "Preview runtime Namespace UID changed after diagnostics", +): + assert required in gate2_final_uid_run, required +verify_setup_python = verify_by_name["Set up canonical Python dependencies"] +assert verify_setup_python["uses"] == "./.github/actions/setup-python" +assert verify_setup_python["with"] == {"requirements": "smoke"} +telnet_diagnostic = verify_by_name["Smoke hosted preview over TCP"] +wss_diagnostic = verify_by_name["Smoke first-party hosted WSS and compare Telnet LOOK"] +proof_writer = verify_by_name["Write bounded hosted playable diagnostic evidence"] +proof_upload = verify_by_name["Upload bounded hosted playable diagnostic evidence"] +final_evidence_recheck = verify_by_name[ + "Revalidate exact source binding and runtime Namespace UID after diagnostic evidence" +] +public_controller_condition = ( + "${{ needs.validate-target.outputs.exposure_mode == 'public' && " + "needs.validate-target.outputs.certificate_identity_mode == 'hosted-controller' }}" +) +assert telnet_diagnostic["env"]["CERTIFICATE_IDENTITY_MODE"] == ( + "${{ needs.validate-target.outputs.certificate_identity_mode }}" +) +assert 'if [[ "$CERTIFICATE_IDENTITY_MODE" == hosted-controller ]]; then' in telnet_diagnostic["run"] +assert 'export SMOKE_SEMANTIC_OUT="$RUNNER_TEMP/preview-telnet-semantics.json"' in telnet_diagnostic["run"] +for target, source in ( + ("SMOKE_LOGIN_EMAIL", "HOSTED_PLAYABLE_EMAIL"), + ("SMOKE_PASSWORD", "HOSTED_PLAYABLE_PASSWORD"), + ("SMOKE_WORLD", "HOSTED_PLAYABLE_WORLD"), + ("SMOKE_REALM", "HOSTED_PLAYABLE_REALM"), + ("SMOKE_CHARACTER", "HOSTED_PLAYABLE_CHARACTER"), +): + assert f'export {target}="${source}"' in telnet_diagnostic["run"] +for flag, source in ( + ("username", "HOSTED_PLAYABLE_EMAIL"), + ("password", "HOSTED_PLAYABLE_PASSWORD"), + ("world", "HOSTED_PLAYABLE_WORLD"), + ("realm", "HOSTED_PLAYABLE_REALM"), + ("character", "HOSTED_PLAYABLE_CHARACTER"), +): + assert f'--{flag} "${source}"' in wss_diagnostic["run"] +for required_wss_argument in ( + '--gateway-base "https://${PREVIEW_HOSTNAME}"', + '--auth-base "https://${PREVIEW_HOSTNAME}"', + '--auth-prefix "/api/account"', + '--websocket-url "wss://${PREVIEW_HOSTNAME}/ws/game"', + '--origin "https://${PREVIEW_HOSTNAME}"', + '--readiness-url ""', + '--revoke-url ""', + '--expected-room-id "$room_id"', + "--reconnect", +): + assert required_wss_argument in wss_diagnostic["run"], required_wss_argument +for diagnostic in (wss_diagnostic, proof_writer, proof_upload): + assert diagnostic["if"] == public_controller_condition +assert proof_writer["env"]["NAMESPACE_KUBECONFIG"] == ( + "${{ runner.temp }}/preview-namespace-manager.kubeconfig" +) +assert proof_writer["env"]["IDENTITY_KUBECONFIG"] == ( + "${{ runner.temp }}/hosted-identity-requester.kubeconfig" +) +assert proof_writer["env"]["RUNTIME_KUBECONFIG"] == ( + "${{ runner.temp }}/preview-runtime.kubeconfig" +) +for credential_path in ( + '"$NAMESPACE_KUBECONFIG"', + '"$IDENTITY_KUBECONFIG"', + '"$RUNTIME_KUBECONFIG"', +): + assert credential_path in proof_writer["run"] +assert "--expected-room-id \"$room_id\"" in wss_diagnostic["run"] +assert "--reconnect" in wss_diagnostic["run"] +assert "--logout" not in wss_diagnostic["run"] +assert '.logout == false' in wss_diagnostic["run"] +assert '.replayRejected == true' in wss_diagnostic["run"] +assert '.steps == ["LOGIN", "PLAY", "LOOK"]' in wss_diagnostic["run"] +assert "write-playable-proof.py" in proof_writer["run"] +assert "--base-sha \"$BASE_SHA\"" in proof_writer["run"] +assert "--merge-sha \"$MERGE_SHA\"" in proof_writer["run"] +assert "--telnet-outcome passed --wss-outcome passed" in proof_writer["run"] +assert proof_upload["with"]["path"] == "${{ runner.temp }}/preview-playable-proof.json" +assert proof_upload["with"]["if-no-files-found"] == "error" +assert proof_upload["with"]["retention-days"] == 7 +assert "revalidate-preview-source-binding.sh" in final_evidence_recheck["run"] +assert "firemud.dev/requested-preview-base-sha" in final_evidence_recheck["run"] +assert "firemud.dev/requested-preview-merge-sha" in final_evidence_recheck["run"] +assert "firemud.dev/last-preview-base-sha" in final_evidence_recheck["run"] +assert "firemud.dev/last-preview-merge-sha" in final_evidence_recheck["run"] +assert "firemud.dev/last-preview-image-tag" in final_evidence_recheck["run"] +assert "firemud.dev/last-preview-head-sha" in final_evidence_recheck["run"] +assert "EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID" in final_evidence_recheck["run"] +assert ( + verify_steps.index(telnet_diagnostic) + < verify_steps.index(wss_diagnostic) + < verify_steps.index( + verify_by_name["Revalidate exact source binding and runtime Namespace UID before diagnostics"] + ) + < verify_steps.index(proof_writer) + < verify_steps.index(final_evidence_recheck) + < verify_steps.index(proof_upload) +) +for required in ( + '"firemud.dev/preview"', + '"firemud.dev/pr-number"', + '"firemud.dev/requested-preview-head-sha"', + '"firemud.dev/last-preview-head-sha"', + '"$CAPTURED_RUNTIME_NAMESPACE_UID" == "$EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID"', + '::error title=Missing deployed preview Namespace UID::The deploy job did not publish its Namespace UID.', + '::error title=Preview runtime proof fence failed::', 'select($metadata.uid == $expected_namespace_uid)', '"firemud.dev/proof-preview-base-sha=${EXPECTED_BASE_SHA}"', '"firemud.dev/proof-preview-head-sha=${EXPECTED_HEAD_SHA}"', @@ -2454,7 +2634,7 @@ for required in ( '"firemud.dev/proof-preview-namespace-uid=${namespace_uid}"', '--resource-version "$namespace_resource_version"', ): - assert required in proof_tuple_run, required + assert required in proof_final_uid_run, required verify_failure = verify_steps[verify_failure_index] assert verify_failure["if"] == "${{ !cancelled() && failure() }}" assert verify_failure["env"] == { @@ -2469,23 +2649,320 @@ assert verify_failure["env"] == { "EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID": ( "${{ needs.deploy-runtime.outputs.runtime_namespace_uid }}" ), + "KUBECONFIG": "${{ runner.temp }}/preview-namespace-manager.kubeconfig", } failure_script = verify_failure["with"]["script"] -for fragment in ( - 'const { execFileSync } = require("node:child_process");', - '"--ignore-not-found"', - "JSON.parse(namespaceJson)", - "observedUid !== process.env.EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID", - "Skipping stale preview verification failure publication", - "core.warning(", -): - assert fragment in failure_script, fragment -assert 'mode: "failure"' in failure_script -assert 'markerPolicy: "replace"' in failure_script -assert 'statePolicy: "expected-open"' in failure_script -assert 'telnetPort: "unavailable"' in failure_script -assert 'failureStage: "verify-runtime"' in failure_script -assert verify_failure["uses"] == verify_success["uses"] +assert verify_failure["uses"] == proof_success["uses"] +proof_failure = proof_by_name["Publish trusted preview proof failure"] +assert proof_failure["if"] == "${{ !cancelled() && failure() }}" +assert proof_failure["env"] == { + "KUBECONFIG": "${{ runner.temp }}/preview-namespace-manager.kubeconfig", + "PREVIEW_PR_NUMBER": "${{ needs.validate-target.outputs.pr_number }}", + "PREVIEW_HEAD_SHA": "${{ needs.validate-target.outputs.head_sha }}", + "PREVIEW_BASE_SHA": "${{ needs.validate-target.outputs.base_sha }}", + "PREVIEW_MERGE_SHA": "${{ needs.validate-target.outputs.merge_sha }}", + "PREVIEW_IMAGE_TAG": "${{ needs.validate-target.outputs.image_tag }}", + "PREVIEW_HOSTNAME": "${{ needs.validate-target.outputs.hostname }}", + "PREVIEW_EXPOSURE_MODE": "${{ needs.validate-target.outputs.exposure_mode }}", + "RUNTIME_NAMESPACE": "${{ needs.validate-target.outputs.namespace }}", + "EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID": ( + "${{ needs.deploy-runtime.outputs.runtime_namespace_uid }}" + ), +} + +failure_scripts = ( + ("verification", failure_script), + ("proof", proof_failure["with"]["script"]), +) +for failure_kind, inline_failure_script in failure_scripts: + for fragment in ( + 'const { execFileSync } = require("node:child_process");', + '"--ignore-not-found"', + "JSON.parse(namespaceJson)", + '"firemud.dev/requested-preview-base-sha"', + '"firemud.dev/requested-preview-head-sha"', + '"firemud.dev/requested-preview-merge-sha"', + '"firemud.dev/requested-preview-image-tag"', + '"firemud.dev/last-preview-base-sha"', + '"firemud.dev/last-preview-head-sha"', + '"firemud.dev/last-preview-merge-sha"', + '"firemud.dev/last-preview-image-tag"', + "metadata.uid !== expectedUid", + "process.env.RUNTIME_NAMESPACE !== expectedNamespace", + f"Skipping stale preview {failure_kind} failure publication", + 'markerPolicy: "preserve-reclaimed"', + 'statePolicy: "expected-open"', + 'telnetPort: "unavailable"', + 'failureStage: "verify-runtime"', + ): + assert fragment in inline_failure_script, (failure_kind, fragment) + assert 'mode: "failure"' in inline_failure_script + +node_failure_fence_harness = r""" +const assert = require("node:assert/strict"); +const { publishPreviewComment: publishRealPreviewComment } = require( + process.env.PUBLISHER_PATH, +); +const sourceTuple = { + "firemud.dev/requested-preview-base-sha": process.env.PREVIEW_BASE_SHA, + "firemud.dev/requested-preview-head-sha": process.env.PREVIEW_HEAD_SHA, + "firemud.dev/requested-preview-merge-sha": process.env.PREVIEW_MERGE_SHA, + "firemud.dev/requested-preview-image-tag": process.env.PREVIEW_IMAGE_TAG, + "firemud.dev/last-preview-base-sha": process.env.PREVIEW_BASE_SHA, + "firemud.dev/last-preview-head-sha": process.env.PREVIEW_HEAD_SHA, + "firemud.dev/last-preview-merge-sha": process.env.PREVIEW_MERGE_SHA, + "firemud.dev/last-preview-image-tag": process.env.PREVIEW_IMAGE_TAG, +}; +const reclaimedMarker = ""; + +function namespaceFor(uid, annotationOverrides = {}) { + return { + metadata: { + name: "pr-42", + uid, + labels: { "firemud.dev/preview": "true", "firemud.dev/pr-number": "42" }, + annotations: { ...sourceTuple, ...annotationOverrides }, + }, + }; +} + +async function runScenario(scenario, inlineScript) { + let comments = []; + const mutations = []; + const publishCalls = []; + const core = { info() {}, notice() {}, warning() {} }; + const context = { repo: { owner: "FireMUD", repo: "FireMUD" } }; + const github = { + rest: { + pulls: { + async get() { + return { + data: { + state: "open", + head: { sha: process.env.PREVIEW_HEAD_SHA }, + merge_commit_sha: process.env.PREVIEW_MERGE_SHA, + base: { ref: "main" }, + }, + }; + }, + }, + git: { + async getRef() { + return { data: { object: { sha: process.env.PREVIEW_BASE_SHA } } }; + }, + }, + repos: { + async getCommit() { + return { + data: { + sha: process.env.PREVIEW_MERGE_SHA, + parents: [ + { sha: process.env.PREVIEW_BASE_SHA }, + { sha: process.env.PREVIEW_HEAD_SHA }, + ], + }, + }; + }, + }, + issues: { + async listComments() { + return { data: comments }; + }, + async createComment({ body }) { + mutations.push({ type: "create", body }); + comments.push({ + id: 3, + created_at: "2026-01-03T00:00:00Z", + user: { login: "github-actions[bot]" }, + body, + }); + }, + async updateComment({ comment_id, body }) { + mutations.push({ type: "update", id: comment_id, body }); + comments = comments.map((comment) => + comment.id === comment_id ? { ...comment, body } : comment, + ); + }, + async deleteComment({ comment_id }) { + mutations.push({ type: "delete", id: comment_id }); + comments = comments.filter((comment) => comment.id !== comment_id); + }, + }, + }, + async paginate() { + return comments; + }, + }; + + if (scenario === "exact-reclaimed") { + comments = [ + { + id: 1, + created_at: "2026-01-01T00:00:00Z", + user: { login: "github-actions[bot]" }, + body: "\n### Preview Summary\nold failure", + }, + { + id: 2, + created_at: "2026-01-02T00:00:00Z", + user: { login: "github-actions[bot]" }, + body: `\n### Preview Summary\n${reclaimedMarker}\nPreview unavailable`, + }, + ]; + } else if (scenario !== "exact") { + comments = [ + { + id: 2, + created_at: "2026-01-02T00:00:00Z", + user: { login: "github-actions[bot]" }, + body: `\n### Preview Summary\n${reclaimedMarker}\nPreview unavailable`, + }, + ]; + } + + function requireForWorkflow(moduleName) { + if (moduleName === "node:child_process") { + return { + execFileSync(binary, args) { + assert.equal(binary, "kubectl"); + assert.deepEqual(args, [ + "get", + "namespace", + process.env.RUNTIME_NAMESPACE, + "--ignore-not-found", + "-o", + "json", + ]); + if (scenario === "error") throw new Error("redacted kube read failure"); + if (scenario === "absent") return ""; + if (scenario === "malformed") return "{"; + if (scenario === "malformed-object") return JSON.stringify({ metadata: { uid: 17 } }); + if (scenario === "recreated") return JSON.stringify(namespaceFor("uid-recreated")); + let namespace = namespaceFor("uid-expected"); + if (scenario.startsWith("wrong-annotation:")) { + const annotation = scenario.slice("wrong-annotation:".length); + namespace.metadata.annotations[annotation] = "wrong-tuple-value"; + } + if (scenario === "missing-uid") delete namespace.metadata.uid; + if (scenario === "missing-name") delete namespace.metadata.name; + if (scenario === "wrong-name") namespace.metadata.name = "pr-43"; + if (scenario === "missing-labels") delete namespace.metadata.labels; + if (scenario === "wrong-preview-label") { + namespace.metadata.labels["firemud.dev/preview"] = "false"; + } + if (scenario === "wrong-pr-number-label") { + namespace.metadata.labels["firemud.dev/pr-number"] = "43"; + } + if (scenario === "missing-annotations") delete namespace.metadata.annotations; + return JSON.stringify(namespace); + }, + }; + } + if (moduleName.endsWith("/publish-preview-comment.js")) { + return { + async publishPreviewComment(options) { + publishCalls.push(options); + return publishRealPreviewComment({ + ...options, + summaryExecutor: () => "failure summary from exact tuple\n", + }); + }, + }; + } + throw new Error(`Unexpected workflow require: ${moduleName}`); + } + + const runInlineScript = new Function( + "github", + "context", + "core", + "require", + `return (async () => {\n${inlineScript}\n})()`, + ); + await runInlineScript(github, context, core, requireForWorkflow); + + const expectedPublication = scenario.startsWith("exact"); + assert.equal(publishCalls.length, expectedPublication ? 1 : 0, scenario); + if (!expectedPublication) { + assert.equal(mutations.length, 0, `${scenario} must not overwrite a reclaimed or current status`); + assert.equal(comments.length, 1); + assert.match(comments[0].body, /firemud-preview-reclaimed/); + return; + } + + assert.equal(publishCalls[0].mode, "failure"); + assert.equal(publishCalls[0].markerPolicy, "preserve-reclaimed"); + assert.equal(publishCalls[0].failureStage, "verify-runtime"); + if (scenario === "exact") { + assert.equal(mutations.length, 1); + assert.equal(mutations[0].type, "create"); + assert.match(mutations[0].body, /failure summary from exact tuple/); + } else { + assert.ok(mutations.some((mutation) => mutation.type === "update")); + assert.ok(mutations.some((mutation) => mutation.type === "delete")); + assert.equal(comments.length, 1); + assert.match(comments[0].body, /firemud-preview-reclaimed/); + assert.doesNotMatch(comments[0].body, /failure summary from exact tuple/); + } +} + +(async () => { + const scenarios = [ + "absent", + "recreated", + "malformed", + "malformed-object", + "missing-uid", + "missing-name", + "wrong-name", + "missing-labels", + "wrong-preview-label", + "wrong-pr-number-label", + "missing-annotations", + "error", + "exact", + "exact-reclaimed", + ...Object.keys(sourceTuple).map((annotation) => `wrong-annotation:${annotation}`), + ]; + for (const scenario of scenarios) { + await runScenario(scenario, process.env.INLINE_FAILURE_SCRIPT); + } +})().catch((error) => { + process.stderr.write(`${error.stack || error}\n`); + process.exitCode = 1; +}); +""" +for failure_kind, inline_failure_script in failure_scripts: + node_environment = os.environ.copy() + node_environment.update( + { + "INLINE_FAILURE_SCRIPT": inline_failure_script, + "PUBLISHER_PATH": str( + Path(sys.argv[1]).parents[2] + / "dev-tools/hosted/preview/publish-preview-comment.js" + ), + "PREVIEW_PR_NUMBER": "42", + "PREVIEW_HEAD_SHA": "b" * 40, + "PREVIEW_BASE_SHA": "a" * 40, + "PREVIEW_MERGE_SHA": "c" * 40, + "PREVIEW_IMAGE_TAG": f"pr-merge-{'c' * 40}", + "PREVIEW_HOSTNAME": "pr-42.preview.firemud.test", + "RUNTIME_NAMESPACE": "pr-42", + "EXPECTED_DEPLOYED_RUNTIME_NAMESPACE_UID": "uid-expected", + } + ) + failure_fence_result = subprocess.run( + ["node", "-e", node_failure_fence_harness], + cwd=Path(sys.argv[1]).parents[2], + env=node_environment, + capture_output=True, + text=True, + ) + assert failure_fence_result.returncode == 0, ( + failure_kind, + failure_fence_result.stdout, + failure_fence_result.stderr, + ) destroy_steps = jobs["destroy-runtime"]["steps"] destroy_by_name = { @@ -5729,7 +6206,16 @@ cat >"$waiter_stub_dir/kubectl" <<'SH' set -euo pipefail scenario="${WAITER_SCENARIO:?}" +kubectl_kubeconfig="" +if [[ "${1:-}" == --kubeconfig ]]; then + [[ $# -ge 3 ]] + kubectl_kubeconfig="$2" + shift 2 +fi printf '%s\n' "$*" >>"${WAITER_KUBECTL_LOG:?}" +if [[ -n "${WAITER_KUBECONFIG_LOG:-}" ]]; then + printf '%s\t%s\n' "$kubectl_kubeconfig" "$*" >>"$WAITER_KUBECONFIG_LOG" +fi next_count() { local name="$1" @@ -6073,6 +6559,35 @@ run_active_waiter_fixture namespace-transport-exhaustion 45 3 2 'Unable to conne run_active_waiter_fixture identity-transport-recovery 0 6 2 run_active_waiter_fixture identity-transport-exhaustion 46 6 2 'Unable to connect to the server' +# Trusted verification keeps runtime data-plane credentials separate from the +# control-plane Namespace and HostedEnvironmentIdentity reads. +credential_separation_log="$TEMP_DIR/active-credential-separation.kubectl.log" +credential_separation_count_root="$TEMP_DIR/active-credential-separation.counts" +credential_separation_output="$TEMP_DIR/active-credential-separation.output" +credential_separation_error="$TEMP_DIR/active-credential-separation.error" +mkdir -p "$credential_separation_count_root" +: >"$credential_separation_log" +env \ + PATH="$waiter_stub_dir:$PATH" \ + WAITER_SCENARIO=success \ + WAITER_EXPECTED_HEAD=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \ + WAITER_COUNT_ROOT="$credential_separation_count_root" \ + WAITER_KUBECTL_LOG="$TEMP_DIR/active-credential-separation.calls.log" \ + WAITER_KUBECONFIG_LOG="$credential_separation_log" \ + KUBECONFIG="$TEMP_DIR/runtime.kubeconfig" \ + NAMESPACE_KUBECONFIG="$TEMP_DIR/namespace-manager.kubeconfig" \ + IDENTITY_KUBECONFIG="$TEMP_DIR/requester.kubeconfig" \ + bash "$waiter" pr-42 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa pr-42 60 \ + >"$credential_separation_output" 2>"$credential_separation_error" +grep -Fqx -- "$TEMP_DIR/namespace-manager.kubeconfig$(printf '\t')get namespace pr-42 --ignore-not-found -o json" \ + "$credential_separation_log" +grep -Fqx -- "$TEMP_DIR/requester.kubeconfig$(printf '\t')-n firemud-system get hostedenvironmentidentity pr-42 --ignore-not-found -o json" \ + "$credential_separation_log" +if grep -Fq -- "$TEMP_DIR/runtime.kubeconfig" "$credential_separation_log"; then + echo "active waiter used the runtime kubeconfig for control-plane reads" >&2 + exit 1 +fi + # Every waiter mode keeps the existing positive-integer diagnostic while # enforcing the shared bounded timeout ceiling. run_waiter_rejects_timeout() { diff --git a/dev-tools/tests/hosted-telnet-tls-contract.sh b/dev-tools/tests/hosted-telnet-tls-contract.sh index d88f707656..70cf477c1e 100644 --- a/dev-tools/tests/hosted-telnet-tls-contract.sh +++ b/dev-tools/tests/hosted-telnet-tls-contract.sh @@ -16,6 +16,9 @@ assert 'ca_file = os.environ.get("SMOKE_TELNET_CA_FILE") or None' in script, ( ) assert "tls_server_hostname=host" in script, "hosted Telnet smoke must set SNI/hostname" assert "tls_ca_file=ca_file" in script, "hosted Telnet smoke must use the CA override" +assert "realm=realm" in script and "character=character" in script, ( + "hosted Telnet smoke must use the trusted WSS realm and character scope" +) assert "_create_unverified_context" not in script, ( "hosted Telnet smoke must not disable certificate verification" ) @@ -74,6 +77,21 @@ from pathlib import Path import yaml documents = list(yaml.safe_load_all(Path(sys.argv[1]).read_text(encoding="utf-8"))) +proxy_deployment = next( + document + for document in documents + if document.get("kind") == "Deployment" + and document.get("metadata", {}).get("name") == "tcp-proxy-service" +) +proxy_container = next( + container + for container in proxy_deployment["spec"]["template"]["spec"]["containers"] + if container.get("name") == "tcp-proxy-service" +) +proxy_env = {item["name"]: item.get("value") for item in proxy_container.get("env", [])} +assert "FIREMUD_TLS_READINESS_GATE_ENABLED" not in proxy_env, ( + "hosted Telnet TLS must use the route-specific listener TLS readiness gate" +) service = next( document for document in documents diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..affc4ae136 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,44 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1503,6 +1541,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1973,6 +2020,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2005,13 +2053,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2025,8 +2076,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2037,6 +2104,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index 5fbb6ff309..74afd34ab5 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -29,6 +29,7 @@ command -v openssl >/dev/null 2>&1 || { python3 - <<'PY' "$ROOT_DIR" import contextlib +import http.server import io import json import socket @@ -44,6 +45,13 @@ from unittest.mock import patch root = Path(sys.argv[1]) sys.path.insert(0, str(root / "dev-tools" / "smoke")) +hosted_telnet_smoke = ( + root / "dev-tools" / "hosted" / "shared" / "hosted-login-look-smoke.sh" +).read_text(encoding="utf-8") +assert "step_results=step_results" in hosted_telnet_smoke +assert 'step["response"] for step in step_results if step["label"] == "LOOK"' in hosted_telnet_smoke +assert "telnet_look_room_id(responses[-1])" not in hosted_telnet_smoke + import smoke_common from smoke_common import ( open_telnet_socket, @@ -52,6 +60,17 @@ from smoke_common import ( run_websocket_smoke_session, ) +shared_scope_steps = smoke_common.login_play_look_steps( + "demo@example.com", "swordfish", "demo", "OK WORLDS", "OK LOGIN", "OK PLAY", "OK LOOK", + realm="production", character="Ada", +) +assert shared_scope_steps[2][0] == "PLAY demo production Ada" +default_character_steps = smoke_common.login_play_look_steps( + "demo@example.com", "swordfish", "demo", "OK WORLDS", "OK LOGIN", "OK PLAY", "OK LOOK", + realm="production", character=None, +) +assert default_character_steps[2][0] == "PLAY demo production" + for local_host in ( "localhost", @@ -79,6 +98,105 @@ for remote_host in ( assert not smoke_common.is_localhost_equivalent(remote_host), remote_host +class FakeReadinessResponse: + def __init__(self, status, body): + self.status = status + self.body = body + + def __enter__(self): + return self + + def __exit__(self, *_args): + return False + + def read(self): + return self.body + + +class FakeReadinessOpener: + def __init__(self, response): + self.response = response + + def open(self, _url, timeout): + assert timeout == 1 + return self.response + + +for status, body, expected in ( + (200, b'{"status":"UP"}', True), + (204, b'{"status":"UP"}', True), + (302, b'{"status":"UP"}', False), + (404, b'{"status":"UP"}', False), + (200, b'{"detail":"\\"status\\":\\"UP\\"","status":"DOWN"}', False), + (200, b'{"components":{"status":"UP"}}', False), + (200, b'{"status":"up"}', False), + (200, b'not-json', False), + (200, b'\xff', False), +): + with patch.object( + smoke_common.urllib.request, + "build_opener", + return_value=FakeReadinessOpener(FakeReadinessResponse(status, body)), + ): + assert smoke_common.http_readiness_up("https://example.test/readiness", 1) is expected + + +class ReadinessRedirectHandler(http.server.BaseHTTPRequestHandler): + requested_paths = [] + + def do_GET(self): + self.requested_paths.append(self.path) + if self.path == "/actuator/health/readiness": + self.send_response(302) + self.send_header("Location", "/actuator/health/liveness") + self.end_headers() + return + if self.path == "/actuator/health/liveness": + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(b'{"status":"UP"}') + return + self.send_error(404) + + def log_message(self, _format, *_args): + pass + + +readiness_server = http.server.ThreadingHTTPServer( + ("127.0.0.1", 0), ReadinessRedirectHandler +) +readiness_server.timeout = 1 +readiness_thread = threading.Thread(target=readiness_server.serve_forever, daemon=True) +ReadinessRedirectHandler.requested_paths.clear() +readiness_thread.start() +try: + readiness_url = ( + f"http://127.0.0.1:{readiness_server.server_port}/actuator/health/readiness" + ) + assert smoke_common.http_readiness_up(readiness_url, 1) is False + assert ReadinessRedirectHandler.requested_paths == ["/actuator/health/readiness"] +finally: + readiness_server.shutdown() + readiness_server.server_close() + readiness_thread.join(timeout=2) +assert not readiness_thread.is_alive() + +assert smoke_common.telnet_look_room_id( + "OK LOOK\n\x1b[32mRoom: \x1b[0mStart (ID: room-123)\nShort: A room\n" +) == "room-123" +assert smoke_common.telnet_look_room_id( + "OK LOOK\r\nRoom: Start (ID: room-123)\r\nShort: A room\r\n" +) == "room-123" +for malformed_look in ("OK LOOK", "Room: Start (ID: )", "Room: Start (ID: x y)"): + try: + smoke_common.telnet_look_room_id(malformed_look) + except smoke_common.ProbeOperationalFailure: + pass + else: + raise AssertionError("malformed Telnet LOOK view accepted") + + class FakeSession: def __init__(self, chunks=None): self.chunks = list(chunks or []) @@ -804,6 +922,42 @@ assert [result["response"] for result in command_plan_results] == [ "OK SAY hello", ] assert command_plan_session.closed is True + + +class SplitLookSession(CommandResponseSession): + def sendall(self, payload): + super().sendall(payload) + if payload.startswith(b"LOOK"): + self.chunks = [ + "OK LOOK\nRoom: Start (ID: room-", + "123)\nShort: A room\n", + ] + + +split_look_results = [] +split_look_chunks = run_telnet_smoke_session( + "example.test", + 2323, + [ + ("LOGIN demo swordfish", ["OK LOGIN"], "LOGIN"), + ("PLAY demo", ["OK PLAY"], "PLAY"), + ("LOOK", ["OK LOOK"], "LOOK"), + ], + 1, + open_session=lambda: SplitLookSession(["OK LOGIN\n", "OK PLAY\n", "OK LOOK\n"]), + step_results=split_look_results, + tls_enabled=False, +) +assert smoke_common.telnet_look_room_id(split_look_results[-1]["response"]) == "room-123" +assert "Room: Start (ID: room-" in split_look_chunks[-2] +assert split_look_chunks[-1] == "123)\nShort: A room\n" +try: + smoke_common.telnet_look_room_id(split_look_chunks[-1]) +except smoke_common.ProbeOperationalFailure: + pass +else: + raise AssertionError("split LOOK fixture did not reproduce the last-chunk defect") + class SessionFakeTlsContext: def __init__(self, wrapped_session): self.wrapped_session = wrapped_session diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) { diff --git a/dev-tools/tests/test_hosted_websocket_playable_smoke.py b/dev-tools/tests/test_hosted_websocket_playable_smoke.py new file mode 100644 index 0000000000..10e0107790 --- /dev/null +++ b/dev-tools/tests/test_hosted_websocket_playable_smoke.py @@ -0,0 +1,1127 @@ +import contextlib +import http.server +import importlib.util +import io +import json +import pathlib +import sys +import threading +import time +import unittest +from collections import deque +from unittest.mock import patch + +HELPER = pathlib.Path(__file__).parents[1] / "hosted/shared/hosted-websocket-playable-smoke.py" +SPEC = importlib.util.spec_from_file_location("hosted_websocket_playable_smoke", HELPER) +MODULE = importlib.util.module_from_spec(SPEC) +assert SPEC.loader is not None +sys.modules[SPEC.name] = MODULE +SPEC.loader.exec_module(MODULE) + + +@contextlib.contextmanager +def local_http_server(): + requests = [] + small_json = b'{"ok":true}' + exact_json = small_json + b" " * (MODULE.MAX_HTTP_RESPONSE_BYTES - len(small_json)) + + class Handler(http.server.BaseHTTPRequestHandler): + def _respond(self): + request_body = self.rfile.read(int(self.headers.get("Content-Length", "0"))) + requests.append((self.command, self.path, dict(self.headers.items()), request_body)) + parsed = MODULE.urllib.parse.urlsplit(self.path) + query = MODULE.urllib.parse.parse_qs(parsed.query) + response_headers = {} + response_body = b"ok" + status = 200 + + if parsed.path in {"/auth/bootstrap/worlds", "/auth/connect-token"}: + status = int(query["redirect"][0]) + response_headers["Location"] = f"http://localhost:{self.server.server_port}/redirect-target" + response_body = b"redirect response" + elif parsed.path == "/success-small": + response_body = small_json + elif parsed.path == "/success-exact": + response_body = exact_json + elif parsed.path == "/success-over": + response_body = b"do-not-print-this" + b"x" * MODULE.MAX_HTTP_RESPONSE_BYTES + elif parsed.path == "/error-exact": + status = 401 + response_body = b"e" * MODULE.MAX_HTTP_RESPONSE_BYTES + elif parsed.path == "/error-over": + status = 401 + response_body = b"do-not-print-this" + b"x" * MODULE.MAX_HTTP_RESPONSE_BYTES + + self.send_response(status) + for name, value in response_headers.items(): + self.send_header(name, value) + self.send_header("Content-Length", str(len(response_body))) + self.end_headers() + self.wfile.write(response_body) + + def do_GET(self): + self._respond() + + def do_POST(self): + self._respond() + + def log_message(self, format, *args): + pass + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_port}", requests + finally: + server.shutdown() + thread.join() + server.server_close() + + +class FakeHttp: + def __init__( + self, + *, + cookie="Firemud-Connect-Token=token-1", + cookie_attributes="; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=30", + connect_token_metadata=None, + readiness=None, + characters=None, + character_rosters=None, + ): + self.calls = [] + self.cookie = cookie + self.cookie_attributes = cookie_attributes + self.connect_token_metadata = ( + connect_token_metadata + if connect_token_metadata is not None + else {"issuedAt": "2026-01-01T00:00:00Z", "expiresAt": "2026-01-01T00:00:30Z"} + ) + self.readiness = readiness + self.characters = characters if characters is not None else [{"characterName": "Ada"}] + self.character_rosters = character_rosters + self.character_discovery_count = 0 + self.connect_count = 0 + + def __call__(self, method, url, payload, headers, timeout): + self.calls.append((method, url, payload, dict(headers), timeout)) + if url.endswith("/ready"): + return self.readiness + if url.endswith("/auth/player-bootstrap"): + return MODULE.HttpResponse(200, {}, {"data": {"bootstrapToken": "bootstrap"}}) + if url.endswith("/auth/bootstrap/worlds"): + return MODULE.HttpResponse(200, {}, {"data": [{"worldSlug": "demo"}]}) + if url.endswith("/realms"): + return MODULE.HttpResponse( + 200, + {}, + {"data": [{"realmSlug": "production", "connectScopeId": "scope-1"}]}, + ) + if "/characters?" in url: + self.character_discovery_count += 1 + characters = self.characters + if self.character_rosters is not None: + roster_index = min(self.character_discovery_count - 1, len(self.character_rosters) - 1) + characters = self.character_rosters[roster_index] + return MODULE.HttpResponse(200, {}, {"data": characters}) + if url.endswith("/auth/connect-token"): + self.connect_count += 1 + cookie = self.cookie + if self.connect_count > 1 and cookie == "Firemud-Connect-Token=token-1": + cookie = f"Firemud-Connect-Token=token-{self.connect_count}" + return MODULE.HttpResponse( + 200, + {"Set-Cookie": cookie + self.cookie_attributes}, + {"data": self.connect_token_metadata}, + ) + if url.endswith("/revoke"): + return MODULE.HttpResponse(200, {}, {"status": "success", "data": {}}) + raise AssertionError(f"unexpected fake HTTP request: {method} {url}") + + +DEFAULT_LOOK_PAYLOAD = object() + + +class FakeWebSocket: + def __init__(self, *, look_payload=DEFAULT_LOOK_PAYLOAD, accepted_value=True): + self.commands = [] + self.responses = deque() + self.closed = False + self.close_observed = False + self.accepted_value = accepted_value + self.look_payload = ( + { + "roomId": "R-1021", + "roomName": "Candle-lit Antechamber", + } + if look_payload is DEFAULT_LOOK_PAYLOAD + else look_payload + ) + + def settimeout(self, timeout): + self.timeout = timeout + + def send(self, command): + self.commands.append(command) + command_type = command.split(" ", 1)[0] + response = { + "eventType": "command_result", + "commandType": command_type, + "accepted": self.accepted_value, + } + if command_type == "LOOK" and self.look_payload is not None: + response["outputs"] = [{"payloadType": "look_view", "payload": self.look_payload}] + self.responses.append(json.dumps(response)) + + def recv(self): + if self.responses: + return self.responses.popleft() + raise RuntimeError("fake server closed") + + def recv_data(self, *, control_frame=False): + if not control_frame: + raise AssertionError("close observation must request control frames") + if self.commands and self.commands[-1] == "LOGOUT": + self.close_observed = True + self.closed = True + return MODULE.WEBSOCKET_CLOSE_OPCODE, b"\x03\xe8" + raise RuntimeError("fake server did not close") + + def close(self): + self.closed = True + + +class FakeWireSocket: + def __init__(self, wire=b"", *, chunk_size=None, trickle_seconds=0): + self.wire = bytearray(wire) + self.chunk_size = chunk_size + self.trickle_seconds = trickle_seconds + self.timeout = None + self.bytes_read = 0 + self.sent = [] + self._closed = False + self.shutdown_called = False + + def settimeout(self, timeout): + self.timeout = timeout + + def gettimeout(self): + return self.timeout + + def recv(self, requested): + if self.trickle_seconds: + if self.timeout is not None and self.timeout <= self.trickle_seconds: + time.sleep(max(0, self.timeout)) + raise TimeoutError("fake socket timeout") + time.sleep(self.trickle_seconds) + if not self.wire: + if self.timeout is not None: + time.sleep(max(0, self.timeout)) + raise TimeoutError("fake socket timeout") + count = min(requested, len(self.wire)) + if self.chunk_size is not None: + count = min(count, self.chunk_size) + data = bytes(self.wire[:count]) + del self.wire[:count] + self.bytes_read += count + return data + + def send(self, payload): + self.sent.append(bytes(payload)) + return len(payload) + + def shutdown(self, *_args): + self.shutdown_called = True + + def close(self): + self._closed = True + + +def websocket_frame(opcode, payload=b"", *, final=True): + first = (0x80 if final else 0) | opcode + payload = bytes(payload) + length = len(payload) + if length < 126: + header = bytes((first, length)) + elif length < 65_536: + header = bytes((first, 126)) + length.to_bytes(2, "big") + else: + header = bytes((first, 127)) + length.to_bytes(8, "big") + return header + payload + + +class LogoutUnavailableWebSocket(FakeWebSocket): + def send(self, command): + if command == "LOGOUT": + self.commands.append(command) + self.responses.append( + json.dumps( + { + "eventType": "command_result", + "commandType": "LOGOUT", + "accepted": False, + "errorCode": "LOGOUT_UNAVAILABLE", + } + ) + ) + return + super().send(command) + + +class FakeHandshakeRejected(Exception): + def __init__(self, status_code=403, error_class="CONNECT_TOKEN_REPLAYED"): + super().__init__("replay response contains a token that must not be logged") + self.status_code = status_code + self.resp_headers = {"X-Firemud-Handshake-Error-Class": error_class} + + +class HostedWebSocketPlayableSmokeTests(unittest.TestCase): + def config(self, **overrides): + values = { + "auth_api_base": "https://preview.example", + "websocket_url": "wss://preview.example/ws/game", + "origin": "https://frontend.preview.example", + "username": "operator@example.com", + "password": "do-not-print-this", + } + values.update(overrides) + return MODULE.SmokeConfig(**values) + + def make_bounded_wire_client(self, wire=b"", **socket_options): + import websocket + + client_type = MODULE._bounded_websocket_client(websocket) + client = client_type() + fake_socket = FakeWireSocket(wire, **socket_options) + client.sock = fake_socket + client.connected = True + client.settimeout(1.0) + return client, fake_socket + + def test_bounded_wire_client_rejects_advertised_frame_before_payload_read(self): + client, fake_socket = self.make_bounded_wire_client(b"\x81\x05hello") + with ( + patch.object(MODULE, "MAX_WEBSOCKET_FRAME_BYTES", 4), + self.assertRaises(MODULE._WebSocketReceiveLimitExceeded), + ): + client.recv() + self.assertEqual(fake_socket.bytes_read, 2) + self.assertEqual(bytes(fake_socket.wire), b"hello") + client.close() + self.assertEqual(fake_socket.bytes_read, 2) + self.assertTrue(fake_socket._closed) + + def test_bounded_wire_client_rejects_oversized_control_frame_before_payload_read(self): + client, fake_socket = self.make_bounded_wire_client(b"\x89\x7e\x00\x7e" + b"x" * 126) + with self.assertRaises(MODULE._WebSocketReceiveLimitExceeded): + client.recv_data(control_frame=True) + self.assertEqual(fake_socket.bytes_read, 4) + self.assertEqual(len(fake_socket.wire), 126) + client.close() + self.assertEqual(fake_socket.bytes_read, 4) + self.assertTrue(fake_socket._closed) + + def test_bounded_wire_client_limits_fragmented_message_before_concatenation(self): + wire = websocket_frame(0x1, b"12345678", final=False) + websocket_frame(0x0, b"abc", final=True) + client, _ = self.make_bounded_wire_client(wire) + with ( + patch.object(MODULE, "MAX_WEBSOCKET_MESSAGE_BYTES", 10), + self.assertRaises(MODULE._WebSocketReceiveLimitExceeded), + ): + client.recv() + + def test_bounded_wire_client_limits_frames_consumed_while_handling_control_frames(self): + wire = b"".join(websocket_frame(0x9) for _ in range(3)) + websocket_frame(0x1, b"{}") + client, fake_socket = self.make_bounded_wire_client(wire) + with ( + patch.object(MODULE, "MAX_WEBSOCKET_RECEIVE_FRAMES", 2), + self.assertRaises(MODULE._WebSocketReceiveLimitExceeded), + ): + client.recv() + self.assertEqual(fake_socket.bytes_read, 6) + + def test_command_wait_limits_unmatched_message_flood(self): + payload = json.dumps({"eventType": "unrelated"}).encode() + wire = websocket_frame(0x1, payload) * 3 + client, fake_socket = self.make_bounded_wire_client(wire) + with ( + patch.object(MODULE, "MAX_WEBSOCKET_WAIT_MESSAGES", 2), + self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "receive budget exceeded"), + ): + MODULE._await_command_result(client, "LOGIN", self.config()) + expected = websocket_frame(0x1, payload) * 2 + self.assertEqual(fake_socket.bytes_read, len(expected)) + + def test_command_wait_limits_aggregate_unmatched_bytes(self): + payload = b"not-json!" + wire = websocket_frame(0x1, payload) * 3 + client, fake_socket = self.make_bounded_wire_client(wire) + with ( + patch.object(MODULE, "MAX_WEBSOCKET_WAIT_BYTES", len(payload) + 1), + self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "receive budget exceeded"), + ): + MODULE._await_command_result(client, "LOGIN", self.config()) + expected = websocket_frame(0x1, payload) * 2 + self.assertEqual(fake_socket.bytes_read, len(expected)) + + def test_close_wait_limits_unrelated_control_frame_flood(self): + wire = b"".join(websocket_frame(0x9, b"p") for _ in range(3)) + client, fake_socket = self.make_bounded_wire_client(wire) + with ( + patch.object(MODULE, "MAX_WEBSOCKET_WAIT_MESSAGES", 2), + self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "receive budget exceeded"), + ): + MODULE._await_websocket_close(client, self.config()) + expected = b"".join(websocket_frame(0x9, b"p") for _ in range(2)) + self.assertEqual(fake_socket.bytes_read, len(expected)) + self.assertEqual(len(fake_socket.sent), 2) + + def test_receive_deadline_is_refreshed_against_trickled_wire_bytes(self): + client, fake_socket = self.make_bounded_wire_client( + websocket_frame(0x1, b"{}"), chunk_size=1, trickle_seconds=0.02 + ) + deadline = time.monotonic() + 0.05 + client.set_receive_deadline(deadline) + started = time.monotonic() + with self.assertRaises(Exception) as caught: + client.recv() + self.assertIn( + type(caught.exception).__name__, + {"TimeoutError", "WebSocketTimeoutException"}, + ) + self.assertLess(time.monotonic() - started, 0.2) + self.assertLess(fake_socket.bytes_read, len(websocket_frame(0x1, b"{}"))) + + def test_bounded_close_observes_close_opcode_and_timeout(self): + close_frame = websocket_frame(0x8, b"\x03\xe8") + client, fake_socket = self.make_bounded_wire_client(close_frame) + MODULE._await_websocket_close(client, self.config(timeout_seconds=1)) + self.assertFalse(client.connected) + self.assertTrue(any(frame[0] & 0x0F == 0x8 for frame in fake_socket.sent)) + client.close() + self.assertTrue(fake_socket._closed) + + timed_out_client, _ = self.make_bounded_wire_client() + with self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "close observation failed"): + MODULE._await_websocket_close( + timed_out_client, + self.config(timeout_seconds=0.02), + ) + + def test_websocket_cleanup_close_has_an_absolute_deadline(self): + client, fake_socket = self.make_bounded_wire_client( + websocket_frame(0x1, b"x") * 10, + chunk_size=1, + trickle_seconds=0.02, + ) + with patch.object(MODULE, "MAX_WEBSOCKET_CLOSE_SECONDS", 0.05): + started = time.monotonic() + client.close(timeout=None) + self.assertLess(time.monotonic() - started, 0.2) + self.assertTrue(fake_socket._closed) + + def test_default_http_transport_rejects_cross_origin_redirects_for_get_and_post(self): + with local_http_server() as (base_url, requests): + for status in (301, 302, 303): + get_response = MODULE._default_http_request( + "GET", + f"{base_url}/auth/bootstrap/worlds?redirect={status}", + None, + {"Authorization": "Bearer bootstrap-secret"}, + 2.0, + ) + self.assertEqual(get_response.status, status) + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + f"returned HTTP {status}", + ): + MODULE._require_success(get_response, "bootstrap worlds", self.config()) + + post_response = MODULE._default_http_request( + "POST", + f"{base_url}/auth/connect-token?redirect={status}", + {"connectScopeId": "scope-1", "requestId": "request-1"}, + { + "Authorization": "Bearer bootstrap-secret", + "Content-Type": "application/json", + }, + 2.0, + ) + self.assertEqual(post_response.status, status) + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + f"returned HTTP {status}", + ): + MODULE._require_success(post_response, "connect-token issuance", self.config()) + + self.assertEqual(len(requests), 6) + self.assertTrue(all("redirect-target" not in request[1] for request in requests)) + get_requests = [request for request in requests if request[0] == "GET"] + post_requests = [request for request in requests if request[0] == "POST"] + self.assertEqual(len(get_requests), 3) + self.assertEqual(len(post_requests), 3) + self.assertTrue(all(request[2].get("Authorization") == "Bearer bootstrap-secret" for request in requests)) + self.assertTrue( + all( + json.loads(request[3]) == {"connectScopeId": "scope-1", "requestId": "request-1"} + for request in post_requests + ) + ) + + def test_default_http_redirect_handler_rejects_https_downgrade_without_post_conversion(self): + handler = MODULE._RejectRedirectHandler() + for status in (301, 302, 303): + with self.subTest(status=status): + request = MODULE.urllib.request.Request( + "https://preview.example/api/account/auth/connect-token", + data=b'{"connectScopeId":"scope-1"}', + method="POST", + headers={"Authorization": "Bearer bootstrap-secret"}, + ) + redirected = handler.redirect_request( + request, + None, + status, + "Found", + {}, + "http://attacker.example/connect-token", + ) + self.assertIsNone(redirected) + self.assertEqual(request.full_url, "https://preview.example/api/account/auth/connect-token") + self.assertEqual(request.get_method(), "POST") + self.assertEqual(request.data, b'{"connectScopeId":"scope-1"}') + + def test_default_http_transport_accepts_in_limit_and_exact_limit_success_bodies(self): + with local_http_server() as (base_url, _): + for path in ("/success-small", "/success-exact"): + with self.subTest(path=path): + response = MODULE._default_http_request("GET", base_url + path, None, {}, 2.0) + self.assertEqual(MODULE._require_success(response, "local probe", self.config()), {"ok": True}) + if path == "/success-exact": + self.assertEqual(len(response.body), MODULE.MAX_HTTP_RESPONSE_BYTES) + + def test_default_http_transport_bounds_oversized_success_and_http_error_bodies(self): + secret = "do-not-print-this" + with local_http_server() as (base_url, _): + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + rf"HTTP 200.*{MODULE.MAX_HTTP_RESPONSE_BYTES} bytes", + ) as caught: + MODULE._default_http_request( + "GET", + base_url + "/success-over?token=" + secret, + None, + {"Authorization": "Bearer bootstrap-secret"}, + 2.0, + ) + self.assertNotIn(secret, str(caught.exception)) + self.assertNotIn("bootstrap-secret", str(caught.exception)) + + error_response = MODULE._default_http_request("GET", base_url + "/error-over", None, {}, 2.0) + self.assertEqual(error_response.status, 401) + self.assertEqual(len(error_response.body), MODULE.MAX_HTTP_RESPONSE_BYTES) + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "returned HTTP 401", + ) as caught: + MODULE._require_success(error_response, "local probe", self.config()) + self.assertNotIn(secret, str(caught.exception)) + + exact_error_response = MODULE._default_http_request("GET", base_url + "/error-exact", None, {}, 2.0) + self.assertEqual(exact_error_response.status, 401) + self.assertEqual(len(exact_error_response.body), MODULE.MAX_HTTP_RESPONSE_BYTES) + + def test_default_http_transport_closes_http_error_responses(self): + url = "https://preview.example/auth/connect-token" + response_body = io.BytesIO(b"error response") + error = MODULE.urllib.error.HTTPError(url, 401, "Unauthorized", {}, response_body) + + class ErrorOpener: + def open(self, request, timeout): + raise error + + with patch.object(MODULE.urllib.request, "build_opener", return_value=ErrorOpener()): + response = MODULE._default_http_request("POST", url, {}, {}, 2.0) + + self.assertEqual(response.status, 401) + self.assertTrue(response_body.closed) + + def test_default_first_party_cookie_bootstrap_runs_read_only_baseline(self): + http = FakeHttp() + sockets = [] + + def socket_factory(url, timeout, headers): + sockets.append((url, timeout, list(headers))) + ws = LogoutUnavailableWebSocket() + sockets.append(ws) + return ws + + result = MODULE.run_smoke(self.config(), http_request=http, websocket_factory=socket_factory) + + self.assertEqual(result["steps"], ["LOGIN", "PLAY", "LOOK"]) + self.assertFalse(result["logout"]) + self.assertEqual(result["lookRoomId"], "R-1021") + self.assertEqual(result["lookRoomName"], "Candle-lit Antechamber") + self.assertNotIn("outputs", result) + ws = sockets[1] + self.assertEqual(ws.commands, ["LOGIN", "PLAY demo production Ada", "LOOK"]) + self.assertFalse(ws.close_observed) + self.assertEqual( + sockets[0][2], + [ + "Cookie: Firemud-Connect-Token=token-1", + "Origin: https://frontend.preview.example", + ], + ) + self.assertEqual( + http.calls[0][2], + { + "accountIdentifier": "operator@example.com", + "secret": "do-not-print-this", + }, + ) + + def test_ambiguous_character_discovery_fails_before_connect_token(self): + http = FakeHttp(characters=[{"characterName": "Ada"}, {"characterName": "Bea"}]) + + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "multiple characters.*explicit character", + ): + MODULE.run_smoke( + self.config(), + http_request=http, + websocket_factory=FakeWebSocket, + ) + + self.assertEqual(http.connect_count, 0) + + def test_empty_or_malformed_character_discovery_fails_before_token_or_socket(self): + malformed_name = "Ada\nPLAY private realm" + for roster in ( + [], + [{}], + [{"characterName": None}], + [{"characterName": ""}], + [{"characterName": " "}], + [{"characterName": 7}], + [{"characterName": malformed_name}], + [None], + ): + with self.subTest(roster=roster): + http = FakeHttp(characters=roster) + socket_attempts = [] + + with self.assertRaises(MODULE.HostedWebSocketPlayableSmokeError) as caught: + MODULE.run_smoke( + self.config(), + http_request=http, + websocket_factory=lambda *args, attempts=socket_attempts: attempts.append(args), + ) + + self.assertNotIn(malformed_name, str(caught.exception)) + self.assertNotIn(self.config().password, str(caught.exception)) + self.assertEqual(http.connect_count, 0) + self.assertEqual(socket_attempts, []) + + def test_explicit_character_must_be_valid_and_visible_before_token_issuance(self): + for configured_character, roster in ( + ("Ada", [{"characterName": "Bea"}]), + (" ", [{"characterName": "Ada"}]), + ("Ada\nPLAY private realm", [{"characterName": "Ada\nPLAY private realm"}]), + ): + with self.subTest(configured_character=configured_character): + http = FakeHttp(characters=roster) + socket_attempts = [] + + with self.assertRaises(MODULE.HostedWebSocketPlayableSmokeError): + MODULE.run_smoke( + self.config(character=configured_character), + http_request=http, + websocket_factory=lambda *args, attempts=socket_attempts: attempts.append(args), + ) + + self.assertEqual(http.connect_count, 0) + self.assertEqual(socket_attempts, []) + + def test_reconnect_revalidates_character_before_issuing_fresh_token_or_socket(self): + http = FakeHttp( + character_rosters=[ + [{"characterName": "Ada"}], + [{"characterName": " "}], + ] + ) + socket_attempts = [] + sockets = [] + + def socket_factory(url, timeout, headers): + socket_attempts.append(list(headers)) + if len(socket_attempts) == 2: + self.assertTrue(sockets[0].closed) + raise FakeHandshakeRejected() + sockets.append(LogoutUnavailableWebSocket()) + return sockets[-1] + + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "malformed name", + ): + MODULE.run_smoke( + self.config(exercise_reconnect=True), + http_request=http, + websocket_factory=socket_factory, + ) + + self.assertEqual(http.character_discovery_count, 2) + self.assertEqual(http.connect_count, 1) + self.assertEqual(len(sockets), 1) + self.assertEqual(len(socket_attempts), 2) + + def test_default_reconnect_uses_fresh_cookie_and_rejects_replay_without_logout(self): + http = FakeHttp() + attempts = [] + sockets = [] + + def socket_factory(url, timeout, headers): + attempts.append(list(headers)) + if len(attempts) == 2: + self.assertTrue(sockets[0].closed) + raise FakeHandshakeRejected() + sockets.append(LogoutUnavailableWebSocket()) + return sockets[-1] + + result = MODULE.run_smoke( + self.config(exercise_reconnect=True), + http_request=http, + websocket_factory=socket_factory, + ) + + self.assertEqual(result["sessions"], 2) + self.assertFalse(result["logout"]) + self.assertTrue(result["replayRejected"]) + self.assertEqual( + attempts, + [ + [ + "Cookie: Firemud-Connect-Token=token-1", + "Origin: https://frontend.preview.example", + ], + [ + "Cookie: Firemud-Connect-Token=token-1", + "Origin: https://frontend.preview.example", + ], + [ + "Cookie: Firemud-Connect-Token=token-2", + "Origin: https://frontend.preview.example", + ], + ], + ) + self.assertEqual( + sockets[0].commands, + ["LOGIN", "PLAY demo production Ada", "LOOK"], + ) + self.assertEqual( + sockets[1].commands, + ["LOGIN", "PLAY demo production Ada", "LOOK"], + ) + self.assertTrue(result["replayRejected"]) + + def test_cli_defaults_to_read_only_and_logout_flag_opts_in(self): + result = { + "transport": "first-party-wss", + "classification": "diagnostic-operator-smoke", + "steps": ["LOGIN", "PLAY", "LOOK"], + "sessions": 1, + "logout": False, + "reconnect": False, + "replayRejected": False, + "lookRoomId": "R-1021", + "lookRoomName": "Candle-lit Antechamber", + } + for extra_args, expected_logout in (([], False), (["--logout"], True)): + with self.subTest(extra_args=extra_args): + output = io.StringIO() + with ( + patch.object(MODULE, "run_smoke", return_value=result) as run_smoke, + contextlib.redirect_stdout(output), + ): + self.assertEqual( + MODULE.main(["--origin", "https://frontend.preview.example", *extra_args]), + 0, + ) + self.assertEqual(run_smoke.call_args.args[0].exercise_logout, expected_logout) + + def test_trusted_cli_pins_destinations_over_ambient_configuration(self): + http = FakeHttp() + socket_attempts = [] + + def socket_factory(url, timeout, headers): + socket_attempts.append((url, list(headers))) + if len(socket_attempts) == 2: + raise FakeHandshakeRejected() + return FakeWebSocket() + + actual_run_smoke = MODULE.run_smoke + observed_configs = [] + + def run_with_fakes(config): + observed_configs.append(config) + return actual_run_smoke( + config, + http_request=http, + websocket_factory=socket_factory, + ) + + hostile_environment = { + "PLAYER_EXPERIENCE_AUTH_API_BASE": "https://attacker.invalid", + "PLAYER_EXPERIENCE_AUTH_API_PREFIX": "/attacker-account", + "SMOKE_GATEWAY_READINESS_URL": "https://attacker.invalid/ready", + "SMOKE_GATEWAY_CONNECT_TOKEN_REVOKE_URL": "https://attacker.invalid/revoke", + } + output = io.StringIO() + with ( + patch.dict(MODULE.os.environ, hostile_environment), + patch.object(MODULE, "run_smoke", side_effect=run_with_fakes), + contextlib.redirect_stdout(output), + ): + self.assertEqual( + MODULE.main( + [ + "--gateway-base", + "https://preview.example", + "--auth-base", + "https://preview.example", + "--auth-prefix", + "/api/account", + "--websocket-url", + "wss://preview.example/ws/game", + "--origin", + "https://preview.example", + "--readiness-url", + "", + "--revoke-url", + "", + "--username", + "operator@example.com", + "--password", + "do-not-print-this", + "--world", + "demo", + "--realm", + "production", + "--expected-room-id", + "R-1021", + "--reconnect", + ] + ), + 0, + ) + + self.assertEqual(len(observed_configs), 1) + config = observed_configs[0] + self.assertEqual(config.auth_api_base, "https://preview.example") + self.assertEqual(config.auth_api_prefix, "/api/account") + self.assertEqual(config.readiness_url, "") + self.assertEqual(config.revoke_url, "") + self.assertEqual(config.websocket_url, "wss://preview.example/ws/game") + self.assertEqual(config.origin, "https://preview.example") + self.assertTrue(config.exercise_reconnect) + self.assertEqual(len(socket_attempts), 3) + self.assertTrue(all(url == "wss://preview.example/ws/game" for url, _ in socket_attempts)) + self.assertTrue( + all( + any(header.startswith("Cookie: Firemud-Connect-Token=") for header in headers) + for _, headers in socket_attempts + ) + ) + self.assertTrue(all(url.startswith("https://preview.example/") for _, url, _, _, _ in http.calls)) + credential_calls = [call for call in http.calls if "secret" in (call[2] or {}) or "Authorization" in call[3]] + self.assertTrue(credential_calls) + self.assertTrue(all(call[1].startswith("https://preview.example/") for call in credential_calls)) + self.assertFalse(any(url.endswith(("/ready", "/revoke")) for _, url, _, _, _ in http.calls)) + self.assertNotIn("do-not-print-this", output.getvalue()) + + def test_explicit_logout_opt_in_fails_when_logout_is_unavailable(self): + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "LOGOUT was rejected", + ): + MODULE.run_smoke( + self.config(exercise_logout=True), + http_request=FakeHttp(), + websocket_factory=lambda url, timeout, headers: LogoutUnavailableWebSocket(), + ) + + def test_truthy_non_boolean_command_acceptance_is_rejected(self): + for accepted_value in ("false", 1, ["yes"], {"accepted": False}): + with ( + self.subTest(accepted_value=accepted_value), + self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "LOGIN was rejected", + ), + ): + MODULE.run_smoke( + self.config(), + http_request=FakeHttp(), + websocket_factory=lambda url, timeout, headers, value=accepted_value: FakeWebSocket( + accepted_value=value + ), + ) + + def test_boolean_true_command_acceptance_is_success(self): + client = FakeWebSocket() + client.send("LOGIN") + parsed = MODULE._await_command_result(client, "LOGIN", self.config()) + self.assertIs(parsed["accepted"], True) + + def test_explicit_logout_opt_in_requires_and_observes_close_frame(self): + http = FakeHttp() + sockets = [] + + def socket_factory(url, timeout, headers): + socket = FakeWebSocket() + sockets.append(socket) + return socket + + result = MODULE.run_smoke( + self.config(exercise_logout=True), + http_request=http, + websocket_factory=socket_factory, + ) + + self.assertTrue(result["logout"]) + self.assertEqual( + sockets[0].commands, + ["LOGIN", "PLAY demo production Ada", "LOOK", "LOGOUT"], + ) + self.assertTrue(sockets[0].close_observed) + + def test_reconnect_replay_check_fails_closed_for_non_replay_handshakes(self): + for failure in ( + FakeHandshakeRejected(status_code=500), + FakeHandshakeRejected(error_class="CONNECT_TOKEN_MISSING"), + OSError("network failure"), + ): + with self.subTest(failure=type(failure).__name__): + http = FakeHttp() + accepted = [] + + def socket_factory(url, timeout, headers, *, accepted=accepted, failure=failure): + if not accepted: + socket = FakeWebSocket() + accepted.append(socket) + return socket + raise failure + + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "CONNECT_TOKEN_REPLAYED", + ): + MODULE.run_smoke( + self.config(exercise_reconnect=True), + http_request=http, + websocket_factory=socket_factory, + ) + + def test_reconnect_replay_check_rejects_an_accepted_upgrade(self): + http = FakeHttp() + sockets = [] + + def socket_factory(url, timeout, headers): + socket = FakeWebSocket() + sockets.append(socket) + return socket + + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "replayed connect-token handshake was accepted", + ): + MODULE.run_smoke( + self.config(exercise_reconnect=True), + http_request=http, + websocket_factory=socket_factory, + ) + self.assertTrue(sockets[1].closed) + + def test_look_without_authoritative_view_fails_closed(self): + http = FakeHttp() + + def socket_factory(url, timeout, headers): + return FakeWebSocket(look_payload=None) + + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "authoritative LOOK view", + ): + MODULE.run_smoke( + self.config(), + http_request=http, + websocket_factory=socket_factory, + ) + + def test_look_room_id_must_match_optional_telnet_parity_id(self): + http = FakeHttp() + + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "expected Telnet parity room ID", + ): + MODULE.run_smoke( + self.config(expected_room_id="R-other"), + http_request=http, + websocket_factory=lambda url, timeout, headers: FakeWebSocket(), + ) + + def test_missing_or_malformed_origin_fails_closed(self): + for origin in ( + "", + "frontend.preview.example", + "https://frontend.preview.example/path", + ): + http = FakeHttp() + with ( + self.subTest(origin=origin), + self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "first-party Origin"), + ): + MODULE.run_smoke( + self.config(origin=origin), + http_request=http, + websocket_factory=FakeWebSocket, + ) + self.assertEqual(http.calls, []) + + def test_wrong_allowlisted_origin_is_not_treated_as_a_pass(self): + http = FakeHttp() + + def gateway_requiring_expected_origin(url, timeout, headers): + if "Origin: https://frontend.preview.example" not in headers: + raise RuntimeError("origin rejected by gateway allowlist") + return FakeWebSocket() + + with self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "WSS connection failed"): + MODULE.run_smoke( + self.config(origin="https://wrong.preview.example"), + http_request=http, + websocket_factory=gateway_requiring_expected_origin, + ) + + def test_missing_cookie_fails_closed(self): + http = FakeHttp(cookie="") + with self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "valid Firemud-Connect-Token"): + MODULE.run_smoke(self.config(), http_request=http, websocket_factory=FakeWebSocket) + + def test_wrong_cookie_fails_closed(self): + http = FakeHttp(cookie="Other=wrong") + with self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "valid Firemud-Connect-Token"): + MODULE.run_smoke(self.config(), http_request=http, websocket_factory=FakeWebSocket) + + def test_connect_token_cookie_requires_full_protection_before_wss(self): + invalid_responses = ( + ("; Secure; SameSite=Strict; Path=/ws/game; Max-Age=30", None), + ("; HttpOnly; SameSite=Strict; Path=/ws/game; Max-Age=30", None), + ("; HttpOnly=false; Secure; SameSite=Strict; Path=/ws/game; Max-Age=30", None), + ("; HttpOnly; Secure=false; SameSite=Strict; Path=/ws/game; Max-Age=30", None), + ("; HttpOnly; Secure; SameSite=Lax; Path=/ws/game; Max-Age=30", None), + ("; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=30", None), + ("; HttpOnly; Secure; SameSite=Strict; Path=/ws/game", None), + ("; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=0", None), + ("; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=030", None), + ("; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=thirty", None), + ( + "; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=31", + {"issuedAt": "2026-01-01T00:00:00Z", "expiresAt": "2026-01-01T00:00:30Z"}, + ), + ( + "; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=30", + {"issuedAt": "bad", "expiresAt": "2026-01-01T00:00:30Z"}, + ), + ( + "; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=30", + {"issuedAt": "2026-01-01T00:00:30Z", "expiresAt": "2026-01-01T00:00:00Z"}, + ), + ( + "; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=30", + {"issuedAt": "2026-01-01T00:00:00Z"}, + ), + ("; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=30", {}), + ) + for attributes, metadata in invalid_responses: + http = FakeHttp(cookie_attributes=attributes, connect_token_metadata=metadata) + socket_attempts = [] + with ( + self.subTest(attributes=attributes, metadata=metadata), + self.assertRaises(MODULE.HostedWebSocketPlayableSmokeError), + ): + MODULE.run_smoke( + self.config(), + http_request=http, + websocket_factory=lambda *args, attempts=socket_attempts: attempts.append(args), + ) + self.assertEqual(socket_attempts, []) + + def test_connect_token_cookie_accepts_full_protection_and_token_ttl(self): + http = FakeHttp() + socket_attempts = [] + MODULE.run_smoke( + self.config(), + http_request=http, + websocket_factory=lambda *args: socket_attempts.append(args) or FakeWebSocket(), + ) + self.assertEqual(len(socket_attempts), 1) + + def test_readiness_rejects_non_2xx_and_malformed_payload(self): + for readiness in ( + MODULE.HttpResponse(503, {}, {"status": "DOWN"}), + MODULE.HttpResponse(200, {}, {"ready": True}), + ): + http = FakeHttp(readiness=readiness) + with self.subTest(readiness=readiness), self.assertRaises(MODULE.HostedWebSocketPlayableSmokeError): + MODULE.run_smoke( + self.config(readiness_url="https://preview.example/ready"), + http_request=http, + websocket_factory=FakeWebSocket, + ) + self.assertEqual(len(http.calls), 1) + + def test_failure_does_not_echo_credentials(self): + secret = "do-not-print-this" + + def failing_http(method, url, payload, headers, timeout): + return MODULE.HttpResponse(401, {}, {"error": secret, "request": payload}) + + with self.assertRaises(MODULE.HostedWebSocketPlayableSmokeError) as caught: + MODULE.run_smoke( + self.config(password=secret), + http_request=failing_http, + websocket_factory=FakeWebSocket, + ) + self.assertNotIn(secret, str(caught.exception)) + + def test_logout_silent_open_does_not_count_as_a_close(self): + http = FakeHttp() + sockets = [] + + class SilentOpenWebSocket(FakeWebSocket): + def recv_data(self, *, control_frame=False): + self.assert_control_frame = control_frame + raise TimeoutError("socket remains open") + + def socket_factory(url, timeout, headers): + socket = SilentOpenWebSocket() + sockets.append(socket) + return socket + + with self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "close observation"): + MODULE.run_smoke( + self.config(exercise_logout=True), + http_request=http, + websocket_factory=socket_factory, + ) + self.assertFalse(sockets[0].close_observed) + self.assertTrue(sockets[0].assert_control_frame) + + +if __name__ == "__main__": + unittest.main() diff --git a/dev-tools/tests/test_write_playable_proof.py b/dev-tools/tests/test_write_playable_proof.py new file mode 100644 index 0000000000..a89cfaef5e --- /dev/null +++ b/dev-tools/tests/test_write_playable_proof.py @@ -0,0 +1,204 @@ +from __future__ import annotations + +import importlib.util +import unittest +from pathlib import Path + +SCRIPT = ( + Path(__file__).resolve().parents[1] + / "hosted/preview/write-playable-proof.py" +) +SPEC = importlib.util.spec_from_file_location("write_playable_proof", SCRIPT) +assert SPEC is not None and SPEC.loader is not None +proof = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(proof) + + +BASE_SHA = "1" * 40 +HEAD_SHA = "2" * 40 +MERGE_SHA = "3" * 40 +IMAGE_TAG = "pr-merge-" + MERGE_SHA +IMAGE_DIGEST = "a" * 64 + + +def make_namespace(*, uid: str = "runtime-uid", head: str = HEAD_SHA, image_tag: str = IMAGE_TAG): + return { + "apiVersion": "v1", + "kind": "Namespace", + "metadata": { + "name": "pr-42", + "uid": uid, + "labels": { + proof.EXPOSURE_LABEL: "public", + proof.PREVIEW_LABEL: "true", + proof.PR_NUMBER_LABEL: "42", + }, + "annotations": { + proof.REQUESTED_HEAD_ANNOTATION: head, + proof.DEPLOYED_HEAD_ANNOTATION: head, + proof.REQUESTED_BASE_ANNOTATION: BASE_SHA, + proof.DEPLOYED_BASE_ANNOTATION: BASE_SHA, + proof.REQUESTED_MERGE_ANNOTATION: MERGE_SHA, + proof.DEPLOYED_MERGE_ANNOTATION: MERGE_SHA, + proof.REQUESTED_IMAGE_ANNOTATION: image_tag, + proof.EXPECTED_IMAGE_ANNOTATION: image_tag, + proof.TELNET_PORT_ANNOTATION: "32000", + }, + }, + } + + +def make_identity(*, namespace_uid: str = "runtime-uid", head: str = HEAD_SHA): + return { + "apiVersion": "platform.firemud.dev/v1alpha1", + "kind": "HostedEnvironmentIdentity", + "metadata": {"name": "pr-42", "generation": 4}, + "status": { + "phase": "Ready", + "observedGeneration": 4, + "conditions": [ + {"type": "Ready", "status": "True", "observedGeneration": 4} + ], + "profile": { + "runtimeNamespaceUid": namespace_uid, + "requestedHeadSha": head, + "deployedHeadSha": head, + "exposureMode": "public", + "telnetPort": 32000, + }, + "ingress": {"revision": "sha256:" + "b" * 64}, + "telnet": {"revision": "sha256:" + "c" * 64}, + "gatewayInternalWs": {"revision": "sha256:" + "d" * 64}, + "tcpProxyBridge": {"revision": "sha256:" + "e" * 64}, + "grpc": {"revision": "sha256:" + "f" * 64}, + }, + } + + +def make_pods(*, image_tag: str = IMAGE_TAG, include_digest: bool = True): + items = [] + for service in proof.SERVICE_IMAGES: + image_id = ( + f"containerd://{proof.APP_IMAGE_PREFIX}{service}@sha256:{IMAGE_DIGEST}" + if include_digest + else f"containerd://{proof.APP_IMAGE_PREFIX}{service}" + ) + items.append( + { + "kind": "Pod", + "metadata": { + "name": f"{service}-abcde", + "namespace": "pr-42", + "labels": {"app": service}, + }, + "spec": { + "containers": [ + { + "name": service, + "image": f"{proof.APP_IMAGE_PREFIX}{service}:{image_tag}", + "env": [{"name": "IGNORED", "value": "never-copy"}], + } + ] + }, + "status": { + "phase": "Running", + "conditions": [{"type": "Ready", "status": "True"}], + "containerStatuses": [ + {"name": service, "ready": True, "imageID": image_id} + ], + }, + } + ) + return {"apiVersion": "v1", "kind": "PodList", "items": items} + + +def build(**overrides): + values = { + "pr_number": "42", + "base_sha": BASE_SHA, + "head_sha": HEAD_SHA, + "merge_sha": MERGE_SHA, + "image_tag": IMAGE_TAG, + "namespace": make_namespace(), + "identity": make_identity(), + "pods": make_pods(), + "telnet_passed": True, + "wss_passed": True, + } + values.update(overrides) + return proof.build_record(**values) + + +class WritePlayableProofTests(unittest.TestCase): + def test_builds_bounded_record_from_ready_public_runtime(self): + record = build() + + self.assertEqual(record["identity"]["headSha"], HEAD_SHA) + self.assertEqual(record["namespace"]["uid"], "runtime-uid") + self.assertEqual(record["namespace"]["exposureMode"], "public") + self.assertEqual( + record["proofType"], "hosted-pr-transport-diagnostic" + ) + self.assertEqual( + record["outcomes"], + { + "publicTelnetDiagnosticPassed": True, + "firstPartyWssDiagnosticPassed": True, + }, + ) + self.assertEqual(len(record["runtimeImages"]), len(proof.SERVICE_IMAGES)) + self.assertTrue(all(image["digest"] == f"sha256:{IMAGE_DIGEST}" for image in record["runtimeImages"])) + self.assertNotIn("never-copy", str(record)) + self.assertNotIn("items", record) + + def test_rejects_stale_head(self): + with self.assertRaisesRegex(ValueError, "requested head SHA is stale"): + build(namespace=make_namespace(head="4" * 40)) + + def test_rejects_missing_namespace_uid(self): + with self.assertRaisesRegex(ValueError, "Namespace UID"): + build(namespace=make_namespace(uid="")) + + def test_rejects_missing_runtime_image_digest(self): + with self.assertRaisesRegex(ValueError, "no identifiable SHA-256 digest"): + build(pods=make_pods(include_digest=False)) + + def test_rejects_wrong_namespace_image_tag(self): + with self.assertRaisesRegex(ValueError, "Namespace requested image tag"): + build(namespace=make_namespace(image_tag="wrong-tag")) + + def test_rejects_missing_or_stale_merge_namespace_evidence(self): + missing = make_namespace() + del missing["metadata"]["annotations"][proof.REQUESTED_MERGE_ANNOTATION] + with self.assertRaisesRegex(ValueError, "requested-preview-merge-sha"): + build(namespace=missing) + stale = make_namespace() + stale["metadata"]["annotations"][proof.DEPLOYED_MERGE_ANNOTATION] = "4" * 40 + with self.assertRaisesRegex(ValueError, "last-preview-merge-sha is stale"): + build(namespace=stale) + + def test_rejects_wrong_runtime_image_tag(self): + with self.assertRaisesRegex(ValueError, "does not match the trusted image tag"): + build(pods=make_pods(image_tag="wrong-tag")) + + def test_rejects_missing_controller_revision(self): + identity = make_identity() + del identity["status"]["tcpProxyBridge"] + with self.assertRaisesRegex(ValueError, "tcpProxyBridge projection"): + build(identity=identity) + + def test_rejects_namespace_without_exact_preview_ownership_labels(self): + namespace = make_namespace() + del namespace["metadata"]["labels"][proof.PR_NUMBER_LABEL] + with self.assertRaisesRegex(ValueError, "PR label"): + build(namespace=namespace) + + def test_rejects_absent_transport_proof(self): + with self.assertRaisesRegex(ValueError, "public Telnet and first-party WSS diagnostic"): + build(telnet_passed=None) + with self.assertRaisesRegex(ValueError, "public Telnet and first-party WSS diagnostic"): + build(wss_passed=None) + + +if __name__ == "__main__": + unittest.main() diff --git a/dev-tools/tests/trust-bootstrap-live-proof-contract.sh b/dev-tools/tests/trust-bootstrap-live-proof-contract.sh index 9861c9d9db..2a3cda500e 100755 --- a/dev-tools/tests/trust-bootstrap-live-proof-contract.sh +++ b/dev-tools/tests/trust-bootstrap-live-proof-contract.sh @@ -4,6 +4,8 @@ set -euo pipefail repo_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)" proof="$repo_root/dev-tools/hosted/trust-bootstrap/prove-issuance-boundary.sh" +verifier="$repo_root/dev-tools/hosted/trust-bootstrap/verify-live-admission-boundary.py" +readme="$repo_root/k8s/trust-bootstrap/README.md" fail() { echo "trust-bootstrap live-proof contract: $1" >&2 @@ -11,8 +13,419 @@ fail() { } [[ -f "$proof" ]] || fail 'proof helper is missing' +[[ -f "$verifier" ]] || fail 'live admission verifier is missing' +[[ -f "$readme" ]] || fail 'trust-bootstrap README is missing' bash -n "$proof" || fail 'proof helper has invalid shell syntax' +python3 - "$readme" <<'PY' +from __future__ import annotations + +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +readme = Path(sys.argv[1]).read_text(encoding="utf-8") +marker = "## Pre-CA handoff evidence (non-secret)" +if marker not in readme: + raise SystemExit("README is missing the canonical pre-CA handoff evidence section") +handoff = readme.split(marker, 1)[1].split("## Recovery copy and rotation", 1)[0] +ordered_markers = [ + "reviewed repository root", + "Python 3 and PyYAML", + "trusted_context=", + 'kubectl config current-context', + 'readonly KUBECTL=(kubectl --context "$trusted_context")', + 'auth whoami -o jsonpath=', + 'grep -Fx system:masters', + 'verify-live-admission-boundary.py', + ' --context "$trusted_context"', + 'admission_policies=(', + 'firemud-trust-bootstrap-certificaterequest', + 'firemud-trust-ca-secret-boundary', + 'firemud-trust-runtime-binding-boundary', + 'failure_policy="', + 'validation_actions="', + 'controller_resource="', + 'controller_mode="', + 'FIREMUD_HOSTED_IDENTITY_ACTIVATION_MODE', + 'rollout status deployment/firemud-hosted-identity-controller --timeout=480s', + "'{.metadata.generation}'", + "'{.status.observedGeneration}'", + 'controller_mode_after_rollout=', + 'controller_pods=', + 'app.kubernetes.io/name=hosted-environment-identity-controller,app.kubernetes.io/component=controller', + 'controllerActivation=', + 'clusterissuer firemud-ca-issuer', + 'secret firemud-grpc-ca', + 'serviceaccount preview-deployer', + 'clusterrolebinding preview-deployer', + 'pre-ca-handoff=pass', +] +positions = [handoff.find(marker) for marker in ordered_markers] +if any(position < 0 for position in positions) or positions != sorted(positions): + raise SystemExit( + "pre-CA handoff evidence is missing its context, identity, Fail/Deny, " + "paused-controller, absence, or pass ordering" + ) + +for forbidden in ( + "kubectl apply", + "kubectl create", + "kubectl delete", + "kubectl patch", + "gh secret set", + "base64", + ".data", + "--from-file", +): + if forbidden in handoff: + raise SystemExit(f"pre-CA evidence must not contain mutating or secret-bearing operation: {forbidden}") + +if re.search(r"-o json(?:\s|['\"]|$)", handoff): + raise SystemExit("pre-CA evidence must not request Secret-bearing JSON output") + +if '--ignore-not-found -o name' not in handoff: + raise SystemExit("pre-CA evidence must use name-only absence readbacks") +if 'if ! resource_names=' not in handoff: + raise SystemExit("pre-CA evidence must fail closed when an absence lookup errors") +if 'pre-CA handoff could not verify resource absence:' not in handoff: + raise SystemExit("pre-CA evidence must report lookup failure separately from resource presence") +if 'if [[ -n "$resource_names" ]]; then' not in handoff: + raise SystemExit("pre-CA evidence must check captured names only after a successful lookup") +if 'if kubectl get $resource --ignore-not-found -o name | grep -q .' in handoff: + raise SystemExit("pre-CA evidence must not treat a failed lookup pipeline as absence") +if 'if "${KUBECTL[@]}" get $resource --ignore-not-found -o name | grep -q .' in handoff: + raise SystemExit("pre-CA evidence must not treat a failed lookup pipeline as absence") +if "all eight" not in readme.split("## Required order", 1)[1].split( + "## Pre-CA handoff evidence", 1 +)[0]: + raise SystemExit("required order must retain the all-eight admission-boundary obligation") + +block_match = re.search(r"```bash\n(.*?)\n```", handoff, re.DOTALL) +if not block_match: + raise SystemExit("pre-CA handoff evidence is missing its executable Bash block") +handoff_script = block_match.group(1) +mock_kubectl = r'''#!/usr/bin/env python3 +import copy +import json +import os +import sys +from pathlib import Path + +import yaml + +raw_args = sys.argv[1:] +case = os.environ["MOCK_CASE"] +admission_case = os.environ["MOCK_ADMISSION_CASE"] +state = Path(os.environ["MOCK_STATE"]) +joined = " ".join(raw_args) + +def output(value=""): + sys.stdout.write(value) + +def canonical_objects(): + cache = Path(os.environ["MOCK_SPEC_CACHE"]) + if cache.exists(): + return json.loads(cache.read_text()) + root = Path(os.environ["MOCK_REPO_ROOT"]) + objects = {} + for manifest in ( + "k8s/trust-bootstrap/issuance-admission.yaml", + "k8s/trust-bootstrap/recovery-admission.yaml", + "k8s/trust-bootstrap/deployment-admission.yaml", + ): + for document in yaml.safe_load_all((root / manifest).read_text()): + key = document["kind"] + "/" + document["metadata"]["name"] + objects[key] = document + cache.write_text(json.dumps(objects)) + return objects + +if raw_args[:2] == ["config", "current-context"]: + output("other-context" if case == "wrong-context" else "trusted-context") + raise SystemExit(0) +if raw_args[:2] != ["--context", "trusted-context"]: + raise SystemExit("kubectl invocation was not pinned to the approved context") +args = raw_args[2:] +joined = " ".join(args) + +if args[:2] == ["auth", "whoami"]: + output("operator" if ".username}" in joined else + ("developer" if case == "non-admin" else "system:masters") + chr(10)) +elif "rollout" in args and "status" in args: + if case == "rollout-failure": + raise SystemExit(1) +elif args[:1] == ["get"] and len(args) > 2 and args[1] in ( + "validatingadmissionpolicy", + "validatingadmissionpolicybinding", +): + resource, name = args[1], args[2] + kind = ( + "ValidatingAdmissionPolicy" + if resource == "validatingadmissionpolicy" + else "ValidatingAdmissionPolicyBinding" + ) + output_index = args.index("-o") + 1 if "-o" in args else -1 + output_format = args[output_index] if output_index >= 0 else "" + if output_format == "json": + log = Path(os.environ["MOCK_JSON_READS"]) + log.write_text(log.read_text() + kind + "/" + name + chr(10) + if log.exists() else kind + "/" + name + chr(10)) + if admission_case == "api-error" and name == "firemud-trust-bootstrap-certificate": + raise SystemExit(1) + if admission_case == "missing-object" and name == "firemud-trust-bootstrap-certificate": + raise SystemExit(1) + if admission_case == "malformed-json" and name == "firemud-trust-bootstrap-certificate": + output("{not-json") + raise SystemExit(0) + document = copy.deepcopy(canonical_objects()[kind + "/" + name]) + spec = document["spec"] + if name == "firemud-trust-bootstrap-certificate": + if admission_case == "missing-validation": + spec["validations"].pop() + elif admission_case == "true-validation": + spec["validations"][0]["expression"] = "true" + elif admission_case == "altered-condition": + spec["matchConditions"][0]["expression"] = "true" + elif admission_case == "unknown-field": + spec["unreviewedField"] = True + if name == "firemud-trust-runtime-namespace-boundary": + if admission_case == "altered-scope": + spec["matchConstraints"]["resourceRules"][0]["scope"] = "Namespaced" + elif admission_case == "widened-policy-scope": + spec["matchConstraints"]["resourceRules"][0]["resources"] = ["*"] + if kind == "ValidatingAdmissionPolicyBinding": + if admission_case == "empty-selectors": + spec["matchResources"] = { + "namespaceSelector": { + "matchLabels": {}, + "matchExpressions": [], + }, + "objectSelector": {"matchExpressions": []}, + } + elif admission_case == "narrowed-binding-selector" and name == "firemud-trust-bootstrap-certificate": + spec["matchResources"] = { + "namespaceSelector": {"matchLabels": {"proof": "selected"}}, + } + elif admission_case == "binding-object-selector" and name == "firemud-trust-bootstrap-certificate": + spec["matchResources"] = { + "objectSelector": {"matchExpressions": [ + {"key": "proof", "operator": "In", "values": ["selected"]} + ]}, + } + elif admission_case == "widened-binding-selector" and name == "firemud-trust-bootstrap-certificate": + spec["matchResources"] = { + "namespaceSelector": {"matchExpressions": [ + {"key": "proof", "operator": "NotIn", "values": ["selected"]} + ]}, + } + elif admission_case == "binding-paramref" and name == "firemud-trust-bootstrap-certificate": + spec["paramRef"] = { + "name": "unapproved-admission-parameters", + "namespace": "firemud-system", + } + elif admission_case == "unknown-selector-field" and name == "firemud-trust-bootstrap-certificate": + spec["matchResources"] = { + "namespaceSelector": {"matchLabels": {}, "futureField": "ignored"}, + } + output(json.dumps(document)) + elif ".spec.failurePolicy}" in joined: + output("Fail") + elif ".spec.policyName}" in joined: + output(name) + elif ".spec.validationActions[*]}" in joined: + output("Deny") +elif "get" in args and "deployment" in args: + if "--ignore-not-found" in args: + output( + "" + if case in ("absent", "absent-active-orphan", "absent-paused-orphan") + else "deployment.apps/firemud-hosted-identity-controller" + ) + elif "ACTIVATION_MODE" in joined: + count = int(state.read_text()) if state.exists() else 0 + state.write_text(str(count + 1)) + output("active" if case == "marker-change" and count > 0 else "paused") + elif ".metadata.generation}" in joined: + output("5") + elif ".status.observedGeneration}" in joined: + output("" if case == "missing-observed" else "4" if case == "stale-observed" else "5") + elif ".spec.replicas}" in joined: + output("0" if case == "zero-desired-replicas" else "1") + elif ".status.replicas}" in joined: + output("0" if case == "zero-status-replicas" else "0" if case == "zero-desired-replicas" else "1") + elif ".status.updatedReplicas}" in joined: + output("0" if case in ("unconverged-replicas", "zero-status-replicas", "zero-desired-replicas") else "1") + elif ".status.readyReplicas}" in joined: + output("0" if case in ("zero-status-replicas", "zero-desired-replicas") else "1") + elif ".status.availableReplicas}" in joined: + output("0" if case in ("zero-status-replicas", "zero-desired-replicas") else "1") +elif "get" in args and "pods" in args: + if case in ("paused-stale-active", "old-active-pods"): + output("controller-old" + chr(9) + "active" + chr(10)) + elif case == "absent-active-orphan": + output("controller-orphan" + chr(9) + "active" + chr(10)) + elif case == "absent-paused-orphan": + output("controller-orphan" + chr(9) + "paused" + chr(10)) + elif case == "missing-pod-mode": + output("controller-missing-mode" + chr(9) + chr(10)) + elif case in ("absent-matching-pods", "absent"): + output("") + else: + output("controller-current" + chr(9) + "paused" + chr(10)) +elif "get" in args: + # The remaining named resource checks are absence-only readbacks. + output("") +else: + raise SystemExit("unexpected mocked kubectl invocation: " + joined) +''' + +controller_cases = { + "wrong-context": False, + "non-admin": False, + "paused-stale-active": False, + "rollout-failure": False, + "stale-observed": False, + "missing-observed": False, + "unconverged-replicas": False, + "zero-desired-replicas": False, + "zero-status-replicas": False, + "old-active-pods": False, + "missing-pod-mode": False, + "absent-matching-pods": False, + "absent": True, + "absent-active-orphan": False, + "absent-paused-orphan": False, + "converged": True, + "marker-change": False, +} +admission_cases = { + "admission-missing-validation": False, + "admission-true-validation": False, + "admission-altered-scope": False, + "admission-altered-condition": False, + "admission-widened-policy-scope": False, + "admission-narrowed-binding-selector": False, + "admission-binding-object-selector": False, + "admission-widened-binding-selector": False, + "admission-binding-paramref": False, + "admission-unknown-field": False, + "admission-unknown-selector-field": False, + "admission-missing-object": False, + "admission-api-error": False, + "admission-malformed-json": False, + "admission-empty-selectors": True, +} +cases = {**controller_cases, **admission_cases} +with tempfile.TemporaryDirectory(prefix="trust-bootstrap-pause-proof-") as temporary: + mock_path = Path(temporary) / "kubectl" + mock_path.write_text(mock_kubectl, encoding="utf-8") + mock_path.chmod(0o755) + for case, expected_success in cases.items(): + environment = os.environ.copy() + environment.update( + PATH=f"{temporary}:{environment['PATH']}", + MOCK_CASE=case, + MOCK_ADMISSION_CASE=case.removeprefix("admission-") + if case.startswith("admission-") + else "canonical", + MOCK_STATE=str(Path(temporary) / f"{case}.state"), + MOCK_JSON_READS=str(Path(temporary) / f"{case}.json-reads"), + MOCK_SPEC_CACHE=str(Path(temporary) / "canonical-admission-specs.json"), + MOCK_REPO_ROOT=str(Path(sys.argv[1]).resolve().parents[2]), + FIREMUD_HOSTED_IDENTITY_TRUSTED_CONTEXT="trusted-context", + ) + result = subprocess.run( + ["bash", "-euo", "pipefail", "-c", handoff_script], + env=environment, + cwd=Path(sys.argv[1]).resolve().parents[2], + text=True, + capture_output=True, + check=False, + ) + if (result.returncode == 0) != expected_success: + raise SystemExit( + f"mocked pre-CA controller case {case!r} returned " + f"{result.returncode}, expected success={expected_success}: " + f"{result.stderr}{result.stdout}" + ) + if expected_success and "pre-ca-handoff=pass" not in result.stdout: + raise SystemExit(f"mocked pre-CA controller case {case!r} did not pass the gate") + if expected_success: + if "admission-specs=pass objects=16 sha256=" not in result.stdout: + raise SystemExit(f"mocked pre-CA case {case!r} did not prove all admission specs") + if "request.userInfo" in result.stdout or "expression" in result.stdout: + raise SystemExit(f"mocked pre-CA case {case!r} printed a raw admission spec") + reads = Path(environment["MOCK_JSON_READS"]).read_text().splitlines() + if len(reads) != 16 or len(set(reads)) != 16: + raise SystemExit(f"mocked pre-CA case {case!r} did not read exactly 16 fixed admission objects") + elif case.startswith("admission-") and case.endswith("api-error"): + if "result=api-error" not in result.stderr: + raise SystemExit("admission API failure was not reported fail-closed") + elif case.startswith("admission-") and case.endswith("missing-object"): + if "result=api-error" not in result.stderr: + raise SystemExit("missing admission object was not reported fail-closed") + elif case.startswith("admission-") and case.endswith("malformed-json"): + if "result=invalid-json" not in result.stderr: + raise SystemExit("malformed admission JSON was not reported fail-closed") + +repo_root = Path(sys.argv[1]).resolve().parents[2] +canonical_manifests = ( + "k8s/trust-bootstrap/issuance-admission.yaml", + "k8s/trust-bootstrap/recovery-admission.yaml", + "k8s/trust-bootstrap/deployment-admission.yaml", +) +for source_error in ("malformed-source", "missing-source"): + with tempfile.TemporaryDirectory(prefix="trust-bootstrap-source-proof-") as temporary: + temporary_path = Path(temporary) + isolated_root = temporary_path / "repo" + for manifest in canonical_manifests: + destination = isolated_root / manifest + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(repo_root / manifest, destination) + isolated_helper = ( + isolated_root + / "dev-tools/hosted/trust-bootstrap/verify-live-admission-boundary.py" + ) + isolated_helper.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile( + repo_root + / "dev-tools/hosted/trust-bootstrap/verify-live-admission-boundary.py", + isolated_helper, + ) + source_file = isolated_root / canonical_manifests[0] + if source_error == "malformed-source": + source_file.write_text("apiVersion: [malformed\n", encoding="utf-8") + else: + (isolated_root / canonical_manifests[1]).unlink() + kubectl_stub = temporary_path / "kubectl" + kubectl_stub.write_text("#!/bin/sh\nexit 99\n", encoding="utf-8") + kubectl_stub.chmod(0o755) + environment = os.environ.copy() + environment["PATH"] = str(temporary_path) + result = subprocess.run( + [ + sys.executable, + str(isolated_helper), + "--context", + "trusted-context", + ], + env=environment, + text=True, + capture_output=True, + check=False, + ) + if result.returncode == 0 or "result=source-error" not in result.stderr: + raise SystemExit( + f"mocked {source_error} case did not fail closed: " + f"{result.stderr}{result.stdout}" + ) +PY + require() { local fragment=$1 grep -Fq -- "$fragment" "$proof" || fail "proof helper is missing: $fragment" diff --git a/dev-tools/tests/workflow_version_authority_contract.py b/dev-tools/tests/workflow_version_authority_contract.py index dd34d2b6ae..45d7032609 100644 --- a/dev-tools/tests/workflow_version_authority_contract.py +++ b/dev-tools/tests/workflow_version_authority_contract.py @@ -139,6 +139,8 @@ def read_lock(path): for name, (entries, includes) in locks.items(): if includes: fail(f"{name} requirements must not include another profile") + if "websocket-client" not in locks["smoke"][0]: + fail("smoke requirements must pin the bounded WebSocket test dependency") for dependency in expected_direct_requirements["docs"]: if dependency not in locks["docs"][0]: fail(f"docs requirements must pin its direct dependency in the generated lock: {dependency}") @@ -591,6 +593,55 @@ def validate_workflow_python_steps(path, job_name, steps): fail(f"{path.name}:{job_name}: {need} helper lacks its pinned dependency profile") return setup_count + smoke_requirements_install = ( + "python3 -m pip install --disable-pip-version-check --require-hashes -r config/python/smoke-requirements.txt" + ) + full_validation_guard = "${{ needs.changes.outputs.lightweight_only != 'true' }}" + full_validation_commands = { + "python3 -m unittest discover -s dev-tools/validation -p 'test_*.py'", + "python3 -m unittest discover -s dev-tools/tests -p 'test_*.py'", + } + + def validate_dev_tool_smoke_dependencies(path, steps): + setup_indices = [ + index + for index, step in enumerate(steps) + if isinstance(step, dict) and step.get("uses") == "./.github/actions/setup-python" + ] + if len(setup_indices) != 1: + fail(f"{path.name}:dev-tool-contract-checks must set up Python exactly once") + setup_index = setup_indices[0] + install_indices = [ + index + for index, step in enumerate(steps) + if isinstance(step, dict) and "pip install" in str(step.get("run", "")) + ] + if len(install_indices) != 1: + fail(f"{path.name}:dev-tool-contract-checks must install the smoke lock exactly once") + install_index = install_indices[0] + install_step = steps[install_index] + if install_index != setup_index + 1: + fail(f"{path.name}:dev-tool-contract-checks smoke lock must install immediately after Python setup") + if str(install_step.get("run", "")).strip() != smoke_requirements_install: + fail(f"{path.name}:dev-tool-contract-checks must install the hash-locked smoke requirements") + if install_step.get("if") != full_validation_guard: + fail(f"{path.name}:dev-tool-contract-checks smoke lock install must be limited to full validation") + + full_discovery = [] + for index, step in enumerate(steps): + if not isinstance(step, dict): + continue + run_lines = {line.strip() for line in str(step.get("run", "")).splitlines()} + if full_validation_commands <= run_lines: + full_discovery.append((index, step)) + if len(full_discovery) != 1: + fail(f"{path.name}:dev-tool-contract-checks must retain full unittest discovery") + discovery_index, discovery_step = full_discovery[0] + if discovery_index <= install_index: + fail(f"{path.name}:dev-tool-contract-checks must install smoke requirements before full discovery") + if discovery_step.get("if") != full_validation_guard: + fail(f"{path.name}:dev-tool-contract-checks full unittest discovery must remain on full validation") + if python_needs("bash ./dev-tools/tests/dev-tools-readme-contract.sh") == "smoke": fail("documentation/data references must not imply the smoke dependency profile") if python_needs("bash ./services/game-session-service/websocket-login-look-smoke.sh") != "smoke": @@ -796,6 +847,19 @@ def expect_workflow_failure(steps, expected_message, *, path=workflow_fixture, j ], "profile-sequencing: smoke helper lacks its pinned dependency profile", ) + expect_workflow_failure( + [workflow_checkout, {"run": smoke_requirements_install}], + "profile-sequencing: direct or helper Python consumer uses ambient runner Python", + ) + expect_workflow_failure( + [ + workflow_checkout, + {"uses": "./.github/actions/setup-python", "with": {"requirements": "ci"}}, + {"run": smoke_requirements_install}, + {"run": python_smoke_reference}, + ], + "profile-sequencing: smoke helper lacks its pinned dependency profile", + ) conditional_setup = { "uses": "./.github/actions/setup-python", @@ -844,6 +908,41 @@ def expect_workflow_failure(steps, expected_message, *, path=workflow_fixture, j job_name="dev-tool-contract-checks", ) + valid_full_run = { + "if": full_validation_guard, + "run": "\n".join(sorted(full_validation_commands)), + } + valid_smoke_install = {"if": full_validation_guard, "run": smoke_requirements_install} + valid_smoke_dependency_steps = [workflow_checkout, conditional_setup, valid_smoke_install, valid_full_run] + validate_dev_tool_smoke_dependencies(ci_workflow_fixture, valid_smoke_dependency_steps) + + def expect_smoke_dependency_failure(steps, expected_message): + try: + validate_dev_tool_smoke_dependencies(ci_workflow_fixture, steps) + except SystemExit as error: + if expected_message not in str(error): + fail(f"smoke dependency fixture failed for an unexpected reason: {error}") + else: + fail(f"smoke dependency fixture unexpectedly passed: {expected_message}") + + expect_smoke_dependency_failure( + [ + workflow_checkout, + conditional_setup, + {**valid_smoke_install, "run": valid_smoke_install["run"].replace("--require-hashes ", "")}, + valid_full_run, + ], + "must install the hash-locked smoke requirements", + ) + expect_smoke_dependency_failure( + [workflow_checkout, conditional_setup, {**valid_smoke_install, "if": None}, valid_full_run], + "smoke lock install must be limited to full validation", + ) + expect_smoke_dependency_failure( + [workflow_checkout, conditional_setup, valid_smoke_install], + "must retain full unittest discovery", + ) + workflow_paths = sorted((*workflows.glob("*.yml"), *workflows.glob("*.yaml"))) expected_permissions = { @@ -935,6 +1034,8 @@ def expect_workflow_failure(steps, expected_message, *, path=workflow_fixture, j continue steps = job.get("steps", []) python_count += validate_workflow_python_steps(path, job_name, steps) + if path.name == "ci.yml" and job_name == "dev-tool-contract-checks": + validate_dev_tool_smoke_dependencies(path, steps) checkout = gh_setup_seen = loader = False for step in steps: if not isinstance(step, dict): diff --git a/dev-tools/validation/check_dev_demo_summary.py b/dev-tools/validation/check_dev_demo_summary.py index b35529618e..e73fe1ff00 100644 --- a/dev-tools/validation/check_dev_demo_summary.py +++ b/dev-tools/validation/check_dev_demo_summary.py @@ -17,19 +17,74 @@ import yaml WORKFLOW_RELATIVE_PATH = Path(".github/workflows/dev-demo.yml") +SUMMARY_HELPER_PATH = "./dev-tools/hosted/dev-demo/write-dev-demo-summary.sh" +SUMMARY_HELPER_NAME = "write-dev-demo-summary.sh" ALLOWED_WORKSPACE_ROOT_VARIABLES = frozenset( {"FIREMUD_REPO_ROOT", "GITHUB_WORKSPACE", "ROOT_DIR"} ) -SUMMARY_HELPER_PATTERN = re.compile( - r"(?(?:" - r"dev-tools/[A-Za-z0-9_./-]+[.]sh|" - r"[.]/dev-tools/[A-Za-z0-9_./-]+[.]sh|" - r"/[^\s;&|\"']+/dev-tools/[A-Za-z0-9_./-]+[.]sh|" - r"(?P\$(?:\{[A-Za-z_][A-Za-z0-9_]*\}|[A-Za-z_][A-Za-z0-9_]*))" - r"/dev-tools/[A-Za-z0-9_./-]+[.]sh" - r"))(?![A-Za-z0-9_./-])" +# The workflow deliberately has one supported summary language. Keep this +# parser narrower than shell itself: a direct, line-continued invocation of +# the canonical helper, followed by the exact plan outputs, is the only +# supported helper form. Unknown shell syntax is rejected rather than being +# silently omitted from the sensitive-output scan. +SUMMARY_HELPER_COMMAND_PATTERN = re.compile( + r"^(?:" + r"(?:target|success|destroyed) " + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]head_sha \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]image_tag \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]hostname \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]telnet_port \}\}"' + r"|" + r"unavailable " + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]head_sha \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]image_tag \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]hostname \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]telnet_port \}\}" ' + r'"cluster-access"' + r"|" + r"failure " + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]head_sha \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]image_tag \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]hostname \}\}" ' + r'"\$\{\{ needs[.]dev-demo-plan[.]outputs[.]telnet_port \}\}" ' + r'"\$\{DEV_DEMO_STAGE:-unknown\}"' + r') >> "\$GITHUB_STEP_SUMMARY"$' +) + +SUMMARY_METADATA_LINES = ( + "{", + 'echo ""', + 'echo "- Demo login username: ${DEMO_SMOKE_USERNAME}"', + 'echo "- Demo login email: ${DEMO_SMOKE_EMAIL}"', + 'echo "- Demo login password: repository smoke default (not printed)"', + '} >> "$GITHUB_STEP_SUMMARY"', +) +SUMMARY_STATIC_WARNING_BLOCKS = ( + ( + "{", + 'echo ""', + 'echo "### Game Design recovery"', + 'echo ""', + 'echo "**Warning:** The participant-first Helm upgrade may have left Game Design unavailable (scaled to zero or with publication endpoints drained) because the staged dev-demo deploy did not complete. Inspect and repair the Game Design Deployment, Pods, Service, and EndpointSlices before retrying."', + '} >> "$GITHUB_STEP_SUMMARY"', + ), + ( + "{", + 'echo ""', + 'echo "### Migration writer recovery"', + 'echo ""', + 'echo "**Warning:** The Account, Game Session, and Automation writer Deployments may be partially quiesced because migration activation did not complete. This can happen when writer quiescence fails or the Helm deploy fails partway through. Inspect their current state before retrying; a partial deployment may have re-enabled some writers."', + '} >> "$GITHUB_STEP_SUMMARY"', + ), +) + +REPO_SHELL_HELPER_REFERENCE = re.compile( + r"(?(?:(?:\./)?|\$(?:\{[A-Za-z_][A-Za-z0-9_]*\}|[A-Za-z_][A-Za-z0-9_]*)/|/[^\s\"']+/)" + r"dev-tools/[A-Za-z0-9_./-]+[.]sh)" + r"(?![A-Za-z0-9_./-])" ) FORBIDDEN_SUMMARY_REFERENCE = re.compile( @@ -44,21 +99,8 @@ re.IGNORECASE, ) -SUMMARY_TARGET = re.compile( - r"(?P>{1,2}|tee(?:[ \t]+(?:-a|--append))?)[ \t]*" - r"['\"]?\$\{?GITHUB_STEP_SUMMARY\}?['\"]?" -) -HEREDOC_OPEN = re.compile( - r"<<(?P-)?[ \t]*(?P['\"]?)" - r"(?P[A-Za-z_][A-Za-z0-9_]*)" - r"(?P=quote)" -) SHELL_IF_START = re.compile(r"^if\b.*;[ \t]*then$") -PLAYER_BOOTSTRAP_REQUEST_CALL = re.compile( - r"public_account_url\s*\(\s*(?P['\"])/auth/player-bootstrap" - r"(?P=quote)\s*\)", - re.DOTALL, -) +BOOTSTRAP_PYTHON_HEREDOC_OPENER = 'cat >"${BOOTSTRAP_SCRIPT}" <<\'PY\'' BOOTSTRAP_SECRET_COMMAND_PREFIX = ( "kubectl", "-n", @@ -101,8 +143,10 @@ BOOTSTRAP_PORT_FORWARD_READINESS_REQUIRED_MARKERS = ( 'BOOTSTRAP_PORT_FORWARD_LOG=/tmp/dev-demo-gateway-port-forward.log', 'if ! kill -0 "${BOOTSTRAP_PORT_FORWARD_PID}" >/dev/null 2>&1; then', - "Forwarding from 127[.]0[.]0[.]1:([0-9]+) -> 80", - 'BOOTSTRAP_GATEWAY_PORT="$({ sed -nE', + "parse_bootstrap_gateway_port() {", + r"s/^Forwarding from 127[.]0[.]0[.]1:([0-9]{1,5}) -> 8080$/\1/p", + "10#$port >= 1 && 10#$port <= 65535", + 'BOOTSTRAP_GATEWAY_PORT="$(parse_bootstrap_gateway_port "${BOOTSTRAP_PORT_FORWARD_LOG}" || true)"', '[[ "${BOOTSTRAP_GATEWAY_PORT}" =~ ^[0-9]+$ ]]', "BOOTSTRAP_GATEWAY_PORT <= 65535", 'cat "${BOOTSTRAP_PORT_FORWARD_LOG}" || true', @@ -144,8 +188,6 @@ class WorkflowRunSource: job_name: str step_name: str source: str - summary_reachable: bool = False - resolved_helper_path: Path | None = None def normalize_script(script: str) -> str: @@ -158,61 +200,6 @@ def normalize_nonempty_lines(script: str) -> str: ) -def shell_group_tokens(line: str) -> list[str]: - """Return shell grouping tokens while ignoring quoted/comment text.""" - - tokens: list[str] = [] - quote: str | None = None - escaped = False - word_started = False - index = 0 - while index < len(line): - character = line[index] - if escaped: - escaped = False - word_started = True - index += 1 - continue - if character == "\\" and quote != "'": - escaped = True - word_started = True - index += 1 - continue - if quote is not None: - if character == quote: - quote = None - index += 1 - continue - if character in "'\"": - quote = character - word_started = True - index += 1 - continue - if character == "$" and index + 1 < len(line) and line[index + 1] in "{(": - opener = line[index + 1] - closer = "}" if opener == "{" else ")" - depth = 1 - word_started = True - index += 2 - while index < len(line) and depth: - if line[index] == opener: - depth += 1 - elif line[index] == closer: - depth -= 1 - index += 1 - continue - if character == "#" and not word_started: - break - if character in "{}()": - tokens.append(character) - if character.isspace() or character in ";|&<>()": - word_started = False - else: - word_started = True - index += 1 - return tokens - - def _assert_supported_shell_if(line: str) -> None: if re.match(r"^if(?:\s|$)", line) and not SHELL_IF_START.fullmatch(line): raise AssertionError( @@ -236,87 +223,53 @@ def closing_fi_index(lines: list[str], if_index: int) -> int | None: return None -def _grouped_command_start( - lines: list[str], index: int, target_match: re.Match[str] -) -> int | None: - attached_tokens = shell_group_tokens(lines[index][: target_match.start()]) - if not attached_tokens or attached_tokens[-1] not in "})": - return None - depth = 0 - saw_closing_group = False - for candidate in range(index, -1, -1): - candidate_text = ( - lines[candidate][: target_match.start()] - if candidate == index - else lines[candidate] - ) - for token in reversed(shell_group_tokens(candidate_text)): - if token in "})": - depth += 1 - saw_closing_group = True - elif saw_closing_group and token in "{(": - depth -= 1 - if depth == 0: - return candidate - return None - - -def _summary_heredoc( - lines: list[str], start: int, index: int -) -> re.Match[str] | None: - for opener_index in range(start, index + 1): - if opener_index < index and any( - not lines[candidate].rstrip().endswith("\\") - for candidate in range(opener_index, index) - ): - continue - opener_line = lines[opener_index] - match = HEREDOC_OPEN.search(opener_line) - if match is None: - continue - suffix = opener_line[match.end() :] - if re.search(r"[;&|]", suffix) and not re.fullmatch( - r"\s*\|\s*tee(?:\s+(?:-a|--append))?\s+" - r"['\"]?\$\{?GITHUB_STEP_SUMMARY\}?['\"]?\s*", - suffix, - ): - continue - return match - return None - - def _summary_write_line_ranges(source: str) -> list[tuple[int, int]]: + """Find only canonical direct helper and exact fixed summary regions.""" + lines = source.splitlines() ranges: list[tuple[int, int]] = [] - for index, line in enumerate(lines): - target_match = SUMMARY_TARGET.search(line) - if target_match is None: - continue - start = _grouped_command_start(lines, index, target_match) - if start is None: - start = index - while start > 0 and lines[start - 1].rstrip().endswith("\\"): - start -= 1 - end = index - heredoc_match = _summary_heredoc(lines, start, index) - if heredoc_match is not None: - delimiter = heredoc_match.group("delimiter") - strip_tabs = heredoc_match.group("strip_tabs") is not None - for candidate in range(index + 1, len(lines)): - candidate_line = lines[candidate] - if strip_tabs: - candidate_line = candidate_line.lstrip("\t") - if candidate_line == delimiter: - end = candidate + index = 0 + while index < len(lines): + if lines[index].strip() == f"bash {SUMMARY_HELPER_PATH} \\": + end = index + command_lines = [lines[index].strip()] + while command_lines[-1].endswith("\\"): + end += 1 + if end >= len(lines): break - else: - end = len(lines) - 1 - ranges.append((start, end)) + command_lines.append(lines[end].strip()) + if end < len(lines): + command = " ".join( + line.removesuffix("\\").rstrip() for line in command_lines + ) + if SUMMARY_HELPER_COMMAND_PATTERN.fullmatch( + command.removeprefix(f"bash {SUMMARY_HELPER_PATH} ") + ): + ranges.append((index, end)) + index = end + if index + len(SUMMARY_METADATA_LINES) <= len(lines): + candidate = tuple( + line.strip() + for line in lines[index : index + len(SUMMARY_METADATA_LINES)] + ) + if candidate == SUMMARY_METADATA_LINES: + ranges.append((index, index + len(SUMMARY_METADATA_LINES) - 1)) + index += len(SUMMARY_METADATA_LINES) - 1 + for warning_lines in SUMMARY_STATIC_WARNING_BLOCKS: + if index + len(warning_lines) <= len(lines): + candidate = tuple( + line.strip() for line in lines[index : index + len(warning_lines)] + ) + if candidate == warning_lines: + ranges.append((index, index + len(warning_lines) - 1)) + index += len(warning_lines) - 1 + break + index += 1 return ranges def summary_write_regions(source: str) -> list[str]: - """Return shell regions that write to GITHUB_STEP_SUMMARY.""" + """Return supported regions that write to GITHUB_STEP_SUMMARY.""" lines = source.splitlines() return [ @@ -325,38 +278,30 @@ def summary_write_regions(source: str) -> list[str]: ] -def has_forbidden_summary_reference(text: str) -> bool: - normalized_text = re.sub(r"[ \t]+", " ", text) - return FORBIDDEN_SUMMARY_REFERENCE.search(normalized_text) is not None - - -def _variable_name(variable: str) -> str: - return variable[2:-1] if variable.startswith("${") else variable[1:] +def _repo_shell_helper_references(source: str) -> list[tuple[int, str]]: + """Find explicit repository shell-helper paths and their source lines.""" + return [ + (source.count("\n", 0, match.start()), match.group("path")) + for match in REPO_SHELL_HELPER_REFERENCE.finditer(source) + ] -def normalize_summary_helper_path(invocation: str, root_dir: Path) -> Path: - """Resolve a helper path, rejecting unknown variable-rooted forms.""" - root_dir = root_dir.resolve() - if invocation.startswith("$"): - variable, separator, suffix = invocation.partition("/dev-tools/") - if ( - not separator - or _variable_name(variable) not in ALLOWED_WORKSPACE_ROOT_VARIABLES - ): - allowed = ", ".join(sorted(ALLOWED_WORKSPACE_ROOT_VARIABLES)) - raise ValueError( - f"unsupported variable-prefixed summary helper path: {invocation}; " - f"allowed workspace variables: {allowed}" - ) +def _repo_shell_helper_path(reference: str, root_dir: Path) -> Path: + if reference.startswith("$"): + variable, separator, suffix = reference.partition("/dev-tools/") + variable = variable[2:-1] if variable.startswith("${") else variable[1:] + if not separator or variable not in ALLOWED_WORKSPACE_ROOT_VARIABLES: + raise AssertionError(f"unsupported repository shell helper root: {reference}") return (root_dir / "dev-tools" / suffix).resolve() - if invocation.startswith("/"): - return Path(invocation).resolve() - return (root_dir / invocation.removeprefix("./")).resolve() + if reference.startswith("/"): + return Path(reference).resolve() + return (root_dir / reference.removeprefix("./")).resolve() -def _helper_matches(source: str) -> Iterable[re.Match[str]]: - return SUMMARY_HELPER_PATTERN.finditer(source) +def has_forbidden_summary_reference(text: str) -> bool: + normalized_text = re.sub(r"[ \t]+", " ", text) + return FORBIDDEN_SUMMARY_REFERENCE.search(normalized_text) is not None def collect_workflow_run_sources(workflow: dict) -> list[WorkflowRunSource]: @@ -392,71 +337,129 @@ def collect_workflow_run_sources(workflow: dict) -> list[WorkflowRunSource]: def discover_summary_writers( workflow_run_sources: Iterable[WorkflowRunSource], root_dir: Path ) -> list[WorkflowRunSource]: - """Find direct and transitively redirected summary-producing sources.""" + """Find summary writers and reject unsupported shell/source forms.""" root_dir = root_dir.resolve() summary_writers: list[WorkflowRunSource] = [] - pending = list(workflow_run_sources) - seen_sources: dict[tuple[str, str, str], bool] = {} - seen_helpers: dict[tuple[str, Path], bool] = {} - summary_writer_indexes: dict[tuple[str, str, str] | tuple[str, Path], int] = {} - while pending: - current = pending.pop() - if current.resolved_helper_path is None: - traversal_key: tuple[str, str, str] | tuple[str, Path] = ( - current.job_name, - current.step_name, - current.source, - ) - previous_reachability = seen_sources.get(traversal_key) - else: - traversal_key = (current.job_name, current.resolved_helper_path) - previous_reachability = seen_helpers.get(traversal_key) - if previous_reachability is True or ( - previous_reachability is False and not current.summary_reachable - ): - continue - if current.resolved_helper_path is None: - seen_sources[traversal_key] = current.summary_reachable - else: - seen_helpers[traversal_key] = current.summary_reachable + pending_helpers: list[Path] = [] + seen_helpers: set[Path] = set() + for current in workflow_run_sources: direct_ranges = _summary_write_line_ranges(current.source) - if direct_ranges or current.summary_reachable: - existing_index = summary_writer_indexes.get(traversal_key) - if existing_index is None: - summary_writer_indexes[traversal_key] = len(summary_writers) + if any( + marker in current.source + for marker in ("GITHUB_STEP_SUMMARY", SUMMARY_HELPER_NAME) + ): + summary_lines = { + line_index + for line_index, line in enumerate(current.source.splitlines()) + if "GITHUB_STEP_SUMMARY" in line + } + expected_summary_lines = {end for _, end in direct_ranges} + if summary_lines != expected_summary_lines: + raise AssertionError( + "dev-demo summary must use only the canonical direct helper or " + "the exact safe metadata block; unsupported or indirect summary " + f"syntax found in {current.job_name}/{current.step_name}" + ) + helper_lines = { + line_index + for line_index, line in enumerate(current.source.splitlines()) + if SUMMARY_HELPER_NAME in line + } + expected_helper_lines = { + start + for start, _ in direct_ranges + if current.source.splitlines()[start].strip().startswith("bash ") + } + if helper_lines != expected_helper_lines: + raise AssertionError( + "dev-demo summary helper must use the canonical direct invocation; " + f"unsupported or indirect helper syntax found in {current.job_name}/{current.step_name}" + ) + if direct_ranges: summary_writers.append(current) - else: - summary_writers[existing_index] = current - for match in _helper_matches(current.source): - helper_path = normalize_summary_helper_path( - match.group("invocation"), root_dir + direct_helper_starts = { + start + for start, _ in direct_ranges + if current.source.splitlines()[start].strip().startswith("bash ") + } + for line_index, helper_reference in _repo_shell_helper_references( + current.source + ): + helper_path = _repo_shell_helper_path(helper_reference, root_dir) + canonical_path = (root_dir / SUMMARY_HELPER_PATH.removeprefix("./")).resolve() + if helper_path == canonical_path: + if line_index not in direct_helper_starts: + raise AssertionError( + "dev-demo summary helper must use the canonical direct invocation; " + f"unsupported or indirect helper syntax found in {current.job_name}/{current.step_name}" + ) + continue + pending_helpers.append(helper_path) + + while pending_helpers: + helper_path = pending_helpers.pop() + if helper_path in seen_helpers: + continue + seen_helpers.add(helper_path) + try: + helper_path.relative_to(root_dir) + except ValueError as exc: + raise AssertionError( + "repository shell helper path escapes the repository: " + f"{helper_path}" + ) from exc + if not helper_path.is_file(): + raise AssertionError(f"repository shell helper is missing: {helper_path}") + try: + helper_source = helper_path.read_text(encoding="utf-8") + except OSError as exc: + raise AssertionError( + f"repository shell helper cannot be read: {helper_path}" + ) from exc + if "GITHUB_STEP_SUMMARY" in helper_source: + raise AssertionError( + "repository shell helper must not write to GITHUB_STEP_SUMMARY: " + f"{helper_path}" ) - try: - relative_helper = helper_path.relative_to(root_dir) - except ValueError as exc: - raise ValueError( - f"summary helper path escapes repository root: {match.group('invocation')}" - ) from exc - if not helper_path.is_file(): + for _, helper_reference in _repo_shell_helper_references(helper_source): + nested_path = _repo_shell_helper_path(helper_reference, root_dir) + if nested_path == ( + root_dir / SUMMARY_HELPER_PATH.removeprefix("./") + ).resolve(): raise AssertionError( - "summary helper file is missing: " - f"{helper_path} (referenced as {match.group('invocation')})" + "repository shell helper must not invoke the canonical dev-demo " + f"summary helper: {helper_path}" ) - line_index = current.source.count("\n", 0, match.start()) - redirected = current.summary_reachable or any( - start <= line_index <= end for start, end in direct_ranges + pending_helpers.append(nested_path) + + if any( + _summary_write_line_ranges(source.source) + for source in summary_writers + ): + helper_path = root_dir / SUMMARY_HELPER_PATH.removeprefix("./") + if not helper_path.is_file(): + raise AssertionError( + "canonical dev-demo summary helper is missing: " f"{helper_path}" ) + try: helper_source = helper_path.read_text(encoding="utf-8") - pending.append( - WorkflowRunSource( - current.job_name, - f"{current.step_name}:{relative_helper.as_posix()}", - helper_source, - summary_reachable=redirected, - resolved_helper_path=helper_path, - ) + except OSError as exc: + raise AssertionError( + "canonical dev-demo summary helper cannot be read: " f"{helper_path}" + ) from exc + nested_helpers = _repo_shell_helper_references(helper_source) + if nested_helpers: + _, nested_reference = nested_helpers[0] + raise AssertionError( + "canonical dev-demo summary helper must not invoke repository " + f"shell helpers: {nested_reference}" + ) + if has_forbidden_summary_reference(helper_source): + raise AssertionError( + "canonical dev-demo summary helper must not reference " + "bootstrap credential material" ) return summary_writers @@ -682,79 +685,58 @@ def _validate_bootstrap_pod_spec(bootstrap_manifest: str) -> None: ) -def _player_bootstrap_payload_end(source: str, start: int) -> int | None: - """Return the end of the first balanced mapping after a request call.""" - - if start >= len(source) or source[start] != "{": - return None - - depth = 0 - quote: str | None = None - triple_quoted = False - escaped = False - index = start - while index < len(source): - character = source[index] - if quote is not None: - if escaped: - escaped = False - elif character == "\\": - escaped = True - elif triple_quoted: - if source.startswith(quote * 3, index): - quote = None - triple_quoted = False - index += 2 - elif character == quote: - quote = None - index += 1 - continue - if character in "'\"": - if source.startswith(character * 3, index): - quote = character - triple_quoted = True - index += 3 - else: - quote = character - index += 1 - continue - if character == "#": - newline = source.find("\n", index) - index = len(source) if newline == -1 else newline + 1 - continue - if character == "{": - depth += 1 - elif character == "}": - depth -= 1 - if depth == 0: - return index + 1 - index += 1 - return None +def _bootstrap_python_source(bootstrap_manifest: str) -> str: + """Extract the Python heredoc so shell comments and strings cannot be calls.""" + + lines = bootstrap_manifest.splitlines() + opener_indices = [ + index + for index, line in enumerate(lines) + if line.strip() == BOOTSTRAP_PYTHON_HEREDOC_OPENER + ] + if len(opener_indices) != 1: + raise AssertionError( + "dev-demo bootstrap must contain exactly one Python script heredoc" + ) + start = opener_indices[0] + 1 + try: + end = next(index for index in range(start, len(lines)) if lines[index] == "PY") + except StopIteration as exc: + raise AssertionError( + "dev-demo bootstrap Python script heredoc is unterminated" + ) from exc + return "\n".join(lines[start:end]) -def _player_bootstrap_payload(source: str, request: re.Match[str]) -> ast.Dict | None: - """Parse the mapping passed to one /auth/player-bootstrap request.""" - - payload_start = request.end() - while payload_start < len(source) and source[payload_start].isspace(): - payload_start += 1 - if payload_start >= len(source) or source[payload_start] != ",": - return None - payload_start += 1 - while payload_start < len(source) and source[payload_start].isspace(): - payload_start += 1 - payload_end = _player_bootstrap_payload_end(source, payload_start) - if payload_end is None: - return None +def _player_bootstrap_requests(bootstrap_manifest: str) -> list[ast.Call]: + """Return actual Python calls, excluding comments and string literals.""" + try: - expression = ast.parse(source[payload_start:payload_end], mode="eval") - except SyntaxError: - return None - return expression.body if isinstance(expression.body, ast.Dict) else None + python_tree = ast.parse(_bootstrap_python_source(bootstrap_manifest)) + except SyntaxError as exc: + raise AssertionError( + "dev-demo bootstrap Python script must be valid Python" + ) from exc + return [ + node + for node in ast.walk(python_tree) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == "post_json" + and len(node.args) >= 2 + and isinstance(node.args[0], ast.Call) + and isinstance(node.args[0].func, ast.Name) + and node.args[0].func.id == "public_account_url" + and node.args[0].args + and isinstance(node.args[0].args[0], ast.Constant) + and node.args[0].args[0].value == "/auth/player-bootstrap" + ] -def _validate_player_bootstrap_payload(source: str, request: re.Match[str]) -> bool: - payload = _player_bootstrap_payload(source, request) +def _validate_player_bootstrap_payload(request: ast.Call) -> bool: + if len(request.args) < 2 or not isinstance(request.args[1], ast.Dict): + return False + payload = request.args[1] if payload is None or len(payload.keys) != 2: return False fields = { @@ -884,18 +866,14 @@ def _validate_bootstrap_manifest(bootstrap_manifest: str) -> None: "dev-demo bootstrap must remove its credential secret after successful pod logging" ) - player_bootstrap_requests = list( - PLAYER_BOOTSTRAP_REQUEST_CALL.finditer(bootstrap_manifest) - ) + player_bootstrap_requests = _player_bootstrap_requests(bootstrap_manifest) player_bootstrap_request_count = len(player_bootstrap_requests) if player_bootstrap_request_count != 1: raise AssertionError( "dev-demo bootstrap must contain exactly one /auth/player-bootstrap request " f"(found {player_bootstrap_request_count})" ) - if not _validate_player_bootstrap_payload( - bootstrap_manifest, player_bootstrap_requests[0] - ): + if not _validate_player_bootstrap_payload(player_bootstrap_requests[0]): raise AssertionError( "dev-demo bootstrap must send exactly accountIdentifier and secret " "to /auth/player-bootstrap" @@ -988,10 +966,7 @@ def validate_workflow(root: Path) -> None: for source in summary_writers if any( has_forbidden_summary_reference(region) - for region in ( - summary_write_regions(source.source) - + ([source.source] if source.summary_reachable else []) - ) + for region in summary_write_regions(source.source) ) ] if offending: diff --git a/dev-tools/validation/test_check_dev_demo_summary.py b/dev-tools/validation/test_check_dev_demo_summary.py index c4de264a87..b90bc2acec 100644 --- a/dev-tools/validation/test_check_dev_demo_summary.py +++ b/dev-tools/validation/test_check_dev_demo_summary.py @@ -69,9 +69,26 @@ def _write_workflow_fixture( self, root: Path, bootstrap_manifest: str, - summary_run: str = 'echo "safe summary" >> "$GITHUB_STEP_SUMMARY"', + summary_run: str | None = None, smoke_condition: str = "${{ success() }}", ) -> None: + helper_path = root / "dev-tools/hosted/dev-demo/write-dev-demo-summary.sh" + helper_path.parent.mkdir(parents=True) + helper_path.write_text( + ( + ROOT / "dev-tools/hosted/dev-demo/write-dev-demo-summary.sh" + ).read_text(encoding="utf-8"), + encoding="utf-8", + ) + if summary_run is None: + summary_run = ( + 'bash ./dev-tools/hosted/dev-demo/write-dev-demo-summary.sh \\\n' + " success \\\n" + ' "${{ needs.dev-demo-plan.outputs.head_sha }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.image_tag }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.hostname }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.telnet_port }}" >> "$GITHUB_STEP_SUMMARY"' + ) workflow = { "jobs": { "dev-demo-deploy": { @@ -116,8 +133,7 @@ def test_validate_workflow_rejects_bootstrap_credentials_in_summary_writer(self) ) with self.assertRaisesRegex( AssertionError, - "dev-demo summaries must not reference bootstrap credential material; " - "offending summary writers: dev-demo-deploy/Summarize dev-demo access", + "unsupported or indirect summary syntax", ): self.validator.validate_workflow(root) @@ -220,9 +236,19 @@ def test_validate_workflow_rejects_multiple_player_bootstrap_requests(self): " }," ) self.assertIn(canonical_payload, bootstrap_manifest) + canonical_request = ( + "status, bootstrap_body = post_json(\n" + " " + + canonical_payload + + "\n )" + ) + self.assertIn(canonical_request, bootstrap_manifest) + duplicate_request = canonical_request.replace( + "status, bootstrap_body", "duplicate_status, duplicate_body", 1 + ) invalid_manifest = bootstrap_manifest.replace( - canonical_payload, - f"{canonical_payload}\n{canonical_payload}", + canonical_request, + f"{canonical_request}\n {duplicate_request}", 1, ) with tempfile.TemporaryDirectory() as directory: @@ -234,6 +260,37 @@ def test_validate_workflow_rejects_multiple_player_bootstrap_requests(self): ): self.validator.validate_workflow(root) + def test_validate_workflow_does_not_count_fake_bootstrap_call_comment_or_string(self): + bootstrap_manifest = self._bootstrap_manifest_fixture() + canonical_payload = ( + 'public_account_url("/auth/player-bootstrap"),\n' + " {\n" + ' "accountIdentifier": email,\n' + ' "secret": password,\n' + " }," + ) + fake_source = ( + '# public_account_url("/auth/player-bootstrap")\n' + 'fake = "public_account_url(\\"/auth/player-bootstrap\\")"' + ) + self.assertIn(canonical_payload, bootstrap_manifest) + invalid_manifest = bootstrap_manifest.replace(canonical_payload, fake_source, 1) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self._write_workflow_fixture(root, invalid_manifest) + with self.assertRaisesRegex( + AssertionError, + r"dev-demo bootstrap must contain exactly one /auth/player-bootstrap request \(found 0\)", + ): + self.validator.validate_workflow(root) + + def test_bootstrap_python_heredoc_uses_exact_shell_terminator(self): + source = ( + self.validator.BOOTSTRAP_PYTHON_HEREDOC_OPENER + + "\nprint('before')\n PY\nprint('after')\nPY\n" + ) + self.assertIn("print('after')", self.validator._bootstrap_python_source(source)) + def test_validate_workflow_accepts_reformatted_player_bootstrap_payload(self): bootstrap_manifest = self._bootstrap_manifest_fixture() canonical_payload = ( @@ -729,20 +786,6 @@ def test_smoke_account_runtime_does_not_retry_non_retryable_http_failure(self): "HTTP 400 must not be retried", ) - def test_shell_group_tokens_ignore_comments_quotes_and_expansions(self): - fixtures = ( - ("{ echo safe # comment with } and )", ["{"]), - ("{ echo safe#not-a-comment }", ["{", "}"]), - ('{ echo "# not a comment }" }', ["{", "}"]), - (r"{ echo \#not-a-comment }", ["{", "}"]), - ("{ echo '\\' }", ["{", "}"]), - ("{ echo ${value#pattern} }", ["{", "}"]), - ('{ echo $(printf "# not a comment }") }', ["{", "}"]), - ) - for fixture, expected in fixtures: - with self.subTest(fixture=fixture): - self.assertEqual(self.validator.shell_group_tokens(fixture), expected) - def test_cleanup_parsers_handle_nested_groups_and_reject_unsupported_if_forms(self): validator = self.validator nested_if = [ @@ -783,142 +826,168 @@ def test_cleanup_parsers_handle_nested_groups_and_reject_unsupported_if_forms(se ) ) - def test_summary_helper_paths_allow_only_workspace_root_variables(self): + def test_summary_write_regions_accept_only_canonical_direct_forms(self): + validator = self.validator + direct = ( + 'bash ./dev-tools/hosted/dev-demo/write-dev-demo-summary.sh \\\n' + " success \\\n" + ' "${{ needs.dev-demo-plan.outputs.head_sha }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.image_tag }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.hostname }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.telnet_port }}" >> "$GITHUB_STEP_SUMMARY"' + ) + metadata = "\n".join(validator.SUMMARY_METADATA_LINES) + self.assertEqual(len(validator.summary_write_regions(direct)), 1) + self.assertEqual(len(validator.summary_write_regions(metadata)), 1) + for warning_lines in validator.SUMMARY_STATIC_WARNING_BLOCKS: + warning = "\n".join(warning_lines) + self.assertEqual(validator.summary_write_regions(warning), [warning]) + self.assertEqual( + validator.summary_write_regions( + warning.replace("**Warning:**", "${UNTRUSTED_WARNING}") + ), + [], + ) + self.assertEqual( + validator.summary_write_regions('echo "safe summary" >> "$GITHUB_STEP_SUMMARY"'), + [], + ) + + def test_discovery_rejects_indirect_summary_sink(self): validator = self.validator with tempfile.TemporaryDirectory() as directory: root = Path(directory) - expected = root / "dev-tools/tests/smoke-transport-contract.sh" - fixtures = ( - "dev-tools/tests/smoke-transport-contract.sh", - "./dev-tools/tests/smoke-transport-contract.sh", - "bash dev-tools/tests/smoke-transport-contract.sh", - "bash ./dev-tools/tests/smoke-transport-contract.sh", - f"bash {root}/dev-tools/tests/smoke-transport-contract.sh", - "$FIREMUD_REPO_ROOT/dev-tools/tests/smoke-transport-contract.sh", - "$GITHUB_WORKSPACE/dev-tools/tests/smoke-transport-contract.sh", - "${ROOT_DIR}/dev-tools/tests/smoke-transport-contract.sh", - ) - for fixture in fixtures: - with self.subTest(fixture=fixture): - matches = list(validator._helper_matches(fixture)) - self.assertEqual(len(matches), 1) - self.assertEqual( - validator.normalize_summary_helper_path( - matches[0].group("invocation"), root - ), - expected.resolve(), - ) - unsupported = "$HOME/dev-tools/tests/smoke-transport-contract.sh" - match = next(validator._helper_matches(unsupported)) - with self.assertRaisesRegex(ValueError, "unsupported variable-prefixed"): - validator.normalize_summary_helper_path(match.group("invocation"), root) + source = [ + validator.WorkflowRunSource( + "job", + "step", + 'summary_file="$GITHUB_STEP_SUMMARY"\necho safe >> "$summary_file"', + ) + ] + with self.assertRaisesRegex(AssertionError, "unsupported or indirect summary syntax"): + validator.discover_summary_writers(source, root) - outside = root.parent / "dev-tools/tests/smoke-transport-contract.sh" + def test_discovery_rejects_unsupported_helper_indirection(self): + validator = self.validator + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source = [ + validator.WorkflowRunSource( + "job", + "step", + 'summary_helper="./dev-tools/hosted/dev-demo/write-dev-demo-summary.sh"\n' + 'bash "$summary_helper" success >> "$GITHUB_STEP_SUMMARY"', + ) + ] + with self.assertRaisesRegex(AssertionError, "unsupported or indirect summary syntax"): + validator.discover_summary_writers(source, root) + + def test_discovery_rejects_workflow_helper_summary_credential_sink(self): + validator = self.validator + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self._write_workflow_fixture( + root, + self._bootstrap_manifest_fixture(), + 'bash ./dev-tools/other-summary.sh', + ) + helper = root / "dev-tools/other-summary.sh" + helper.write_text( + 'echo "${DEMO_SMOKE_PASSWORD}" >> "$GITHUB_STEP_SUMMARY"\n', + encoding="utf-8", + ) with self.assertRaisesRegex( - ValueError, "summary helper path escapes repository root" + AssertionError, "repository shell helper must not write" ): - validator.discover_summary_writers( - [ - validator.WorkflowRunSource( - "job", - "step", - f'bash {outside} >> "$GITHUB_STEP_SUMMARY"', - ) - ], - root, - ) + validator.validate_workflow(root) - def test_summary_write_regions_preserve_group_and_heredoc_boundaries(self): + def test_discovery_accepts_canonical_direct_summary_writer_with_inline_helper(self): validator = self.validator - fixtures = ( - ('echo "safe summary" > "$GITHUB_STEP_SUMMARY"', False), - ('echo "safe summary" | tee "$GITHUB_STEP_SUMMARY"', False), - ('echo "safe summary" | tee -a "$GITHUB_STEP_SUMMARY"', False), - ( - 'echo "safe summary" | tee --append "$GITHUB_STEP_SUMMARY"', - False, - ), - ( - ( - 'printf "%s" "$DEMO_SMOKE_PASSWORD" >/tmp/password\n' - 'echo "safe summary" >> "$GITHUB_STEP_SUMMARY"' - ), - False, - ), - ( - '{\n echo "unsafe: $DEMO_SMOKE_PASSWORD"\n} >> "$GITHUB_STEP_SUMMARY"', - True, - ), - ( - ( - "cat <<'SUMMARY_EOF' >> \"$GITHUB_STEP_SUMMARY\"\n" - "unsafe: $DEMO_SMOKE_PASSWORD\n" - "SUMMARY_EOF" - ), - True, - ), - ( - ( - "cat <<-'SUMMARY_EOF' >> \"$GITHUB_STEP_SUMMARY\"\n" - "\tunsafe: $DEMO_SMOKE_PASSWORD\n" - "SUMMARY_EOF" - ), - True, - ), - ( - ( - "cat >> \"$GITHUB_STEP_SUMMARY\" <<'SUMMARY_EOF'\n" - "unsafe: $DEMO_SMOKE_PASSWORD\n" - "SUMMARY_EOF" - ), - True, - ), - ( - ( - "cat <<'SUMMARY_EOF' | tee \"$GITHUB_STEP_SUMMARY\"\n" - "unsafe: $DEMO_SMOKE_PASSWORD\n" - "SUMMARY_EOF" - ), - True, - ), - ( - '{ echo "unsafe: $DEMO_SMOKE_PASSWORD"; } >> "$GITHUB_STEP_SUMMARY"', - True, - ), - ( - '( echo "unsafe: $DEMO_SMOKE_PASSWORD" ) >> "$GITHUB_STEP_SUMMARY"', - True, - ), - ( - ( - "cat <<'UNRELATED'\n" - "unsafe: $DEMO_SMOKE_PASSWORD\n" - "UNRELATED\n" - 'echo "safe summary" >> "$GITHUB_STEP_SUMMARY"' - ), - False, - ), - ( - ( - "unrelated() {\n" - ' echo "unsafe: $DEMO_SMOKE_PASSWORD"\n' - "}\n" - 'echo "safe summary" >> "$GITHUB_STEP_SUMMARY"' - ), - False, - ), + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self._write_workflow_fixture(root, self._bootstrap_manifest_fixture()) + + writers = validator.discover_summary_writers( + validator.collect_workflow_run_sources(validator._load_workflow(root)), + root, + ) + + self.assertEqual( + [(writer.job_name, writer.step_name) for writer in writers], + [("dev-demo-deploy", "Summarize dev-demo access")], + ) + + def test_discovery_rejects_nested_canonical_summary_helper_calls(self): + validator = self.validator + child_calls = ( + 'source ./dev-tools/hosted/dev-demo/emit-summary-details.sh', + 'bash ./dev-tools/hosted/dev-demo/emit-summary-details.sh', ) - for fixture, unsafe in fixtures: - with self.subTest(fixture=fixture): - regions = validator.summary_write_regions(fixture) - self.assertEqual( - any( - validator.has_forbidden_summary_reference(region) - for region in regions - ), - unsafe, + for child_call in child_calls: + with self.subTest(child_call=child_call), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self._write_workflow_fixture(root, self._bootstrap_manifest_fixture()) + summary_helper = ( + root / "dev-tools/hosted/dev-demo/write-dev-demo-summary.sh" + ) + summary_helper.write_text(f"{child_call}\n", encoding="utf-8") + ( + root / "dev-tools/hosted/dev-demo/emit-summary-details.sh" + ).write_text( + 'printf \'%s\\n\' "${DEMO_SMOKE_PASSWORD}"\n', + encoding="utf-8", ) + with self.assertRaisesRegex( + AssertionError, + "canonical dev-demo summary helper must not invoke " + "repository shell helpers", + ): + validator.validate_workflow(root) + + def test_discovery_rejects_nested_workflow_helper_summary_credential_sink(self): + validator = self.validator + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self._write_workflow_fixture( + root, + self._bootstrap_manifest_fixture(), + 'bash ./dev-tools/outer-summary.sh', + ) + (root / "dev-tools/outer-summary.sh").write_text( + "bash ./dev-tools/inner-summary.sh\n", encoding="utf-8" + ) + (root / "dev-tools/inner-summary.sh").write_text( + 'echo "${DEMO_SMOKE_PASSWORD}" >> "$GITHUB_STEP_SUMMARY"\n', + encoding="utf-8", + ) + with self.assertRaisesRegex( + AssertionError, "repository shell helper must not write" + ): + validator.validate_workflow(root) + + def test_discovery_checks_variable_rooted_nested_helper(self): + validator = self.validator + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self._write_workflow_fixture( + root, + self._bootstrap_manifest_fixture(), + 'bash ./dev-tools/outer-summary.sh', + ) + (root / "dev-tools/outer-summary.sh").write_text( + 'source "$FIREMUD_REPO_ROOT/dev-tools/inner-summary.sh"\n', + encoding="utf-8", + ) + (root / "dev-tools/inner-summary.sh").write_text( + 'echo "${DEMO_SMOKE_PASSWORD}" >> "$GITHUB_STEP_SUMMARY"\n', + encoding="utf-8", + ) + with self.assertRaisesRegex( + AssertionError, "repository shell helper must not write" + ): + validator.validate_workflow(root) + def test_forbidden_summary_reference_detects_secret_pipelines_without_crossing_commands( self, ): @@ -954,145 +1023,31 @@ def test_forbidden_summary_reference_detects_secret_pipelines_without_crossing_c with self.subTest(fixture=fixture): self.assertFalse(validator.has_forbidden_summary_reference(fixture)) - def test_summary_reachability_propagates_through_redirected_helpers(self): - validator = self.validator - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - helper_one = root / "dev-tools/summary-one.sh" - helper_two = root / "dev-tools/summary-two.sh" - helper_one.parent.mkdir(parents=True) - helper_one.write_text( - "#!/usr/bin/env bash\nbash dev-tools/summary-two.sh\n", - encoding="utf-8", - ) - helper_two.write_text( - '#!/usr/bin/env bash\necho "unsafe: $DEMO_SMOKE_PASSWORD"\n', - encoding="utf-8", - ) - sources = [ - validator.WorkflowRunSource( - "job", - "step", - 'bash dev-tools/summary-one.sh >> "$GITHUB_STEP_SUMMARY"', - ) - ] - writers = validator.discover_summary_writers(sources, root) - self.assertEqual(len(writers), 3) - reachable_helpers = [ - writer - for writer in writers - if writer.resolved_helper_path - in {helper_one.resolve(), helper_two.resolve()} - ] - self.assertEqual(len(reachable_helpers), 2) - self.assertTrue(all(writer.summary_reachable for writer in reachable_helpers)) - self.assertTrue( - any( - validator.has_forbidden_summary_reference(writer.source) - for writer in reachable_helpers - if writer.summary_reachable - ) - ) - - def test_helper_cycles_terminate_without_repeating_resolved_paths(self): + def test_canonical_helper_is_checked_for_forbidden_references(self): validator = self.validator with tempfile.TemporaryDirectory() as directory: root = Path(directory) - helper_one = root / "dev-tools/summary-one.sh" - helper_two = root / "dev-tools/summary-two.sh" - helper_one.parent.mkdir(parents=True) - helper_one.write_text( - "#!/usr/bin/env bash\nbash dev-tools/summary-two.sh\n", - encoding="utf-8", - ) - helper_two.write_text( - "#!/usr/bin/env bash\nbash dev-tools/summary-one.sh\n", - encoding="utf-8", + helper_path = root / "dev-tools/hosted/dev-demo/write-dev-demo-summary.sh" + helper_path.parent.mkdir(parents=True) + helper_path.write_text( + 'echo "${DEMO_SMOKE_PASSWORD}"\n', encoding="utf-8" ) - sources = [ - validator.WorkflowRunSource( - "job", - "step", - 'bash dev-tools/summary-one.sh >> "$GITHUB_STEP_SUMMARY"', - ) - ] - writers = validator.discover_summary_writers(sources, root) - self.assertEqual(len(writers), 3) - resolved_helper_paths = [ - writer.resolved_helper_path - for writer in writers - if writer.resolved_helper_path is not None - ] - self.assertCountEqual( - resolved_helper_paths, [helper_one.resolve(), helper_two.resolve()] - ) - self.assertTrue( - all( - writer.summary_reachable - for writer in writers - if writer.resolved_helper_path is not None - ) - ) - - def test_helper_reprocesses_when_reachability_is_upgraded(self): - validator = self.validator - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - helper = root / "dev-tools/summary.sh" - helper.parent.mkdir(parents=True) - helper.write_text( - '#!/usr/bin/env bash\necho "unsafe: $DEMO_SMOKE_PASSWORD"\n', - encoding="utf-8", - ) - sources = [ - validator.WorkflowRunSource( - "job", - "summary-step", - 'bash dev-tools/summary.sh >> "$GITHUB_STEP_SUMMARY"', - ), - validator.WorkflowRunSource( - "job", "non-summary-step", "bash dev-tools/summary.sh" - ), - ] - writers = validator.discover_summary_writers(sources, root) - reachable_helpers = [ - writer - for writer in writers - if writer.resolved_helper_path == helper.resolve() - ] - self.assertEqual(len(reachable_helpers), 1) - self.assertTrue(reachable_helpers[0].summary_reachable) - - def test_missing_helper_fails_closed_with_clear_assertion(self): - validator = self.validator - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) source = [ validator.WorkflowRunSource( "job", "step", - 'bash dev-tools/missing-summary.sh >> "$GITHUB_STEP_SUMMARY"', + 'bash ./dev-tools/hosted/dev-demo/write-dev-demo-summary.sh \\\n' + ' success "${{ needs.dev-demo-plan.outputs.head_sha }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.image_tag }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.hostname }}" \\\n' + ' "${{ needs.dev-demo-plan.outputs.telnet_port }}" >> "$GITHUB_STEP_SUMMARY"', ) ] with self.assertRaisesRegex( - AssertionError, "summary helper file is missing" + AssertionError, "canonical dev-demo summary helper must not reference" ): validator.discover_summary_writers(source, root) - def test_discovery_fails_closed_for_unsupported_variable_helper(self): - validator = self.validator - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - source = [ - validator.WorkflowRunSource( - "job", - "step", - 'bash "$UNTRUSTED_ROOT/dev-tools/summary.sh" >> "$GITHUB_STEP_SUMMARY"', - ) - ] - with self.assertRaisesRegex(ValueError, "unsupported variable-prefixed"): - validator.discover_summary_writers(source, root) - if __name__ == "__main__": unittest.main() diff --git a/k8s/helm/firemud/values-hosted-shared.example.yaml b/k8s/helm/firemud/values-hosted-shared.example.yaml index 54f0ab3c22..f52aaad66e 100644 --- a/k8s/helm/firemud/values-hosted-shared.example.yaml +++ b/k8s/helm/firemud/values-hosted-shared.example.yaml @@ -91,7 +91,7 @@ previewStack: FIREMUD_REDIS_CACHE_HOST: redis-cache FIREMUD_REDIS_CACHE_PORT: "6379" OTEL_ENDPOINT: disabled - FIREMUD_GRPC_TLS_RELOAD_ENABLED: "false" + FIREMUD_GRPC_TLS_RELOAD_ENABLED: "true" FLUENT_ELASTICSEARCH_HOST: elasticsearch FLUENT_ELASTICSEARCH_PORT: "9200" FIREMUD_GRPC_PLAINTEXT: "false" diff --git a/k8s/hosted-identity-controller/README.md b/k8s/hosted-identity-controller/README.md index 8df1914c3a..2cb92006c5 100644 --- a/k8s/hosted-identity-controller/README.md +++ b/k8s/hosted-identity-controller/README.md @@ -54,6 +54,14 @@ The NetworkPolicy is fail-closed for controller egress. Its raw manifest contain 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. +### Live egress evidence before activation + +From the approved operator context, retain a non-secret matrix of network reachability results from the actual controller Pod after the exact-address policy is installed in `observe` mode. The loopback-only paused policy cannot establish positive egress proof. Record the Pod UID, policy resource version, observed source and destination addresses/ports, DNS answer, command exit status, timestamp, and the exact controller image digest. Do not record a kubeconfig, token, Secret, TLS key, request body, or full Pod manifest. Network success means the expected destination was reached; it does not substitute for the controller's separate TLS/SNI/SAN/issuer checks. + +The positive matrix covers `kubernetes.default:443` and the observed API endpoint `:6443`, kube-dns TCP/UDP 53, the selected Gateway ClusterIP and post-DNAT Pod target `:8443`, separate label-scoped rows for Account `:6565`, Game Session `:6565`, and Social Groups `:6565`, public Traefik HTTPS `:8443`, and, only in public mode, the allocated TCP Proxy NodePort and post-DNAT Pod target `:2323`. Each gRPC service row must be proven independently; Account reachability is not evidence for the other selectors. The negative matrix covers the same ports on a namespace without the canonical preview/dev-demo label and on Pods without the exact workload labels, an unallocated NodePort, an unrelated external address on 443, and a known-open local-node port outside the API allowance. For every denied target, first prove it is reachable from a separately isolated control Pod with no controller policy label; a refusal from a closed destination is not denial evidence. Preserve the control Pod's identity and cleanup result. Test the local-node case explicitly: if the CNI bypasses NetworkPolicy for local-node traffic, the operator must establish and prove a separate host-level restriction before activation rather than reporting the NetworkPolicy as sufficient. Run the matrix again after any CNI, Service, label, NodePort, or policy change. + +The operator records `allowed`, `denied`, or `unproved` per row with the expected and observed result. Any unexpected reachability or `unproved` negative row blocks `active` activation and PO-3.2 completion. This is an execution checklist, not a claim that the current cluster has passed it; no live matrix has been run for this revision. + 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. ## Fixed bridge CA issuer prerequisite diff --git a/k8s/trust-bootstrap/README.md b/k8s/trust-bootstrap/README.md index f55bf45103..83c9888f66 100644 --- a/k8s/trust-bootstrap/README.md +++ b/k8s/trust-bootstrap/README.md @@ -12,6 +12,165 @@ This is a prerequisite for the private Gateway–TCP Proxy bridge in #2713. It m 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 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. +## Pre-CA handoff evidence (non-secret) + +Before step 5, run the following from the reviewed repository root after the staged credentials have been finalized, with Python 3 and PyYAML installed and the explicitly approved Kubernetes context selected. It is a read-only boundary gate: it prints only caller, admission-object names and digests, resource names, and activation-mode metadata; it must not read Secret data, install resources, or repair a failed prerequisite. Its verifier reads only the eight named ValidatingAdmissionPolicies and their eight same-name bindings as JSON, pins every read to the approved context, and compares each live spec with the three canonical admission manifests. It tolerates only empty label selectors that have the same match-all meaning as an omitted selector. Save its output with the bootstrap record. Any failed assertion blocks CA generation and installation. + +```bash +set -euo pipefail + +trusted_context="${FIREMUD_HOSTED_IDENTITY_TRUSTED_CONTEXT:?set the approved Kubernetes context}" +current_context="$(kubectl config current-context)" +[[ "$current_context" == "$trusted_context" ]] || { + echo "current Kubernetes context is not the explicitly approved context" >&2 + exit 1 +} +readonly KUBECTL=(kubectl --context "$trusted_context") +operator_identity="$("${KUBECTL[@]}" auth whoami -o jsonpath='{.status.userInfo.username}')" +operator_groups="$("${KUBECTL[@]}" auth whoami -o jsonpath='{range .status.userInfo.groups[*]}{.}{"\n"}{end}')" +grep -Fx system:masters <<<"$operator_groups" >/dev/null || { + echo "current Kubernetes operator is not a system:masters member" >&2 + exit 1 +} +printf 'pre-ca-caller=%s context=%s\n' "$operator_identity" "$current_context" + +python3 dev-tools/hosted/trust-bootstrap/verify-live-admission-boundary.py \ + --context "$trusted_context" + +admission_policies=( + firemud-trust-bootstrap-certificaterequest + firemud-trust-bootstrap-certificaterequest-subresources + firemud-trust-bootstrap-certificate + firemud-trust-bootstrap-certificate-status + firemud-trust-bootstrap-ca-issuers + firemud-trust-ca-secret-boundary + firemud-trust-runtime-namespace-boundary + firemud-trust-runtime-binding-boundary +) +for policy in "${admission_policies[@]}"; do + failure_policy="$("${KUBECTL[@]}" get validatingadmissionpolicy "$policy" -o jsonpath='{.spec.failurePolicy}')" + bound_policy="$("${KUBECTL[@]}" get validatingadmissionpolicybinding "$policy" -o jsonpath='{.spec.policyName}')" + validation_actions="$("${KUBECTL[@]}" get validatingadmissionpolicybinding "$policy" -o jsonpath='{.spec.validationActions[*]}')" + [[ "$failure_policy" == Fail && "$bound_policy" == "$policy" && "$validation_actions" == Deny ]] || { + echo "trust-bootstrap admission boundary is not exactly Fail/Deny for ${policy}" >&2 + exit 1 + } + printf 'admission=%s failurePolicy=%s policyName=%s validationActions=%s\n' \ + "$policy" "$failure_policy" "$bound_policy" "$validation_actions" +done + +controller_resource="$("${KUBECTL[@]}" -n firemud-system get deployment firemud-hosted-identity-controller \ + --ignore-not-found -o name)" +if [[ -n "$controller_resource" ]]; then + controller_mode="$("${KUBECTL[@]}" -n firemud-system get deployment firemud-hosted-identity-controller \ + -o jsonpath='{.spec.template.spec.containers[?(@.name=="controller")].env[?(@.name=="FIREMUD_HOSTED_IDENTITY_ACTIVATION_MODE")].value}')" + [[ "$controller_mode" == paused ]] || { + echo "hosted identity controller is active or missing its pause marker; keep it paused before CA installation" >&2 + exit 1 + } + if ! "${KUBECTL[@]}" -n firemud-system rollout status deployment/firemud-hosted-identity-controller --timeout=480s; then + echo "hosted identity controller rollout did not complete; keep it paused before CA installation" >&2 + exit 1 + fi + + controller_generation="$("${KUBECTL[@]}" -n firemud-system get deployment firemud-hosted-identity-controller \ + -o jsonpath='{.metadata.generation}')" + controller_observed_generation="$("${KUBECTL[@]}" -n firemud-system get deployment firemud-hosted-identity-controller \ + -o jsonpath='{.status.observedGeneration}')" + controller_desired_replicas="$("${KUBECTL[@]}" -n firemud-system get deployment firemud-hosted-identity-controller \ + -o jsonpath='{.spec.replicas}')" + controller_replicas="$("${KUBECTL[@]}" -n firemud-system get deployment firemud-hosted-identity-controller \ + -o jsonpath='{.status.replicas}')" + controller_updated_replicas="$("${KUBECTL[@]}" -n firemud-system get deployment firemud-hosted-identity-controller \ + -o jsonpath='{.status.updatedReplicas}')" + controller_ready_replicas="$("${KUBECTL[@]}" -n firemud-system get deployment firemud-hosted-identity-controller \ + -o jsonpath='{.status.readyReplicas}')" + controller_available_replicas="$("${KUBECTL[@]}" -n firemud-system get deployment firemud-hosted-identity-controller \ + -o jsonpath='{.status.availableReplicas}')" + for controller_count in \ + "$controller_generation" \ + "$controller_observed_generation" \ + "$controller_desired_replicas" \ + "$controller_replicas" \ + "$controller_updated_replicas" \ + "$controller_ready_replicas" \ + "$controller_available_replicas"; do + [[ "$controller_count" =~ ^[0-9]+$ ]] || { + echo "hosted identity controller rollout evidence is missing or invalid; keep it paused before CA installation" >&2 + exit 1 + } + done + [[ "$controller_generation" -gt 0 \ + && "$controller_observed_generation" == "$controller_generation" \ + && "$controller_desired_replicas" -gt 0 \ + && "$controller_replicas" == "$controller_desired_replicas" \ + && "$controller_updated_replicas" == "$controller_desired_replicas" \ + && "$controller_ready_replicas" == "$controller_desired_replicas" \ + && "$controller_available_replicas" == "$controller_desired_replicas" ]] || { + echo "hosted identity controller rollout is not observed and converged; keep it paused before CA installation" >&2 + exit 1 + } + + controller_mode_after_rollout="$("${KUBECTL[@]}" -n firemud-system get deployment firemud-hosted-identity-controller \ + -o jsonpath='{.spec.template.spec.containers[?(@.name=="controller")].env[?(@.name=="FIREMUD_HOSTED_IDENTITY_ACTIVATION_MODE")].value}')" + [[ "$controller_mode_after_rollout" == paused ]] || { + echo "hosted identity controller pause marker changed during rollout; keep it paused before CA installation" >&2 + exit 1 + } + +else + controller_mode=absent +fi + +controller_pods="$("${KUBECTL[@]}" -n firemud-system get pods \ + -l app.kubernetes.io/name=hosted-environment-identity-controller,app.kubernetes.io/component=controller \ + -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[?(@.name=="controller")].env[?(@.name=="FIREMUD_HOSTED_IDENTITY_ACTIVATION_MODE")].value}{"\n"}{end}')" +controller_pod_count=0 +while IFS=$'\t' read -r controller_pod_name controller_pod_mode; do + [[ -n "$controller_pod_name" ]] || continue + controller_pod_count=$((controller_pod_count + 1)) + [[ "$controller_pod_mode" == paused ]] || { + echo "hosted identity controller Pod ${controller_pod_name} is not exactly paused; keep it paused before CA installation" >&2 + exit 1 + } +done <<< "$controller_pods" +if [[ -n "$controller_resource" ]]; then + [[ "$controller_pod_count" == "$controller_desired_replicas" ]] || { + echo "hosted identity controller Pods do not match converged replicas; keep it paused before CA installation" >&2 + exit 1 + } +else + [[ "$controller_pod_count" == 0 ]] || { + echo "hosted identity controller Deployment is absent but matching Pods remain; keep the pre-CA gate closed" >&2 + exit 1 + } +fi +printf 'controllerActivation=%s\n' "${controller_mode:-absent}" + +for resource in \ + "clusterissuer firemud-ca-issuer" \ + "-n firemud-system secret firemud-grpc-ca" \ + "-n cert-manager secret firemud-grpc-ca" \ + "-n kube-system serviceaccount preview-deployer" \ + "clusterrolebinding preview-deployer"; do + resource_names="" + if ! resource_names="$("${KUBECTL[@]}" get $resource --ignore-not-found -o name)"; then + echo "pre-CA handoff could not verify resource absence: ${resource}" >&2 + exit 1 + fi + if [[ -n "$resource_names" ]]; then + echo "pre-CA handoff found a forbidden existing resource: ${resource}" >&2 + exit 1 + fi +done +printf 'pre-ca-resources=issuer-and-fixed-secrets-absent legacy-credential=revoked\n' +printf 'pre-ca-handoff=pass\n' +``` + +The verifier's JSON reads are limited to those fixed public admission objects; its output contains names and SHA-256 digests, never raw objects. The policy specs must exactly match the checked-in manifests, so same-name Fail/Deny objects with missing or weakened expressions, conditions, match scope, variables, or binding parameters do not pass. The separate live denial and canonical-allow probes in required-order step 3 remain mandatory. The resource loop intentionally reads only object names (`-o name`); it is not a CA or credential readback. This gate does not prove CA validity, cert-manager issuance, served identity, or consumer convergence. Those remain the private recovery, issuer, and later hosted-controller proof obligations below. + +The controller checks are a read-only point-in-time snapshot: they prove rollout and paused-mode readback at this gate, but do not prevent a later independent operator change to the Deployment. + ## Recovery copy and rotation `FIREMUD_PREVIEW_CA_RECOVERY_BUNDLE` is a versioned JSON envelope with base64 PEM certificate and private key plus the public SHA-256 fingerprint. It is stored only as a GitHub Environment secret; the expected fingerprint is a separate Environment variable and must also match the deployed controller trust anchor. `preview-ca-recovery.yml` checks out only `develop`, selects only the recovery Environment, and accepts `verify` or `restore`. The script refuses malformed, mismatched, expired, non-RSA-4096, non-CA, or non-self-signed material. A fresh cluster first installs the same reviewed admission/RBAC boundary and reissues a scoped recovery kubeconfig; it must not reuse a token from the lost cluster. The recovery copy is independently usable without the original operator machine or password manager. @@ -23,3 +182,11 @@ Scoped deployment kubeconfigs use dedicated ServiceAccount token Secrets labeled ## Current state The recovery Environment and its `develop` branch policy were created on 2026-09-21. No recovery bundle, fingerprint, or recovery kubeconfig has been populated yet. No FireMUD internal CA has been generated or installed; the controller remains inactive. This note must be updated with the actual live proof before the prerequisite is called operationally complete. + +## Hosted playable diagnostic after activation + +Once the protected bootstrap above and controller activation have their own live proof, and Gate 1's exact base/head/merge/image Namespace annotations are present in the deployed trusted workflow, an eligible public preview can run the trusted default-branch `verify-runtime` job in `hosted-identity-request.yml`. The job waits for controller identity and runtime rollouts, runs the public Telnet `LOGIN → PLAY → LOOK` probe, then runs the first-party WSS flow with a fresh one-use connect token. Both probes receive the same trusted demo account, password, world, realm, and optional character mapping; ambient transport-specific overrides cannot split parity evidence. The WSS probe compares its structured LOOK room ID with Telnet, closes and reconnects with a second fresh token, and checks that the consumed cookie is rejected as a replay. It does not issue LOGOUT or use candidate-controlled scripts after the runtime kubeconfig enters scope. + +The trusted job revalidates the open PR's exact base, head, and merge binding, requested/deployed Namespace annotations, and runtime Namespace UID around diagnostics. It fails closed if the current parent stack has not yet absorbed Gate 1's annotation contract. Its bounded `hosted-playable-diagnostic-pr-N-` artifact records the validated source tuple, Namespace UID and allocation, controller observed generation and five projection revisions, running application image tags and runtime digests, and the two transport outcomes. Raw Kubernetes objects, connect tokens, credentials, CA keys, and kubeconfigs are not artifacts. A passing artifact is a diagnostic for this exact deployed preview, not production readiness, browser acceptance under [ADR 0178](../../design/architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md), or proof of CNI/local-node egress policy. + +Before treating this as live evidence, the operator must separately retain non-secret records of the pre-CA admission and credential checks, recovery-copy verification, issuer readiness, controller activation order, served Gateway/TCP Proxy and gRPC certificate identities, projection rotation/convergence, and the [controller egress allow/deny matrix](../hosted-identity-controller/README.md#live-egress-evidence-before-activation). A denied target alone is insufficient to establish egress policy when the target might be unreachable; use a permitted positive control and record the CNI/local-node handling. This diagnostic covers reconnect after transport close and token-replay rejection; successful logout, an active simultaneous-controller takeover, and post-logout replay-suppression proof remain separate player-session obligations, not implied by this artifact. LOGOUT remains fail-closed until its [durable terminal episode fence](../../design/architecture/system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate) is implemented and proved. Do not run a live active takeover against the shared demo character: it changes binding and presence state. That proof requires an explicitly isolated disposable character and two concurrent fresh-token sockets, and must not claim the still-unimplemented namespace-scoped atomic takeover contract. If any protected value, issuer, or controller is absent, stop before activation and report that precise gate. Local tests and rendered manifests are not substitutes for these live observations. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java index 1efb1f3de5..4092522f01 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java @@ -21,7 +21,6 @@ import net.firedevops.firemud.socialgroups.v1.AddFriendResponse; import net.firedevops.firemud.socialgroups.v1.FriendPresenceActivityState; import net.firedevops.firemud.socialgroups.v1.FriendPresenceEntry; -import net.firedevops.firemud.socialgroups.v1.FriendRecentPresenceDisposition; import net.firedevops.firemud.socialgroups.v1.FriendRosterEntry; import net.firedevops.firemud.socialgroups.v1.FriendRosterFilter; import net.firedevops.firemud.socialgroups.v1.GetFriendByOrdinalResponse; @@ -107,6 +106,9 @@ public TextCommandInterpretationResult handle(TextCommand command, SessionContex private TextCommandInterpretationResult handleList( SessionContext context, FriendListFilter filter, String rawCommandText) { + if (!isPlayerSafeFilter(filter)) { + return friendFilterUnavailable(); + } ListFriendsResponse response = filter == FriendListFilter.ALL ? socialGroupsClient.listFriends(context.tenantId(), context.accountId()) @@ -135,6 +137,19 @@ private TextCommandInterpretationResult handleList( CommandEnqueueResult.success(), List.of(PlayerOutput.view(view))); } + private TextCommandInterpretationResult friendFilterUnavailable() { + return new TextCommandInterpretationResult( + CommandEnqueueResult.failure("FRIEND_PRESENCE_UNAVAILABLE", "Friend presence unavailable"), + List.of(PlayerOutput.error("FRIEND_PRESENCE_UNAVAILABLE", "Friend presence unavailable"))); + } + + private boolean isPlayerSafeFilter(FriendListFilter filter) { + return switch (filter) { + case OFFLINE, PUBLIC, FRIENDS_ONLY, PRIVATE, SHARED, ISOLATED, UNSPECIFIED_SCOPE -> false; + default -> true; + }; + } + private TextCommandInterpretationResult handleAdd( SessionContext context, ResolvedFriendTarget target, String rawCommandText) { if (target.friendAccountId() == context.accountId()) { @@ -266,19 +281,7 @@ private TextCommandInterpretationResult handleSummary( CommandEnqueueResult.success(), List.of( PlayerOutput.view( - new FriendRosterSummaryViewOutput( - response.getSummary().getTotalCount(), - response.getSummary().getOnlineCount(), - response.getSummary().getOfflineCount(), - response.getSummary().getRecentCount(), - response.getSummary().getPublicCount(), - response.getSummary().getFriendsOnlyCount(), - response.getSummary().getPrivateCount(), - response.getSummary().getHiddenStaffCount(), - response.getSummary().getUnspecifiedVisibilityCount(), - response.getSummary().getSharedCount(), - response.getSummary().getIsolatedCount(), - response.getSummary().getUnspecifiedScopeCount())))); + new FriendRosterSummaryViewOutput(response.getSummary().getTotalCount())))); } private TextCommandInterpretationResult handleVisibilityView( @@ -310,12 +313,6 @@ private TextCommandInterpretationResult handleVisibilityUpdate( if (visibilityPolicy == null) { return invalidUsage("FRIENDS VISIBILITY "); } - if (visibilityPolicy - == net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy - .FRIEND_PRESENCE_VISIBILITY_POLICY_HIDDEN_STAFF) { - return friendTargetError( - "INVALID_ARGUMENT", "HIDDEN_STAFF is reserved and cannot be set from gameplay"); - } UpdateFriendPresencePolicyResponse response = socialGroupsClient.updateFriendPresencePolicy( context.tenantId(), context.accountId(), visibilityPolicy); @@ -430,13 +427,15 @@ private FriendPresenceViewOutput toView(ListFriendsResponse response, FriendList List mapped = canonicalFiltered ? allEntries : allEntries.stream().filter(filter::matches).toList(); int totalCount = response.getTotalCount() > 0 ? response.getTotalCount() : allEntries.size(); - int matchCount = response.getMatchCount() > 0 ? response.getMatchCount() : mapped.size(); - return new FriendPresenceViewOutput(filter.name(), totalCount, matchCount, mapped); + return new FriendPresenceViewOutput(filter.name(), totalCount, mapped); } private FriendPresenceViewOutput.Entry toEntry(int ordinal, FriendRosterEntry entry) { FriendPresenceEntry presence = entry.getPresence(); long friendAccountId = requireFriendAccountId(entry.getFriendAccountId()); + if (!isPlayerDisclosablePolicy(presence.getVisibilityPolicy())) { + return redactedEntry(ordinal, entry, friendAccountId, "Friend #" + friendAccountId); + } String characterName = presence.getCharacterName().isBlank() ? null : presence.getCharacterName().trim(); return new FriendPresenceViewOutput.Entry( @@ -447,19 +446,50 @@ private FriendPresenceViewOutput.Entry toEntry(int ordinal, FriendRosterEntry en entry.getCreatedAtMs() > 0 ? entry.getCreatedAtMs() : null, characterName != null ? characterName : "Friend #" + friendAccountId, presence.getOnline(), - blankToNull(presence.getWorldSlug()), - blankToNull(presence.getWorldDisplayName()), - blankToNull(presence.getRealmSlug()), - blankToNull(presence.getRealmDisplayName()), + null, + null, + null, + null, characterName, - playableStateScope(presence.getPlayableStateScope()), - presence.getPointerVersion() > 0 ? presence.getPointerVersion() : null, + null, + null, activityState(presence.getActivityState()), presence.getLastSeenAtMs() > 0 ? presence.getLastSeenAtMs() : null, - recentDisposition(presence.getRecentDisposition()), visibilityPolicy(presence.getVisibilityPolicy())); } + private FriendPresenceViewOutput.Entry redactedEntry( + int ordinal, FriendRosterEntry entry, long friendAccountId, String displayName) { + return new FriendPresenceViewOutput.Entry( + ordinal, + parseOptionalLong(entry.getFriendLinkId()), + friendAccountId, + blankToNull(entry.getStatus()), + entry.getCreatedAtMs() > 0 ? entry.getCreatedAtMs() : null, + displayName, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null); + } + + private boolean isPlayerDisclosablePolicy( + net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy policy) { + return policy + == net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC + || policy + == net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_FRIENDS_ONLY; + } + private String activityState(FriendPresenceActivityState activityState) { return switch (activityState) { case FRIEND_PRESENCE_ACTIVITY_STATE_ACTIVE -> "ACTIVE"; @@ -493,30 +523,12 @@ private String blankToNull(String value) { return value == null || value.isBlank() ? null : value; } - private String recentDisposition(FriendRecentPresenceDisposition disposition) { - return switch (disposition) { - case FRIEND_RECENT_PRESENCE_DISPOSITION_TRANSPORT_LOSS -> "TRANSPORT_LOSS"; - case FRIEND_RECENT_PRESENCE_DISPOSITION_LOGOUT -> "LOGOUT"; - case FRIEND_RECENT_PRESENCE_DISPOSITION_TAKEOVER -> "TAKEOVER"; - default -> null; - }; - } - - private String playableStateScope(PlayableStateScope scope) { - return switch (scope) { - case PLAYABLE_STATE_SCOPE_SHARED -> "SHARED"; - case PLAYABLE_STATE_SCOPE_ISOLATED -> "ISOLATED"; - default -> null; - }; - } - private String visibilityPolicy( net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy visibilityPolicy) { return switch (visibilityPolicy) { case FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC -> "PUBLIC"; case FRIEND_PRESENCE_VISIBILITY_POLICY_FRIENDS_ONLY -> "FRIENDS_ONLY"; case FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE -> "PRIVATE"; - case FRIEND_PRESENCE_VISIBILITY_POLICY_HIDDEN_STAFF -> "HIDDEN_STAFF"; default -> null; }; } @@ -558,16 +570,10 @@ private FriendAction parseAction(TextCommand command) { FriendActionKind.LIST, "LIST", FriendListFilter.FRIENDS_ONLY, null, null); case "PRIVATE" -> new FriendAction(FriendActionKind.LIST, "LIST", FriendListFilter.PRIVATE, null, null); - case "HIDDEN_STAFF", "HIDDEN-STAFF", "HIDDEN" -> - new FriendAction( - FriendActionKind.LIST, "LIST", FriendListFilter.HIDDEN_STAFF, null, null); case "SHARED" -> new FriendAction(FriendActionKind.LIST, "LIST", FriendListFilter.SHARED, null, null); case "ISOLATED" -> new FriendAction(FriendActionKind.LIST, "LIST", FriendListFilter.ISOLATED, null, null); - case "UNSPECIFIED", "UNKNOWN", "UNSPECIFIED_VISIBILITY" -> - new FriendAction( - FriendActionKind.LIST, "LIST", FriendListFilter.UNSPECIFIED_VISIBILITY, null, null); case "UNSCOPED", "UNKNOWN_SCOPE", "UNSPECIFIED_SCOPE" -> new FriendAction( FriendActionKind.LIST, "LIST", FriendListFilter.UNSPECIFIED_SCOPE, null, null); @@ -577,7 +583,7 @@ private FriendAction parseAction(TextCommand command) { "INVALID", FriendListFilter.ALL, null, - "FRIENDS [ADD|REMOVE|SHOW|SUMMARY|VISIBILITY|ONLINE|OFFLINE|RECENT|PUBLIC|FRIENDS_ONLY|PRIVATE|HIDDEN_STAFF|UNSPECIFIED_VISIBILITY|SHARED|ISOLATED|UNSPECIFIED_SCOPE]"); + "FRIENDS [ADD|REMOVE|SHOW|SUMMARY|VISIBILITY|ONLINE|RECENT|SHARED|ISOLATED]"); }; } @@ -680,8 +686,6 @@ private FriendRosterFilter mapRosterFilter(FriendListFilter filter) { case PUBLIC -> FriendRosterFilter.FRIEND_ROSTER_FILTER_PUBLIC; case FRIENDS_ONLY -> FriendRosterFilter.FRIEND_ROSTER_FILTER_FRIENDS_ONLY; case PRIVATE -> FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE; - case HIDDEN_STAFF -> FriendRosterFilter.FRIEND_ROSTER_FILTER_HIDDEN_STAFF; - case UNSPECIFIED_VISIBILITY -> FriendRosterFilter.FRIEND_ROSTER_FILTER_UNSPECIFIED_VISIBILITY; case SHARED -> FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED; case ISOLATED -> FriendRosterFilter.FRIEND_ROSTER_FILTER_ISOLATED; case UNSPECIFIED_SCOPE -> FriendRosterFilter.FRIEND_ROSTER_FILTER_UNSPECIFIED_SCOPE; @@ -716,37 +720,35 @@ private String notFoundMessage(String targetToken) { private FriendPresencePolicyViewOutput friendPresencePolicyView( net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy current) { + net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy effectiveCurrent = + isPlayerDisclosablePolicy(current) + ? current + : net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE; return new FriendPresencePolicyViewOutput( - visibilityPolicy(current), + visibilityPolicy(effectiveCurrent), List.of( new FriendPresencePolicyViewOutput.Option( "PUBLIC", "Show the normal bounded friend-presence payload to approved social consumers.", - current + effectiveCurrent == net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC, true), new FriendPresencePolicyViewOutput.Option( "FRIENDS_ONLY", "Expose richer live identity only to approved friends.", - current + effectiveCurrent == net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_FRIENDS_ONLY, true), new FriendPresencePolicyViewOutput.Option( "PRIVATE", - "Suppress current live character identity and expose only coarse online or recent activity.", - current + "Do not expose current presence, recent activity, or location details.", + effectiveCurrent == net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE, - true), - new FriendPresencePolicyViewOutput.Option( - "HIDDEN_STAFF", - "Reserved for staff-hidden role clamps and not set directly from gameplay.", - current - == net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy - .FRIEND_PRESENCE_VISIBILITY_POLICY_HIDDEN_STAFF, - false))); + true))); } private net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy @@ -765,9 +767,6 @@ private FriendPresencePolicyViewOutput friendPresencePolicyView( case "PRIVATE" -> net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE; - case "HIDDEN_STAFF" -> - net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy - .FRIEND_PRESENCE_VISIBILITY_POLICY_HIDDEN_STAFF; default -> null; }; } @@ -792,19 +791,19 @@ boolean matches(FriendPresenceViewOutput.Entry entry) { ONLINE { @Override boolean matches(FriendPresenceViewOutput.Entry entry) { - return entry.online(); + return Boolean.TRUE.equals(entry.online()); } }, OFFLINE { @Override boolean matches(FriendPresenceViewOutput.Entry entry) { - return !entry.online(); + return Boolean.FALSE.equals(entry.online()); } }, RECENT { @Override boolean matches(FriendPresenceViewOutput.Entry entry) { - return !entry.online() && entry.lastSeenAtEpochMs() != null; + return Boolean.FALSE.equals(entry.online()) && entry.lastSeenAtEpochMs() != null; } }, PUBLIC { @@ -822,13 +821,7 @@ boolean matches(FriendPresenceViewOutput.Entry entry) { PRIVATE { @Override boolean matches(FriendPresenceViewOutput.Entry entry) { - return "PRIVATE".equals(entry.visibilityPolicy()); - } - }, - HIDDEN_STAFF { - @Override - boolean matches(FriendPresenceViewOutput.Entry entry) { - return "HIDDEN_STAFF".equals(entry.visibilityPolicy()); + return !StringUtils.hasText(entry.visibilityPolicy()); } }, SHARED { @@ -843,12 +836,6 @@ boolean matches(FriendPresenceViewOutput.Entry entry) { return "ISOLATED".equals(entry.playableStateScope()); } }, - UNSPECIFIED_VISIBILITY { - @Override - boolean matches(FriendPresenceViewOutput.Entry entry) { - return !StringUtils.hasText(entry.visibilityPolicy()); - } - }, UNSPECIFIED_SCOPE { @Override boolean matches(FriendPresenceViewOutput.Entry entry) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java index dc26f8c5f3..5331c1b9bf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java @@ -119,14 +119,15 @@ public TextCommandInterpretationResult handle( success( "FRIENDS\n" + "List your linked friends with bounded cross-game presence.\n" - + "FRIENDS SUMMARY shows canonical linked/online/offline/recent counts.\n" - + "FRIENDS ONLINE, FRIENDS OFFLINE, FRIENDS RECENT, FRIENDS PUBLIC, FRIENDS FRIENDS_ONLY, FRIENDS PRIVATE, FRIENDS HIDDEN_STAFF, FRIENDS UNSPECIFIED_VISIBILITY, FRIENDS SHARED, FRIENDS ISOLATED, and FRIENDS UNSPECIFIED_SCOPE filter the same canonical roster without widening WHO.\n" + + "FRIENDS SUMMARY shows the canonical linked-friend total.\n" + + "FRIENDS ONLINE and FRIENDS RECENT filter the same canonical roster without widening WHO.\n" + + "SHARED and ISOLATED filters are currently unavailable until Social provides viewer-bound location discovery.\n" + "FRIENDS SHOW shows one canonical friend roster entry in detail, including #entryNumber lookups from the rendered roster.\n" + "FRIENDS ADD links another account-scoped friend.\n" + "FRIENDS REMOVE removes an existing account-scoped friend, including canonical #entryNumber removal.\n" + "FRIENDS VISIBILITY shows your current cross-game friend-presence policy, and FRIENDS VISIBILITY updates it.\n" - + "Visible entries show current world/realm labels, character name, and activity state when policy allows.\n" - + "Private or hidden-staff friends stay conservative."); + + "Player output currently withholds world/realm labels; policy-authorized presence, character, and activity remain visible.\n" + + "Private friends stay conservative."); case "INVENTORY" -> success( "INVENTORY shows what you are carrying.\n" diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java index b31bff8ecb..0a9745b6ff 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java @@ -1,14 +1,15 @@ package net.firedevops.firemud.gamesession.presentation; +import com.fasterxml.jackson.annotation.JsonInclude; import java.util.List; -public record FriendPresenceViewOutput( - String filter, int totalCount, int matchCount, List friends) +public record FriendPresenceViewOutput(String filter, int totalCount, List friends) implements PlayerOutputPayload { public FriendPresenceViewOutput { friends = List.copyOf(friends); } + @JsonInclude(JsonInclude.Include.NON_NULL) public record Entry( int ordinal, Long friendLinkId, @@ -16,7 +17,7 @@ public record Entry( String status, Long linkedAtEpochMs, String displayName, - boolean online, + Boolean online, String worldSlug, String worldDisplayName, String realmSlug, @@ -26,6 +27,5 @@ public record Entry( Long pointerVersion, String activityState, Long lastSeenAtEpochMs, - String recentDisposition, String visibilityPolicy) {} } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendRosterSummaryViewOutput.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendRosterSummaryViewOutput.java index 44b477188c..4d3d4147cf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendRosterSummaryViewOutput.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendRosterSummaryViewOutput.java @@ -1,16 +1,3 @@ package net.firedevops.firemud.gamesession.presentation; -public record FriendRosterSummaryViewOutput( - int totalCount, - int onlineCount, - int offlineCount, - int recentCount, - int publicCount, - int friendsOnlyCount, - int privateCount, - int hiddenStaffCount, - int unspecifiedVisibilityCount, - int sharedCount, - int isolatedCount, - int unspecifiedScopeCount) - implements PlayerOutputPayload {} +public record FriendRosterSummaryViewOutput(int totalCount) implements PlayerOutputPayload {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java index de6a73597d..e86710a553 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java @@ -463,9 +463,7 @@ private String renderFriendsView(FriendPresenceViewOutput output) { if (output.friends().isEmpty()) { return "Friends " + output.filter().toUpperCase(java.util.Locale.ROOT) - + " [0/" - + output.totalCount() - + "]: no matching friends."; + + ": no matching friends."; } String body = output.friends().stream() @@ -484,14 +482,7 @@ private String renderFriendsView(FriendPresenceViewOutput output) { if ("ALL".equalsIgnoreCase(output.filter())) { return body; } - return "Friends " - + output.filter().toUpperCase(java.util.Locale.ROOT) - + " [" - + output.matchCount() - + "/" - + output.totalCount() - + "]:\n" - + body; + return "Friends " + output.filter().toUpperCase(java.util.Locale.ROOT) + ":\n" + body; } private String renderFriendDetailView(FriendDetailViewOutput output) { @@ -541,31 +532,7 @@ private String renderFriendDetailView(FriendDetailViewOutput output) { } private String renderFriendRosterSummaryView(FriendRosterSummaryViewOutput output) { - return "Friend roster summary:" - + "\nLinked: " - + output.totalCount() - + "\nOnline: " - + output.onlineCount() - + "\nOffline: " - + output.offlineCount() - + "\nRecent offline: " - + output.recentCount() - + "\nVisibility public: " - + output.publicCount() - + "\nVisibility friends-only: " - + output.friendsOnlyCount() - + "\nVisibility private: " - + output.privateCount() - + "\nVisibility hidden-staff: " - + output.hiddenStaffCount() - + "\nVisibility unspecified: " - + output.unspecifiedVisibilityCount() - + "\nScope shared: " - + output.sharedCount() - + "\nScope isolated: " - + output.isolatedCount() - + "\nScope unspecified: " - + output.unspecifiedScopeCount(); + return "Friend roster summary:" + "\nLinked: " + output.totalCount(); } private String renderFriendPresencePolicyView(FriendPresencePolicyViewOutput output) { @@ -596,7 +563,10 @@ private String renderFriendStatusSuffix(FriendPresenceViewOutput.Entry entry) { } private String renderFriendStatus(FriendPresenceViewOutput.Entry entry) { - if (entry.online()) { + if (isRedactedFriendPresence(entry)) { + return "presence unavailable"; + } + if (Boolean.TRUE.equals(entry.online())) { StringBuilder line = new StringBuilder("online"); String location = renderFriendLocation(entry); if (StringUtils.hasText(location)) { @@ -615,18 +585,25 @@ private String renderFriendStatus(FriendPresenceViewOutput.Entry entry) { return line.toString(); } if (entry.lastSeenAtEpochMs() != null) { - String qualifier = - switch (entry.recentDisposition()) { - case "LOGOUT" -> "logged out"; - case "TAKEOVER" -> "replaced session"; - case "TRANSPORT_LOSS" -> "connection lost"; - default -> "last seen"; - }; - return qualifier + " " + java.time.Instant.ofEpochMilli(entry.lastSeenAtEpochMs()); + return "last seen " + java.time.Instant.ofEpochMilli(entry.lastSeenAtEpochMs()); } return "offline"; } + private boolean isRedactedFriendPresence(FriendPresenceViewOutput.Entry entry) { + return !StringUtils.hasText(entry.visibilityPolicy()) + && !Boolean.TRUE.equals(entry.online()) + && entry.lastSeenAtEpochMs() == null + && !StringUtils.hasText(entry.worldSlug()) + && !StringUtils.hasText(entry.worldDisplayName()) + && !StringUtils.hasText(entry.realmSlug()) + && !StringUtils.hasText(entry.realmDisplayName()) + && !StringUtils.hasText(entry.characterName()) + && !StringUtils.hasText(entry.playableStateScope()) + && entry.pointerVersion() == null + && !StringUtils.hasText(entry.activityState()); + } + private String renderFriendLocation(FriendPresenceViewOutput.Entry entry) { if (StringUtils.hasText(entry.worldDisplayName()) && StringUtils.hasText(entry.realmDisplayName())) { @@ -639,6 +616,9 @@ private String renderFriendLocation(FriendPresenceViewOutput.Entry entry) { } private String renderFriendActivity(String activityState) { + if (!StringUtils.hasText(activityState)) { + return null; + } return switch (activityState) { case "AUTO_AFK" -> "idle"; case "EXPLICIT_AFK" -> "AFK"; diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index c254a871ee..896df3bb95 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -229,18 +229,21 @@ void websocketFriendsShowsCanonicalCrossGamePresence() throws Exception { List responses = runCommunicationSequence( - sessionId, - "FRIENDS", - "Sora [acct #" + SORA_ACCOUNT_ID + "] - online in Demo World / Live Realm (idle)"); + sessionId, "FRIENDS", "Sora [acct #" + SORA_ACCOUNT_ID + "] - online (idle)"); assertThat(responses).hasSizeGreaterThanOrEqualTo(3); assertThat(responses) .anyMatch( + response -> response.contains("Sora [acct #" + SORA_ACCOUNT_ID + "] - online (idle)")); + assertThat(responses) + .noneMatch( response -> - response.contains( - "Sora [acct #" - + SORA_ACCOUNT_ID - + "] - online in Demo World / Live Realm (idle)")); + response.contains("private-playtest") + || response.contains("Private Playtest World") + || response.contains("staff-preview") + || response.contains("Staff Preview Realm") + || response.contains("shared") + || response.contains("Pointer version")); GameplaySocialAssertions.assertListFriendsRequest( socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), Long.toString(ACCOUNT_ID)); } @@ -254,19 +257,14 @@ void websocketFriendsOnlineFiltersCanonicalRoster() throws Exception { runCommunicationSequence( sessionId, "FRIENDS ONLINE", - "Friends ONLINE [1/1]:\n" - + "1) Sora [acct #" - + SORA_ACCOUNT_ID - + "] - online in Demo World / Live Realm (idle)"); + "Friends ONLINE:\n" + "1) Sora [acct #" + SORA_ACCOUNT_ID + "] - online (idle)"); assertThat(responses) .anyMatch( response -> - response.contains("Friends ONLINE [1/1]:") + response.contains("Friends ONLINE:\n") && response.contains( - "1) Sora [acct #" - + SORA_ACCOUNT_ID - + "] - online in Demo World / Live Realm (idle)")); + "1) Sora [acct #" + SORA_ACCOUNT_ID + "] - online (idle)")); GameplaySocialAssertions.assertListFriendsRequest( socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), @@ -275,32 +273,25 @@ void websocketFriendsOnlineFiltersCanonicalRoster() throws Exception { } @Test - void websocketFriendsSharedFiltersCanonicalRoster() throws Exception { + void websocketLocationScopeFiltersFailClosedWithoutSocialQuery() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); - List responses = - runCommunicationSequence( - sessionId, - "FRIENDS SHARED", - "Friends SHARED [1/1]:\n" - + "1) Sora [acct #" - + SORA_ACCOUNT_ID - + "] - online in Demo World / Live Realm (idle)"); - - assertThat(responses) - .anyMatch( - response -> - response.contains("Friends SHARED [1/1]:") - && response.contains( - "1) Sora [acct #" - + SORA_ACCOUNT_ID - + "] - online in Demo World / Live Realm (idle)")); - GameplaySocialAssertions.assertListFriendsRequest( - socialStub().lastFriendsRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - net.firedevops.firemud.socialgroups.v1.FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED); + for (String filter : List.of("SHARED", "ISOLATED")) { + List responses = + runCommunicationSequence( + sessionId, + "FRIENDS " + filter, + "ERROR FRIEND_PRESENCE_UNAVAILABLE Friend presence unavailable"); + + assertThat(responses) + .anyMatch( + response -> + response.contains( + "ERROR FRIEND_PRESENCE_UNAVAILABLE Friend presence unavailable")); + assertThat(responses).noneMatch(response -> response.contains("Friends " + filter + ":")); + } + assertThat(socialStub().lastFriendsRequest()).isEmpty(); } @Test @@ -312,17 +303,76 @@ void freshGameplayBaselineReappliesConfiguredFriendPresenceBaseline() throws Exc sessionId = prepareGameInstance(); List responses = runCommunicationSequence( - sessionId, - "FRIENDS", - "Sora [acct #" + SORA_ACCOUNT_ID + "] - online in Demo World / Live Realm (idle)"); + sessionId, "FRIENDS", "Sora [acct #" + SORA_ACCOUNT_ID + "] - online (idle)"); assertThat(responses) .anyMatch( - response -> - response.contains( - "Sora [acct #" - + SORA_ACCOUNT_ID - + "] - online in Demo World / Live Realm (idle)")); + response -> response.contains("Sora [acct #" + SORA_ACCOUNT_ID + "] - online (idle)")); + } + + @Test + void websocketFriendsMissingPolicyRedactsPresenceWithoutDisconnecting() throws Exception { + ensureTestServicesStarted(); + long sessionId = prepareGameInstance(); + FriendPresenceEntry missingPolicyPresence = + FriendPresenceEntry.newBuilder() + .setFriendAccountId(Long.toString(SORA_ACCOUNT_ID)) + .setOnline(true) + .setCharacterId(ChatTestFixtures.PLAYER_SORA) + .setCharacterName("Sora") + .setPlayableStateScope( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED) + .setWorldSlug("demo") + .setWorldDisplayName("Demo World") + .setRealmSlug("production") + .setRealmDisplayName("Live Realm") + .setActivityState(FriendPresenceActivityState.FRIEND_PRESENCE_ACTIVITY_STATE_AUTO_AFK) + .build(); + socialStub().setFriendPresenceEntries(List.of(missingPolicyPresence)); + + try (GameplayWebSocketDriver client = + openFirstPartyGameplayClient("friends-missing-policy-first-party")) { + int baseline = client.responses().size(); + client.send("FRIENDS"); + JsonNode friends = awaitStructuredCommand(client, baseline, "FRIENDS"); + JsonNode friendsPayload = requirePayload(friends, "friends_view"); + assertThat(friendsPayload.path("friends")).hasSize(1); + JsonNode entry = friendsPayload.path("friends").get(0); + assertThat(entry.path("friendAccountId").asLong()).isEqualTo(SORA_ACCOUNT_ID); + assertThat(entry.path("displayName").asText()).isEqualTo("Friend #" + SORA_ACCOUNT_ID); + for (String field : + List.of( + "online", + "worldSlug", + "worldDisplayName", + "realmSlug", + "realmDisplayName", + "characterName", + "playableStateScope", + "pointerVersion", + "activityState", + "lastSeenAtEpochMs", + "recentDisposition", + "visibilityPolicy")) { + assertThat(entry.has(field)).as("redacted field %s", field).isFalse(); + } + } + + sessionId = prepareGameInstance(); + socialStub().setFriendPresenceEntries(List.of(missingPolicyPresence)); + try (GameplayWebSocketDriver client = + openReadySessionClient(sessionId, "friends-missing-policy-detail")) { + int baseline = client.responses().size(); + client.send("FRIENDS SHOW #1"); + client.awaitContains("Presence: presence unavailable"); + assertThat(client.responses().subList(baseline, client.responses().size())) + .noneMatch( + response -> + response.contains("Sora") + || response.contains("Demo World") + || response.contains("Live Realm")); + } } @Test @@ -400,10 +450,20 @@ void websocketFriendsShowUsesCanonicalFriendDetailSurface() throws Exception { try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-show-detail-conn")) { + int baseline = client.responses().size(); client.send("FRIENDS SHOW #1"); client.awaitContains("Friend Sora [acct #" + SORA_ACCOUNT_ID + "]"); - client.awaitContains("Presence: online in Demo World / Live Realm (idle)"); + client.awaitContains("Presence: online (idle)"); client.awaitContains("Roster entry: #1"); + assertThat(client.responses().subList(baseline, client.responses().size())) + .noneMatch( + response -> + response.contains("private-playtest") + || response.contains("Private Playtest World") + || response.contains("staff-preview") + || response.contains("Staff Preview Realm") + || response.contains("shared") + || response.contains("Pointer version")); } GameplaySocialAssertions.assertGetFriendByOrdinalRequest( @@ -421,11 +481,13 @@ void websocketFriendsSummaryUsesCanonicalRosterSummarySurface() throws Exception try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-summary-conn")) { client.send("FRIENDS SUMMARY"); - client.awaitContains("Friend roster summary:"); - client.awaitContains("Linked: 1"); - client.awaitContains("Online: 1"); - client.awaitContains("Offline: 0"); - client.awaitContains("Recent offline: 0"); + String summary = + client.awaitResponseMatching( + response -> response.contains("Friend roster summary:"), + "friend roster summary response"); + assertThat(summary) + .contains("Linked: 1") + .doesNotContain("Online:", "Offline:", "Recent offline:"); } GameplaySocialAssertions.assertFriendRosterSummaryRequest( @@ -499,10 +561,25 @@ void websocketFirstPartyFriendsViewsUseStructuredCanonicalPayloads() throws Exce JsonNode friendsPayload = requirePayload(friends, "friends_view"); assertThat(friends.path("accepted").asBoolean()).isTrue(); assertThat(friendsPayload.path("filter").asText()).isEqualTo("ALL"); - assertThat(friendsPayload.path("friends").get(0).path("friendAccountId").asLong()) - .isEqualTo(SORA_ACCOUNT_ID); - assertThat(friendsPayload.path("friends").get(0).path("playableStateScope").asText()) - .isEqualTo("SHARED"); + JsonNode friendEntry = friendsPayload.path("friends").get(0); + assertThat(friendEntry.path("friendAccountId").asLong()).isEqualTo(SORA_ACCOUNT_ID); + assertThat(friendEntry.path("online").asBoolean()).isTrue(); + assertThat(friendEntry.path("characterName").asText()).isEqualTo("Sora"); + assertThat(friendEntry.path("activityState").asText()).isEqualTo("AUTO_AFK"); + assertThat(friendEntry.path("visibilityPolicy").asText()).isEqualTo("FRIENDS_ONLY"); + for (String field : + List.of( + "worldSlug", + "worldDisplayName", + "realmSlug", + "realmDisplayName", + "playableStateScope", + "pointerVersion")) { + assertThat(friendEntry.has(field)).as("location evidence %s", field).isFalse(); + } + assertThat(friends.toString()) + .doesNotContain( + "private-playtest", "Private Playtest World", "staff-preview", "Staff Preview Realm"); baseline = client.responses().size(); client.send("FRIENDS SHOW #1"); @@ -511,14 +588,101 @@ void websocketFirstPartyFriendsViewsUseStructuredCanonicalPayloads() throws Exce assertThat(detailPayload.path("friend").path("ordinal").asInt()).isEqualTo(1); assertThat(detailPayload.path("friend").path("friendAccountId").asLong()) .isEqualTo(SORA_ACCOUNT_ID); + assertThat(detailPayload.path("friend").path("online").asBoolean()).isTrue(); + for (String field : + List.of( + "worldSlug", + "worldDisplayName", + "realmSlug", + "realmDisplayName", + "playableStateScope", + "pointerVersion")) { + assertThat(detailPayload.path("friend").has(field)) + .as("location evidence %s", field) + .isFalse(); + } + assertThat(detail.toString()) + .doesNotContain( + "private-playtest", "Private Playtest World", "staff-preview", "Staff Preview Realm"); baseline = client.responses().size(); client.send("FRIENDS SUMMARY"); JsonNode summary = awaitStructuredCommand(client, baseline, "FRIENDS"); JsonNode summaryPayload = requirePayload(summary, "friend_roster_summary_view"); assertThat(summaryPayload.path("totalCount").asInt()).isEqualTo(1); - assertThat(summaryPayload.path("onlineCount").asInt()).isEqualTo(1); - assertThat(summaryPayload.path("sharedCount").asInt()).isEqualTo(1); + assertThat(summaryPayload.fieldNames()).toIterable().containsExactly("totalCount"); + } + } + + @Test + void websocketFirstPartyFriendsPublicPresenceOmitsUndiscoverableLocationEvidence() + throws Exception { + ensureTestServicesStarted(); + prepareGameInstance(); + socialStub() + .setFriendPresenceEntries( + List.of( + FriendPresenceEntry.newBuilder() + .setFriendAccountId(Long.toString(SORA_ACCOUNT_ID)) + .setOnline(true) + .setCharacterId(ChatTestFixtures.PLAYER_SORA) + .setCharacterName("Sora") + .setWorldSlug("private-playtest") + .setWorldDisplayName("Private Playtest World") + .setRealmSlug("staff-preview") + .setRealmDisplayName("Staff Preview Realm") + .setPlayableStateScope( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED) + .setPointerVersion(947L) + .setActivityState( + FriendPresenceActivityState.FRIEND_PRESENCE_ACTIVITY_STATE_AUTO_AFK) + .setVisibilityPolicy( + FriendPresenceVisibilityPolicy.FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC) + .build())); + + try (GameplayWebSocketDriver client = + openFirstPartyGameplayClient("friends-public-private-location")) { + int baseline = client.responses().size(); + client.send("FRIENDS"); + JsonNode friends = awaitStructuredCommand(client, baseline, "FRIENDS"); + JsonNode entry = requirePayload(friends, "friends_view").path("friends").get(0); + assertThat(entry.path("online").asBoolean()).isTrue(); + assertThat(entry.path("characterName").asText()).isEqualTo("Sora"); + assertThat(entry.path("activityState").asText()).isEqualTo("AUTO_AFK"); + assertThat(entry.path("visibilityPolicy").asText()).isEqualTo("PUBLIC"); + for (String field : + List.of( + "worldSlug", + "worldDisplayName", + "realmSlug", + "realmDisplayName", + "playableStateScope", + "pointerVersion")) { + assertThat(entry.has(field)).as("location evidence %s", field).isFalse(); + } + assertThat(friends.toString()) + .doesNotContain( + "private-playtest", "Private Playtest World", "staff-preview", "Staff Preview Realm"); + + baseline = client.responses().size(); + client.send("FRIENDS SHOW #1"); + JsonNode detail = awaitStructuredCommand(client, baseline, "FRIENDS"); + JsonNode detailFriend = requirePayload(detail, "friend_detail_view").path("friend"); + assertThat(detailFriend.path("online").asBoolean()).isTrue(); + for (String field : + List.of( + "worldSlug", + "worldDisplayName", + "realmSlug", + "realmDisplayName", + "playableStateScope", + "pointerVersion")) { + assertThat(detailFriend.has(field)).as("location evidence %s", field).isFalse(); + } + assertThat(detail.toString()) + .doesNotContain( + "private-playtest", "Private Playtest World", "staff-preview", "Staff Preview Realm"); } } @@ -927,10 +1091,14 @@ private static synchronized void ensureTestServicesStarted() throws Exception { .setPlayableStateScope( net.firedevops.firemud.entitymanagement.v1.PlayableStateScope .PLAYABLE_STATE_SCOPE_SHARED) - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") + .setVisibilityPolicy( + FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_FRIENDS_ONLY) + .setWorldSlug("private-playtest") + .setWorldDisplayName("Private Playtest World") + .setRealmSlug("staff-preview") + .setRealmDisplayName("Staff Preview Realm") + .setPointerVersion(941L) .setActivityState( FriendPresenceActivityState .FRIEND_PRESENCE_ACTIVITY_STATE_AUTO_AFK) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java index c7dd4a3e8f..d5ba783c12 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java @@ -21,6 +21,7 @@ import net.firedevops.firemud.socialgroups.v1.AddFriendResponse; import net.firedevops.firemud.socialgroups.v1.FriendPresenceActivityState; import net.firedevops.firemud.socialgroups.v1.FriendPresenceEntry; +import net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy; import net.firedevops.firemud.socialgroups.v1.FriendRecentPresenceDisposition; import net.firedevops.firemud.socialgroups.v1.FriendRosterEntry; import net.firedevops.firemud.socialgroups.v1.FriendRosterFilter; @@ -82,10 +83,16 @@ void friendsMapsVisiblePresenceToTypedViewAndText() { .setOnline(true) .setCharacterId("99") .setCharacterName("Sora") - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") + .setWorldSlug("private-playtest") + .setWorldDisplayName("Private Playtest World") + .setRealmSlug("staff-preview") + .setRealmDisplayName("Staff Preview Realm") + .setPlayableStateScope( + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setPointerVersion(29L) + .setVisibilityPolicy( + FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC) .setActivityState( FriendPresenceActivityState .FRIEND_PRESENCE_ACTIVITY_STATE_AUTO_AFK) @@ -107,7 +114,6 @@ void friendsMapsVisiblePresenceToTypedViewAndText() { (FriendPresenceViewOutput) result.outputs().getFirst().payload(); assertThat(view.filter()).isEqualTo("ALL"); assertThat(view.totalCount()).isEqualTo(1); - assertThat(view.matchCount()).isEqualTo(1); assertThat(view.friends()) .singleElement() .satisfies( @@ -117,13 +123,27 @@ void friendsMapsVisiblePresenceToTypedViewAndText() { assertThat(entry.status()).isEqualTo("active"); assertThat(entry.linkedAtEpochMs()).isNull(); assertThat(entry.displayName()).isEqualTo("Sora"); + assertThat(entry.online()).isTrue(); + assertThat(entry.worldSlug()).isNull(); + assertThat(entry.worldDisplayName()).isNull(); + assertThat(entry.realmSlug()).isNull(); + assertThat(entry.realmDisplayName()).isNull(); + assertThat(entry.playableStateScope()).isNull(); + assertThat(entry.pointerVersion()).isNull(); assertThat(entry.activityState()).isEqualTo("AUTO_AFK"); }); assertThat( new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) - .contains("Sora [acct #77] - online in Demo World / Live Realm (idle)"); + .contains("Sora [acct #77] - online (idle)") + .doesNotContain( + "private-playtest", + "Private Playtest World", + "staff-preview", + "Staff Preview Realm", + "shared", + "Pointer version"); Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.any(), @@ -158,6 +178,9 @@ void friendsFallsBackToBoundedOfflineLabelWhenDetailsAreSuppressed() { .setRecentDisposition( FriendRecentPresenceDisposition .FRIEND_RECENT_PRESENCE_DISPOSITION_LOGOUT) + .setVisibilityPolicy( + FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC) .build()) .build()) .build()); @@ -179,8 +202,81 @@ void friendsFallsBackToBoundedOfflineLabelWhenDetailsAreSuppressed() { assertThat(entry.displayName()).isEqualTo("Friend #77"); assertThat(entry.lastSeenAtEpochMs()) .isEqualTo(Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()); - assertThat(entry.recentDisposition()).isEqualTo("LOGOUT"); }); + assertThat( + new TextPlayerOutputRenderer( + new net.firedevops.firemud.gamesession.config.PresentationProperties()) + .render(result.outputs().getFirst())) + .contains("last seen 2026-04-11T06:15:30Z") + .doesNotContain("logged out", "replaced session", "connection lost", "LOGOUT"); + } + + @Test + void friendsOnlyPresenceDoesNotExposeDisconnectDispositionInText() { + SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); + EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); + FriendsCommandHandler handler = + newHandler( + socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); + when(socialGroupsClient.listFriends(1L, 41L)) + .thenReturn( + ListFriendsResponse.newBuilder() + .addFriends( + FriendRosterEntry.newBuilder() + .setFriendAccountId("77") + .setPresence( + FriendPresenceEntry.newBuilder() + .setFriendAccountId("77") + .setOnline(false) + .setLastSeenAtMs( + Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()) + .setRecentDisposition( + FriendRecentPresenceDisposition + .FRIEND_RECENT_PRESENCE_DISPOSITION_TAKEOVER) + .setWorldSlug("private-playtest") + .setWorldDisplayName("Private Playtest World") + .setRealmSlug("staff-preview") + .setRealmDisplayName("Staff Preview Realm") + .setPlayableStateScope( + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) + .setPointerVersion(41L) + .setVisibilityPolicy( + FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_FRIENDS_ONLY) + .build()) + .build()) + .build()); + + TextCommandInterpretationResult result = + handler.handle( + new TextCommand(TextCommandType.FRIENDS, java.util.List.of(), "FRIENDS"), + GAMEPLAY_CONTEXT); + + assertThat( + new TextPlayerOutputRenderer( + new net.firedevops.firemud.gamesession.config.PresentationProperties()) + .render(result.outputs().getFirst())) + .contains("last seen 2026-04-11T06:15:30Z") + .doesNotContain( + "logged out", + "replaced session", + "connection lost", + "TAKEOVER", + "private-playtest", + "Private Playtest World", + "staff-preview", + "Staff Preview Realm", + "isolated", + "Pointer version"); + FriendPresenceViewOutput.Entry entry = + ((FriendPresenceViewOutput) result.outputs().getFirst().payload()).friends().getFirst(); + assertThat(entry.online()).isFalse(); + assertThat(entry.worldSlug()).isNull(); + assertThat(entry.worldDisplayName()).isNull(); + assertThat(entry.realmSlug()).isNull(); + assertThat(entry.realmDisplayName()).isNull(); + assertThat(entry.playableStateScope()).isNull(); + assertThat(entry.pointerVersion()).isNull(); } @Test @@ -244,6 +340,9 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { .setFriendAccountId("77") .setOnline(true) .setCharacterName("Sora") + .setVisibilityPolicy( + FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC) .build()) .build()) .build()); @@ -257,7 +356,6 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { (FriendPresenceViewOutput) result.outputs().getFirst().payload(); assertThat(view.filter()).isEqualTo("ONLINE"); assertThat(view.totalCount()).isEqualTo(2); - assertThat(view.matchCount()).isEqualTo(1); assertThat(view.friends()) .singleElement() .satisfies(entry -> assertThat(entry.ordinal()).isEqualTo(1)); @@ -265,122 +363,158 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) - .contains("Friends ONLINE [1/2]:") + .contains("Friends ONLINE:\n") .contains("1) Sora [acct #77] - online"); Mockito.verify(socialGroupsClient) .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); } @Test - void friendsPrivateFiltersCanonicalRosterByVisibilityPolicy() { + void friendsOnlineWithNoMatchesKeepsRosterTotalOutOfPlayerText() { SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE)) + when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE)) .thenReturn( ListFriendsResponse.newBuilder() - .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE) + .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE) .setTotalCount(2) - .setMatchCount(1) - .addFriends( - FriendRosterEntry.newBuilder() - .setOrdinal(2) - .setFriendAccountId("88") - .setPresence( - FriendPresenceEntry.newBuilder() - .setFriendAccountId("88") - .setOnline(false) - .setVisibilityPolicy( - net.firedevops.firemud.socialgroups.v1 - .FriendPresenceVisibilityPolicy - .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE) - .build()) - .build()) + .setMatchCount(0) .build()); TextCommandInterpretationResult result = handler.handle( - new TextCommand( - TextCommandType.FRIENDS, java.util.List.of("PRIVATE"), "FRIENDS PRIVATE"), + new TextCommand(TextCommandType.FRIENDS, java.util.List.of("ONLINE"), "FRIENDS ONLINE"), GAMEPLAY_CONTEXT); + assertThat(result.commandResult().accepted()).isTrue(); FriendPresenceViewOutput view = (FriendPresenceViewOutput) result.outputs().getFirst().payload(); - assertThat(view.filter()).isEqualTo("PRIVATE"); + assertThat(view.filter()).isEqualTo("ONLINE"); assertThat(view.totalCount()).isEqualTo(2); - assertThat(view.matchCount()).isEqualTo(1); - assertThat(view.friends()) - .singleElement() - .satisfies( - entry -> { - assertThat(entry.ordinal()).isEqualTo(2); - assertThat(entry.friendAccountId()).isEqualTo(88L); - assertThat(entry.visibilityPolicy()).isEqualTo("PRIVATE"); - }); + assertThat(view.friends()).isEmpty(); assertThat( new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) - .contains("Friends PRIVATE [1/2]:"); + .contains("Friends ONLINE: no matching friends.") + .doesNotContain("[0/2]", "[0/0]"); Mockito.verify(socialGroupsClient) - .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE); + .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); + } + + @Test + void friendsRedactionSelectingFiltersFailClosedWithoutSocialQuery() { + SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); + EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); + FriendsCommandHandler handler = + newHandler( + socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); + for (String filter : + java.util.List.of( + "OFFLINE", + "PUBLIC", + "FRIENDS_ONLY", + "PRIVATE", + "SHARED", + "ISOLATED", + "UNSPECIFIED_SCOPE")) { + TextCommandInterpretationResult result = + handler.handle( + new TextCommand( + TextCommandType.FRIENDS, java.util.List.of(filter), "FRIENDS " + filter), + GAMEPLAY_CONTEXT); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("FRIEND_PRESENCE_UNAVAILABLE"); + assertThat(result.outputs()) + .singleElement() + .extracting(PlayerOutput::text) + .isEqualTo("ERROR FRIEND_PRESENCE_UNAVAILABLE Friend presence unavailable"); + } + Mockito.verifyNoInteractions(socialGroupsClient); } @Test - void friendsSharedFiltersCanonicalRosterByPlayableStateScope() { + void friendsRedactsLegacyHiddenStaffEntryButPreservesRelationshipRow() { SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED)) + when(socialGroupsClient.listFriends(1L, 41L)) .thenReturn( ListFriendsResponse.newBuilder() - .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED) - .setTotalCount(2) - .setMatchCount(1) .addFriends( FriendRosterEntry.newBuilder() - .setOrdinal(1) + .setOrdinal(4) + .setFriendLinkId("12") .setFriendAccountId("77") + .setStatus("active") + .setCreatedAtMs(1_744_336_000_000L) .setPresence( FriendPresenceEntry.newBuilder() .setFriendAccountId("77") .setOnline(true) + .setCharacterId("99") .setCharacterName("Sora") + .setWorldSlug("demo") + .setWorldDisplayName("Demo World") + .setRealmSlug("production") + .setRealmDisplayName("Live Realm") .setPlayableStateScope( PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setPointerVersion(17L) + .setActivityState( + FriendPresenceActivityState + .FRIEND_PRESENCE_ACTIVITY_STATE_ACTIVE) + .setLastSeenAtMs(1_744_336_000_000L) + .setRecentDisposition( + FriendRecentPresenceDisposition + .FRIEND_RECENT_PRESENCE_DISPOSITION_LOGOUT) + .setVisibilityPolicy( + net.firedevops.firemud.socialgroups.v1 + .FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_HIDDEN_STAFF) .build()) .build()) .build()); TextCommandInterpretationResult result = handler.handle( - new TextCommand(TextCommandType.FRIENDS, java.util.List.of("SHARED"), "FRIENDS SHARED"), + new TextCommand(TextCommandType.FRIENDS, java.util.List.of(), "FRIENDS"), GAMEPLAY_CONTEXT); - FriendPresenceViewOutput view = - (FriendPresenceViewOutput) result.outputs().getFirst().payload(); - assertThat(view.filter()).isEqualTo("SHARED"); - assertThat(view.totalCount()).isEqualTo(2); - assertThat(view.matchCount()).isEqualTo(1); - assertThat(view.friends()) - .singleElement() - .satisfies( - entry -> { - assertThat(entry.ordinal()).isEqualTo(1); - assertThat(entry.friendAccountId()).isEqualTo(77L); - assertThat(entry.playableStateScope()).isEqualTo("SHARED"); - }); + FriendPresenceViewOutput.Entry entry = + ((FriendPresenceViewOutput) result.outputs().getFirst().payload()).friends().getFirst(); + assertThat(entry.ordinal()).isEqualTo(4); + assertThat(entry.friendLinkId()).isEqualTo(12L); + assertThat(entry.friendAccountId()).isEqualTo(77L); + assertThat(entry.status()).isEqualTo("active"); + assertThat(entry.linkedAtEpochMs()).isEqualTo(1_744_336_000_000L); + assertThat(entry.displayName()).isEqualTo("Friend #77"); + assertThat(entry.online()).isNull(); + assertThat(entry.worldSlug()).isNull(); + assertThat(entry.worldDisplayName()).isNull(); + assertThat(entry.realmSlug()).isNull(); + assertThat(entry.realmDisplayName()).isNull(); + assertThat(entry.characterName()).isNull(); + assertThat(entry.playableStateScope()).isNull(); + assertThat(entry.pointerVersion()).isNull(); + assertThat(entry.activityState()).isNull(); + assertThat(entry.lastSeenAtEpochMs()).isNull(); + assertThat(entry.visibilityPolicy()).isNull(); assertThat( new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) - .contains("Friends SHARED [1/2]:"); - Mockito.verify(socialGroupsClient) - .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED); + .contains("Friend #77") + .contains("presence unavailable") + .doesNotContain("Sora") + .doesNotContain("Demo World") + .doesNotContain("HIDDEN_STAFF"); } @Test @@ -406,6 +540,9 @@ void friendsRecentFiltersOfflineEntriesWithRecentPresence() { .setOnline(false) .setLastSeenAtMs( Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()) + .setVisibilityPolicy( + FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC) .build()) .build()) .build()); @@ -419,7 +556,6 @@ void friendsRecentFiltersOfflineEntriesWithRecentPresence() { (FriendPresenceViewOutput) result.outputs().getFirst().payload(); assertThat(view.filter()).isEqualTo("RECENT"); assertThat(view.totalCount()).isEqualTo(2); - assertThat(view.matchCount()).isEqualTo(1); assertThat(view.friends()) .singleElement() .satisfies(entry -> assertThat(entry.friendAccountId()).isEqualTo(77L)); @@ -444,8 +580,8 @@ void friendsSummaryUsesCanonicalRosterSummarySurface() { .setPublicCount(1) .setFriendsOnlyCount(2) .setPrivateCount(1) - .setHiddenStaffCount(0) - .setUnspecifiedVisibilityCount(0) + .setHiddenStaffCount(2) + .setUnspecifiedVisibilityCount(2) .setSharedCount(2) .setIsolatedCount(1) .setUnspecifiedScopeCount(1) @@ -466,31 +602,17 @@ void friendsSummaryUsesCanonicalRosterSummarySurface() { FriendRosterSummaryViewOutput view = (FriendRosterSummaryViewOutput) result.outputs().getFirst().payload(); assertThat(view.totalCount()).isEqualTo(4); - assertThat(view.onlineCount()).isEqualTo(1); - assertThat(view.offlineCount()).isEqualTo(3); - assertThat(view.recentCount()).isEqualTo(2); - assertThat(view.publicCount()).isEqualTo(1); - assertThat(view.friendsOnlyCount()).isEqualTo(2); - assertThat(view.privateCount()).isEqualTo(1); - assertThat(view.hiddenStaffCount()).isZero(); - assertThat(view.unspecifiedVisibilityCount()).isZero(); - assertThat(view.sharedCount()).isEqualTo(2); - assertThat(view.isolatedCount()).isEqualTo(1); - assertThat(view.unspecifiedScopeCount()).isEqualTo(1); assertThat( new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) .contains("Friend roster summary:") .contains("Linked: 4") - .contains("Online: 1") - .contains("Offline: 3") - .contains("Recent offline: 2") - .contains("Visibility public: 1") - .contains("Visibility friends-only: 2") - .contains("Visibility private: 1") - .contains("Scope shared: 2") - .contains("Scope isolated: 1"); + .doesNotContain("Online:") + .doesNotContain("Offline:") + .doesNotContain("Recent offline:") + .doesNotContain("Visibility") + .doesNotContain("Scope"); Mockito.verify(socialGroupsClient).getFriendRosterSummary(1L, 41L); } @@ -625,6 +747,9 @@ void friendsRemoveByOrdinalUsesCanonicalRemoveSurface() { FriendPresenceEntry.newBuilder() .setFriendAccountId("77") .setCharacterName("Sora") + .setVisibilityPolicy( + FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC) .build()) .build()) .build()); @@ -707,11 +832,16 @@ void friendsShowReturnsCanonicalFriendDetailView() { .setFriendAccountId("77") .setOnline(true) .setCharacterName("Sora") - .setWorldDisplayName("Demo World") - .setRealmDisplayName("Live Realm") + .setWorldSlug("private-playtest") + .setWorldDisplayName("Private Playtest World") + .setRealmSlug("staff-preview") + .setRealmDisplayName("Staff Preview Realm") .setPlayableStateScope( PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .setPointerVersion(17L) + .setPointerVersion(53L) + .setVisibilityPolicy( + FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC) .setActivityState( FriendPresenceActivityState .FRIEND_PRESENCE_ACTIVITY_STATE_AUTO_AFK) @@ -734,20 +864,32 @@ void friendsShowReturnsCanonicalFriendDetailView() { assertThat(detail.friend().friendAccountId()).isEqualTo(77L); assertThat(detail.friend().friendLinkId()).isEqualTo(11L); assertThat(detail.friend().characterName()).isEqualTo("Sora"); - assertThat(detail.friend().playableStateScope()).isEqualTo("SHARED"); - assertThat(detail.friend().pointerVersion()).isEqualTo(17L); + assertThat(detail.friend().online()).isTrue(); + assertThat(detail.friend().worldSlug()).isNull(); + assertThat(detail.friend().worldDisplayName()).isNull(); + assertThat(detail.friend().realmSlug()).isNull(); + assertThat(detail.friend().realmDisplayName()).isNull(); + assertThat(detail.friend().playableStateScope()).isNull(); + assertThat(detail.friend().pointerVersion()).isNull(); + assertThat(detail.friend().activityState()).isEqualTo("AUTO_AFK"); assertThat( new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) .contains("Friend Sora [acct #77]") - .contains("Presence: online in Demo World / Live Realm (idle)") - .contains("State scope: shared") - .contains("Pointer version: 17"); + .contains("Presence: online (idle)") + .contains("Character: Sora") + .doesNotContain( + "private-playtest", + "Private Playtest World", + "staff-preview", + "Staff Preview Realm", + "State scope", + "Pointer version"); } @Test - void friendsShowByOrdinalUsesCanonicalDetailSurface() { + void friendsShowByOrdinalRedactsMissingPolicyAndRendersDetail() { SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); FriendsCommandHandler handler = @@ -763,7 +905,12 @@ void friendsShowByOrdinalUsesCanonicalDetailSurface() { .setPresence( FriendPresenceEntry.newBuilder() .setFriendAccountId("77") + .setOnline(true) .setCharacterName("Sora") + .setWorldDisplayName("Demo World") + .setActivityState( + FriendPresenceActivityState + .FRIEND_PRESENCE_ACTIVITY_STATE_AUTO_AFK) .build()) .build()) .build()); @@ -777,6 +924,18 @@ void friendsShowByOrdinalUsesCanonicalDetailSurface() { assertThat(result.commandResult().accepted()).isTrue(); FriendDetailViewOutput detail = (FriendDetailViewOutput) result.outputs().getFirst().payload(); assertThat(detail.friend().ordinal()).isEqualTo(1); + assertThat(detail.friend().displayName()).isEqualTo("Friend #77"); + assertThat(detail.friend().online()).isNull(); + assertThat(detail.friend().characterName()).isNull(); + assertThat(detail.friend().worldDisplayName()).isNull(); + assertThat(detail.friend().activityState()).isNull(); + assertThat( + new TextPlayerOutputRenderer( + new net.firedevops.firemud.gamesession.config.PresentationProperties()) + .render(result.outputs().getFirst())) + .contains("Presence: presence unavailable") + .contains("Roster entry: #1") + .doesNotContain("Sora", "Demo World", "online", "idle"); Mockito.verify(socialGroupsClient).getFriendByOrdinal(1L, 41L, 1); } @@ -1005,6 +1164,7 @@ void friendsVisibilityShowsCurrentCanonicalPolicy() { FriendPresencePolicyViewOutput view = (FriendPresencePolicyViewOutput) result.outputs().getFirst().payload(); assertThat(view.currentPolicy()).isEqualTo("FRIENDS_ONLY"); + assertThat(view.options()).noneMatch(option -> option.policy().equals("HIDDEN_STAFF")); assertThat(view.options()) .anySatisfy( option -> { @@ -1166,8 +1326,8 @@ void friendsVisibilityRejectsReservedHiddenStaffPolicy() { assertThat(result.outputs()) .singleElement() .extracting(PlayerOutput::text) - .isEqualTo( - "ERROR INVALID_ARGUMENT HIDDEN_STAFF is reserved and cannot be set from gameplay"); + .isEqualTo("ERROR INVALID_ARGUMENT FRIENDS VISIBILITY "); + assertThat(result.outputs().getFirst().text()).doesNotContain("HIDDEN_STAFF"); Mockito.verify(socialGroupsClient, Mockito.never()) .updateFriendPresencePolicy(Mockito.anyLong(), Mockito.anyLong(), Mockito.any()); } @@ -1191,24 +1351,40 @@ void friendsUnknownSubcommandFailsClosedWithUsage() { .singleElement() .extracting(PlayerOutput::text) .isEqualTo( - "ERROR INVALID_ARGUMENT FRIENDS [ADD|REMOVE|SHOW|SUMMARY|VISIBILITY|ONLINE|OFFLINE|RECENT|PUBLIC|FRIENDS_ONLY|PRIVATE|HIDDEN_STAFF|UNSPECIFIED_VISIBILITY|SHARED|ISOLATED|UNSPECIFIED_SCOPE]"); + "ERROR INVALID_ARGUMENT FRIENDS [ADD|REMOVE|SHOW|SUMMARY|VISIBILITY|ONLINE|RECENT|SHARED|ISOLATED]"); Mockito.verifyNoInteractions(socialGroupsClient); } @Test - void friendsUnspecifiedVisibilityUsesCanonicalFilterAlias() { + void friendsDoesNotAcceptLegacyHiddenStaffFilter() { SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends( - 1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_UNSPECIFIED_VISIBILITY)) - .thenReturn( - ListFriendsResponse.newBuilder() - .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_UNSPECIFIED_VISIBILITY) - .build()); + TextCommandInterpretationResult result = + handler.handle( + new TextCommand( + TextCommandType.FRIENDS, java.util.List.of("HIDDEN_STAFF"), "FRIENDS HIDDEN_STAFF"), + GAMEPLAY_CONTEXT); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.outputs().getFirst().text()) + .isEqualTo( + "ERROR INVALID_ARGUMENT FRIENDS [ADD|REMOVE|SHOW|SUMMARY|VISIBILITY|ONLINE|RECENT|SHARED|ISOLATED]") + .doesNotContain("HIDDEN_STAFF"); + Mockito.verifyNoInteractions(socialGroupsClient); + } + + @Test + void friendsDoesNotAcceptUnspecifiedVisibilityFilter() { + SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); + EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); + FriendsCommandHandler handler = + newHandler( + socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); TextCommandInterpretationResult result = handler.handle( new TextCommand( @@ -1217,11 +1393,12 @@ void friendsUnspecifiedVisibilityUsesCanonicalFilterAlias() { "FRIENDS UNSPECIFIED_VISIBILITY"), GAMEPLAY_CONTEXT); - assertThat(result.commandResult().accepted()).isTrue(); - FriendPresenceViewOutput view = - (FriendPresenceViewOutput) result.outputs().getFirst().payload(); - assertThat(view.filter()).isEqualTo("UNSPECIFIED_VISIBILITY"); - Mockito.verify(socialGroupsClient) - .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_UNSPECIFIED_VISIBILITY); + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.outputs().getFirst().text()) + .isEqualTo( + "ERROR INVALID_ARGUMENT FRIENDS [ADD|REMOVE|SHOW|SUMMARY|VISIBILITY|ONLINE|RECENT|SHARED|ISOLATED]") + .doesNotContain("UNSPECIFIED_VISIBILITY"); + Mockito.verifyNoInteractions(socialGroupsClient); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java index 710a4c6190..229823da75 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java @@ -128,9 +128,30 @@ void helpFriendsTopicExplainsVisibilityReadAndWriteSurface() { .text() .contains( "FRIENDS VISIBILITY shows your current cross-game friend-presence policy, and FRIENDS VISIBILITY updates it.")); - assertTrue(result.outputs().get(0).text().contains("FRIENDS UNSPECIFIED_VISIBILITY")); - assertTrue(result.outputs().get(0).text().contains("FRIENDS UNSPECIFIED_SCOPE")); + assertFalse(result.outputs().get(0).text().contains("FRIENDS UNSPECIFIED_VISIBILITY")); + assertFalse(result.outputs().get(0).text().contains("FRIENDS OFFLINE")); + assertFalse(result.outputs().get(0).text().contains("FRIENDS PUBLIC")); + assertFalse(result.outputs().get(0).text().contains("FRIENDS FRIENDS_ONLY")); + assertFalse(result.outputs().get(0).text().contains("FRIENDS PRIVATE")); + assertFalse(result.outputs().get(0).text().contains("FRIENDS UNSPECIFIED_SCOPE")); + assertTrue( + result + .outputs() + .get(0) + .text() + .contains( + "SHARED and ISOLATED filters are currently unavailable until Social provides viewer-bound location discovery.")); + assertFalse( + result.outputs().get(0).text().contains("FRIENDS SHARED, and FRIENDS ISOLATED filter")); + assertTrue( + result + .outputs() + .get(0) + .text() + .contains("Player output currently withholds world/realm labels")); assertTrue(result.outputs().get(0).text().contains("#entryNumber removal")); + assertFalse(result.outputs().get(0).text().contains("HIDDEN_STAFF")); + assertFalse(result.outputs().get(0).text().contains("hidden-staff")); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java index 4fd751582f..b71afb5e05 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java @@ -86,6 +86,33 @@ void whoKeepsTenantRoleClaimsInThePlayerListWithoutGrantEvidence() { assertThat(render(result)).isEqualTo("Gods [0]: \nPlayers [4]: Aster, Ben, Cara, Dara"); } + @Test + void whoShowsGlobalOnlyRolesAsPlayers() { + FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); + WhoCommandHandler handler = + new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); + String globalOnlyJwt = + jwtUtil.generateToken( + "1", + java.util.Map.of( + "accountId", + "1", + "globalRoles", + java.util.List.of("platformAdmin", "support", "billingAdmin", "god", "moderator"))); + + gameplayPresenceService.registerConnected( + new SessionContext( + 1L, 22L, 1L, "staff@example.com", 101L, "Aster", 7L, "R-1", globalOnlyJwt)); + + TextCommandInterpretationResult result = + handler.handle( + new TextCommand(TextCommandType.WHO, java.util.List.of(), "WHO"), + new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + + assertThat(result.commandResult().accepted()).isTrue(); + assertThat(render(result)).isEqualTo("Gods [0]: \nPlayers [1]: Aster"); + } + @Test void whoOmitsRemovedPresenceAfterLogoutLikeCleanup() { FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java index 3f7ad970cd..536625bd11 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java @@ -1160,7 +1160,6 @@ void renderSuccessfulForOutputFormatsFriendDetailWithFriendsEnvelope() { 1L, "ACTIVE", null, - "FRIEND", "SHARED"))), "en-NZ", new PresentationProperties( @@ -1185,6 +1184,91 @@ void renderSuccessfulForOutputFormatsFriendDetailWithFriendsEnvelope() { + "Roster entry: #1\n\n"); } + @Test + void rendersFilteredOnlineFriendsWithoutAggregateCounts() { + TextPlayerOutputRenderer renderer = + new TextPlayerOutputRenderer( + new PresentationProperties( + "en-NZ", + PresentationProperties.ColorMode.NONE, + false, + new PresentationProperties.Prompt(false, true, 150L))); + + String rendered = + renderer.render( + PlayerOutput.view( + new FriendPresenceViewOutput( + "ONLINE", + 2, + List.of( + new FriendPresenceViewOutput.Entry( + 1, null, 77L, "active", null, "Sora", true, null, null, null, null, + null, null, null, null, null, "PUBLIC"))))); + + assertThat(rendered) + .contains("Friends ONLINE:\n", "1) Sora [acct #77] - online") + .doesNotContain("[1/2]", "[0/2]"); + } + + @Test + void rendersEmptyFilteredOnlineFriendsWithoutAggregateCounts() { + TextPlayerOutputRenderer renderer = + new TextPlayerOutputRenderer( + new PresentationProperties( + "en-NZ", + PresentationProperties.ColorMode.NONE, + false, + new PresentationProperties.Prompt(false, true, 150L))); + + String rendered = + renderer.render(PlayerOutput.view(new FriendPresenceViewOutput("ONLINE", 2, List.of()))); + + assertThat(rendered) + .contains("Friends ONLINE: no matching friends.") + .doesNotContain("[0/2]", "[0/0]"); + } + + @Test + void rendersGenericLastSeenWithoutDisconnectDisposition() { + TextPlayerOutputRenderer renderer = + new TextPlayerOutputRenderer( + new PresentationProperties( + "en-NZ", + PresentationProperties.ColorMode.NONE, + false, + new PresentationProperties.Prompt(false, true, 150L))); + + String rendered = + renderer.render( + PlayerOutput.view( + new FriendPresenceViewOutput( + "ALL", + 1, + List.of( + new FriendPresenceViewOutput.Entry( + 1, + null, + 77L, + "active", + null, + "Sora", + false, + null, + null, + null, + null, + null, + null, + null, + null, + 1_744_336_000_000L, + "FRIENDS_ONLY"))))); + + assertThat(rendered) + .contains("last seen ") + .doesNotContain("logged out", "replaced session", "connection lost", "LOGOUT"); + } + @Test void renderSuccessfulForOutputFormatsQuickLookWithQuickLookEnvelope() { TextPlayerOutputRenderer renderer = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java index c115235856..730ef45c72 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java @@ -91,7 +91,7 @@ void registerConnectedDoesNotElevateTenantRoleClaimsWithoutGrantEvidence() { "accountId", "102", "scopedRoles", - Map.of("22", List.of("tenantAdmin", "moderator")))); + Map.of("22", List.of("tenantAdmin", "moderator", "god")))); SessionContext context = new SessionContext( 1L, 22L, 102L, "player@example.com", 202L, "Ben", 7L, "R-1", tenantAdminJwt); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java index 0646e3b7fd..568f75a2b2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java @@ -38,6 +38,8 @@ import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.web.socket.WebSocketSession; class WebSocketOutputProjectorTest { @@ -344,7 +346,6 @@ void genericWebSocketProjectsFriendViewThroughFriendsRenderer() { 1L, "ACTIVE", null, - "FRIEND", "SHARED"))); when(renderer.renderSuccessfulForOutput(output, "en-NZ", presentation)) .thenReturn("OK FRIENDS\nFriend: Sora\n\n"); @@ -474,72 +475,49 @@ void firstPartyWebProjectsWhoViewPayloads() throws Exception { .isEqualTo("EXPLICIT_AFK"); } - @Test - void firstPartyWebProjectsFriendsViewPayloads() throws Exception { + @ParameterizedTest + @ValueSource(strings = {"ALL", "ONLINE"}) + void firstPartyWebProjectsFriendsViewPayloads(String filter) throws Exception { WebSocketSession session = mock(WebSocketSession.class); when(session.getAttributes()) .thenReturn( Map.of( GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); + List arguments = "ALL".equals(filter) ? List.of() : List.of(filter); + String commandText = "ALL".equals(filter) ? "FRIENDS" : "FRIENDS " + filter; + int totalCount = "ALL".equals(filter) ? 1 : 2; + PlayerOutput friendOutput = + PlayerOutput.view( + new FriendPresenceViewOutput( + filter, + totalCount, + List.of( + new FriendPresenceViewOutput.Entry( + 1, + 11L, + 3L, + "active", + 1_744_336_000_000L, + "Sora", + true, + "demo", + "Demo World", + "production", + "Live Realm", + "Sora", + "SHARED", + 17L, + "AUTO_AFK", + null, + null)))); String payload = projector.projectCommandResponse( session, - new TextCommand(TextCommandType.FRIENDS, List.of(), "FRIENDS"), + new TextCommand(TextCommandType.FRIENDS, arguments, commandText), new TextCommandInterpretationResult( - CommandEnqueueResult.success(), - List.of( - PlayerOutput.view( - new FriendPresenceViewOutput( - "ALL", - 1, - 1, - List.of( - new FriendPresenceViewOutput.Entry( - 1, - 11L, - 3L, - "active", - 1_744_336_000_000L, - "Sora", - true, - "demo", - "Demo World", - "production", - "Live Realm", - "Sora", - "SHARED", - 17L, - "AUTO_AFK", - null, - null, - null)))))), - List.of( - PlayerOutput.view( - new FriendPresenceViewOutput( - "ALL", - 1, - 1, - List.of( - new FriendPresenceViewOutput.Entry( - 1, - 11L, - 3L, - "active", - 1_744_336_000_000L, - "Sora", - true, - "demo", - "Demo World", - "production", - "Live Realm", - "Sora", - "SHARED", - 17L, - "AUTO_AFK", - null, - null, - null))))), + CommandEnqueueResult.success(), List.of(friendOutput)), + List.of(friendOutput), "en-NZ", presentation); @@ -547,8 +525,10 @@ void firstPartyWebProjectsFriendsViewPayloads() throws Exception { assertThat(json.path("outputs")).hasSize(1); assertThat(json.path("outputs").get(0).path("payloadType").asText()).isEqualTo("friends_view"); assertThat(json.path("outputs").get(0).path("payload").path("filter").asText()) - .isEqualTo("ALL"); - assertThat(json.path("outputs").get(0).path("payload").path("totalCount").asInt()).isEqualTo(1); + .isEqualTo(filter); + assertThat(json.path("outputs").get(0).path("payload").path("totalCount").asInt()) + .isEqualTo(totalCount); + assertThat(json.path("outputs").get(0).path("payload").has("matchCount")).isFalse(); assertThat( json.path("outputs") .get(0) @@ -605,6 +585,96 @@ void firstPartyWebProjectsFriendsViewPayloads() throws Exception { .isEqualTo(17L); } + @Test + void firstPartyWebProjectsEmptyOnlineFriendsWithoutAggregateCounts() throws Exception { + WebSocketSession session = mock(WebSocketSession.class); + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); + List outputs = + List.of(PlayerOutput.view(new FriendPresenceViewOutput("ONLINE", 2, List.of()))); + + String payload = + projector.projectCommandResponse( + session, + new TextCommand(TextCommandType.FRIENDS, List.of("ONLINE"), "FRIENDS ONLINE"), + new TextCommandInterpretationResult(CommandEnqueueResult.success(), outputs), + outputs, + "en-NZ", + presentation); + + JsonNode friendPayload = objectMapper.readTree(payload).path("outputs").get(0).path("payload"); + assertThat(friendPayload.path("filter").asText()).isEqualTo("ONLINE"); + assertThat(friendPayload.path("totalCount").asInt()).isEqualTo(2); + assertThat(friendPayload.path("friends")).hasSize(0); + assertThat(friendPayload.has("matchCount")).isFalse(); + } + + @Test + void firstPartyWebOmitsDisconnectDispositionForPublicAndFriendsOnlyPresence() throws Exception { + WebSocketSession session = mock(WebSocketSession.class); + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); + + String payload = + projector.projectPlayerOutput( + session, + PlayerOutput.view( + new FriendPresenceViewOutput( + "ALL", + 2, + List.of( + new FriendPresenceViewOutput.Entry( + 1, + 11L, + 3L, + "active", + null, + "Public Friend", + false, + null, + null, + null, + null, + null, + null, + null, + null, + 1_744_336_000_000L, + "PUBLIC"), + new FriendPresenceViewOutput.Entry( + 2, + 12L, + 4L, + "active", + null, + "Friends-only Friend", + false, + null, + null, + null, + null, + null, + null, + null, + null, + 1_744_336_000_000L, + "FRIENDS_ONLY")))), + "en-NZ", + presentation); + + JsonNode friends = + objectMapper.readTree(payload).path("outputs").get(0).path("payload").path("friends"); + assertThat(friends).hasSize(2); + assertThat(friends.get(0).path("visibilityPolicy").asText()).isEqualTo("PUBLIC"); + assertThat(friends.get(1).path("visibilityPolicy").asText()).isEqualTo("FRIENDS_ONLY"); + assertThat(friends.get(0).has("recentDisposition")).isFalse(); + assertThat(friends.get(1).has("recentDisposition")).isFalse(); + } + @Test void firstPartyWebProjectsFriendDetailViewPayloads() throws Exception { WebSocketSession session = mock(WebSocketSession.class); @@ -639,7 +709,6 @@ void firstPartyWebProjectsFriendDetailViewPayloads() throws Exception { 17L, "AUTO_AFK", null, - null, null))))), List.of( PlayerOutput.view( @@ -661,7 +730,6 @@ void firstPartyWebProjectsFriendDetailViewPayloads() throws Exception { 17L, "AUTO_AFK", null, - null, null)))), "en-NZ", presentation); @@ -696,6 +764,55 @@ void firstPartyWebProjectsFriendDetailViewPayloads() throws Exception { .isEqualTo(17L); } + @Test + void firstPartyWebOmitsRedactedFriendPresenceFields() throws Exception { + WebSocketSession session = mock(WebSocketSession.class); + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); + + FriendPresenceViewOutput.Entry redactedEntry = + new FriendPresenceViewOutput.Entry( + 4, + 12L, + 77L, + "active", + 1_744_336_000_000L, + "Friend #77", + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null); + String payload = + projector.projectPlayerOutput( + session, + PlayerOutput.view(new FriendDetailViewOutput(redactedEntry)), + "en-NZ", + presentation); + + JsonNode friend = + objectMapper.readTree(payload).path("outputs").get(0).path("payload").path("friend"); + assertThat(friend.path("friendAccountId").asLong()).isEqualTo(77L); + assertThat(friend.path("friendLinkId").asLong()).isEqualTo(12L); + assertThat(friend.path("status").asText()).isEqualTo("active"); + assertThat(friend.path("displayName").asText()).isEqualTo("Friend #77"); + assertThat(friend.has("online")).isFalse(); + assertThat(friend.has("worldSlug")).isFalse(); + assertThat(friend.has("characterName")).isFalse(); + assertThat(friend.has("activityState")).isFalse(); + assertThat(friend.has("lastSeenAtEpochMs")).isFalse(); + assertThat(friend.has("recentDisposition")).isFalse(); + assertThat(friend.has("visibilityPolicy")).isFalse(); + } + @Test void firstPartyWebProjectsFriendRosterSummaryViewPayloads() throws Exception { WebSocketSession session = mock(WebSocketSession.class); @@ -710,12 +827,8 @@ void firstPartyWebProjectsFriendRosterSummaryViewPayloads() throws Exception { new TextCommand(TextCommandType.FRIENDS, List.of("SUMMARY"), "FRIENDS SUMMARY"), new TextCommandInterpretationResult( CommandEnqueueResult.success(), - List.of( - PlayerOutput.view( - new FriendRosterSummaryViewOutput(4, 1, 3, 2, 1, 2, 1, 0, 0, 2, 1, 1)))), - List.of( - PlayerOutput.view( - new FriendRosterSummaryViewOutput(4, 1, 3, 2, 1, 2, 1, 0, 0, 2, 1, 1))), + List.of(PlayerOutput.view(new FriendRosterSummaryViewOutput(4)))), + List.of(PlayerOutput.view(new FriendRosterSummaryViewOutput(4))), "en-NZ", presentation); @@ -723,17 +836,9 @@ void firstPartyWebProjectsFriendRosterSummaryViewPayloads() throws Exception { assertThat(json.path("outputs")).hasSize(1); assertThat(json.path("outputs").get(0).path("payloadType").asText()) .isEqualTo("friend_roster_summary_view"); - assertThat(json.path("outputs").get(0).path("payload").path("totalCount").asInt()).isEqualTo(4); - assertThat(json.path("outputs").get(0).path("payload").path("recentCount").asInt()) - .isEqualTo(2); - assertThat(json.path("outputs").get(0).path("payload").path("friendsOnlyCount").asInt()) - .isEqualTo(2); - assertThat(json.path("outputs").get(0).path("payload").path("privateCount").asInt()) - .isEqualTo(1); - assertThat(json.path("outputs").get(0).path("payload").path("sharedCount").asInt()) - .isEqualTo(2); - assertThat(json.path("outputs").get(0).path("payload").path("isolatedCount").asInt()) - .isEqualTo(1); + JsonNode summary = json.path("outputs").get(0).path("payload"); + assertThat(summary.path("totalCount").asInt()).isEqualTo(4); + assertThat(summary.fieldNames()).toIterable().containsExactly("totalCount"); } @Test @@ -752,9 +857,7 @@ void firstPartyWebProjectsFriendPresencePolicyViewPayloads() throws Exception { "PUBLIC", "Normal bounded payload.", false, true), new FriendPresencePolicyViewOutput.Option( "FRIENDS_ONLY", "Approved friends only.", true, true), - new FriendPresencePolicyViewOutput.Option("PRIVATE", "Coarse only.", false, true), - new FriendPresencePolicyViewOutput.Option( - "HIDDEN_STAFF", "Reserved.", false, false))); + new FriendPresencePolicyViewOutput.Option("PRIVATE", "Coarse only.", false, true))); String payload = projector.projectCommandResponse( @@ -772,6 +875,8 @@ void firstPartyWebProjectsFriendPresencePolicyViewPayloads() throws Exception { .isEqualTo("friend_presence_policy_view"); assertThat(json.path("outputs").get(0).path("payload").path("currentPolicy").asText()) .isEqualTo("FRIENDS_ONLY"); + assertThat(json.path("outputs").get(0).path("payload").path("options")) + .allMatch(option -> !option.path("policy").asText().equals("HIDDEN_STAFF")); } @Test diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListener.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListener.java index a378b2b591..1c10aba33a 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListener.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListener.java @@ -1,22 +1,34 @@ package net.firedevops.firemud.springcloudgateway.config; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.netty.buffer.ByteBufAllocator; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; +import io.netty.handler.ssl.ApplicationProtocolNegotiator; import io.netty.handler.ssl.ClientAuth; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.util.concurrent.GlobalEventExecutor; import java.io.File; +import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.FileTime; import java.time.Duration; +import java.util.ArrayList; +import java.util.List; import java.util.Objects; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLSessionContext; +import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; import net.firedevops.firemud.springcloudgateway.filter.TcpProxyTrustPolicy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,9 +51,13 @@ public final class TcpProxyTlsListener implements SmartLifecycle { private final GatewayTcpProxyListenerProperties properties; private final TcpProxyTrustPolicy trustPolicy; private final HttpHandler httpHandler; + private final Object reloadMonitor = new Object(); + private final AtomicReference activeSslContext = new AtomicReference<>(); private volatile DisposableServer server; private volatile boolean running; private volatile ChannelGroup acceptedChannels; + private volatile TlsCertificateWatcher certificateWatcher; + private volatile boolean tlsMaterialReloadHealthy; private volatile ScheduledExecutorService expiryExecutor; private volatile ScheduledFuture expiryTask; @@ -69,18 +85,27 @@ public synchronized void start() { return; } try { + tlsMaterialReloadHealthy = false; String bindAddress = requiredBindAddress(properties.getBindAddress()); - SslContext sslContext = buildSslContext(); + synchronized (reloadMonitor) { + TlsCertificateWatcher watcher = + new TlsCertificateWatcher(watchedCredentialPaths(), this::reloadSslContext); + certificateWatcher = watcher; + watcher.start(); + activeSslContext.set(buildSslContext()); + tlsMaterialReloadHealthy = true; + } ChannelGroup channels = new DefaultChannelGroup("tcp-proxy-internal-tls", GlobalEventExecutor.INSTANCE, true); acceptedChannels = channels; ReactorHttpHandlerAdapter adapter = - new ReactorHttpHandlerAdapter(new InternalOnlyHttpHandler(httpHandler)); + new ReactorHttpHandlerAdapter( + new InternalOnlyHttpHandler(httpHandler, this::isTlsMaterialHealthy)); DisposableServer boundServer = HttpServer.create() .host(bindAddress) .port(properties.getPort()) - .secure(spec -> spec.sslContext(sslContext)) + .secure(spec -> spec.sslContext(new ReloadingSslContext(activeSslContext))) .doOnConnection(connection -> channels.add(connection.channel())) .handle(adapter) .bindNow(); @@ -140,16 +165,77 @@ private void scheduleProfileExpiry() { } private SslContext buildSslContext() throws Exception { - File certificate = requiredFile(properties.getCertificateChainPath(), "certificate chain"); - File privateKey = requiredFile(properties.getPrivateKeyPath(), "private key"); + CredentialSnapshot snapshot = + captureCredentialSnapshot( + configuredPath(properties.getCertificateChainPath(), "certificate chain"), + configuredPath(properties.getPrivateKeyPath(), "private key"), + trustPolicy.requiresClientCertificate() + ? configuredPath(properties.getTrustedClientCaPath(), "trusted client CA") + : null); + snapshot.requireConsistentCertificateKeyGeneration(); + File certificate = requiredFile(snapshot.certificate.readPath.toString(), "certificate chain"); + File privateKey = requiredFile(snapshot.privateKey.readPath.toString(), "private key"); SslContextBuilder builder = SslContextBuilder.forServer(certificate, privateKey); if (trustPolicy.requiresClientCertificate()) { - File clientCa = requiredFile(properties.getTrustedClientCaPath(), "trusted client CA"); + File clientCa = requiredFile(snapshot.clientCa.readPath.toString(), "trusted client CA"); builder.trustManager(clientCa).clientAuth(ClientAuth.REQUIRE); } else { builder.clientAuth(ClientAuth.NONE); } - return builder.protocols("TLSv1.3", "TLSv1.2").build(); + SslContext context = builder.protocols("TLSv1.3", "TLSv1.2").build(); + if (!snapshot.isCurrent()) { + throw new IOException( + "TCP Proxy listener TLS material changed while its context was loading"); + } + return context; + } + + static CredentialSnapshot captureCredentialSnapshot(Path certificate, Path privateKey, Path ca) + throws IOException { + return new CredentialSnapshot( + CredentialPathSnapshot.capture(certificate), + CredentialPathSnapshot.capture(privateKey), + ca == null ? null : CredentialPathSnapshot.capture(ca)); + } + + private List watchedCredentialPaths() { + List paths = + new ArrayList<>( + List.of( + configuredPath(properties.getCertificateChainPath(), "certificate chain"), + configuredPath(properties.getPrivateKeyPath(), "private key"))); + if (trustPolicy.requiresClientCertificate()) { + paths.add(configuredPath(properties.getTrustedClientCaPath(), "trusted client CA")); + } + return List.copyOf(paths); + } + + private static Path configuredPath(String configuredPath, String label) { + try { + return Path.of(configuredPath); + } catch (RuntimeException ex) { + throw new IllegalStateException("Invalid TCP Proxy listener " + label + " path", ex); + } + } + + private void reloadSslContext() { + synchronized (reloadMonitor) { + try { + SslContext replacement = buildSslContext(); + activeSslContext.set(replacement); + tlsMaterialReloadHealthy = true; + LOG.info( + "TCP Proxy internal TLS listener accepted a validated credential update profile={}", + trustPolicy.profileName()); + } catch (Exception ex) { + tlsMaterialReloadHealthy = false; + LOG.error( + "TCP Proxy internal TLS listener rejected a credential update; keeping the last known-good context profile={}", + trustPolicy.profileName(), + ex); + throw new IllegalStateException("Unable to reload TCP Proxy listener TLS credentials", ex); + } + } } private static File requiredFile(String configuredPath, String label) { @@ -174,9 +260,137 @@ private static String requiredBindAddress(String configuredAddress) { return configuredAddress.trim(); } + static final class CredentialSnapshot { + private final CredentialPathSnapshot certificate; + private final CredentialPathSnapshot privateKey; + private final CredentialPathSnapshot clientCa; + + private CredentialSnapshot( + CredentialPathSnapshot certificate, + CredentialPathSnapshot privateKey, + CredentialPathSnapshot clientCa) { + this.certificate = certificate; + this.privateKey = privateKey; + this.clientCa = clientCa; + } + + void requireConsistentCertificateKeyGeneration() throws IOException { + if (certificate.isProjected() != privateKey.isProjected()) { + throw new IOException("TCP Proxy listener certificate and key use different projections"); + } + if (certificate.isProjected() + && (!certificate.projectionPointer.equals(privateKey.projectionPointer) + || !certificate.projectionGeneration.equals(privateKey.projectionGeneration))) { + throw new IOException("TCP Proxy listener certificate and key use different generations"); + } + } + + boolean isCurrent() { + return certificate.isCurrent() + && privateKey.isCurrent() + && (clientCa == null || clientCa.isCurrent()); + } + } + + private static final class CredentialPathSnapshot { + private static final String PROJECTED_DATA_DIRECTORY = "..data"; + + private final Path configuredPath; + private final Path readPath; + private final Path projectionPointer; + private final Path projectionGeneration; + private final FileState fileState; + + private CredentialPathSnapshot( + Path configuredPath, + Path readPath, + Path projectionPointer, + Path projectionGeneration, + FileState fileState) { + this.configuredPath = configuredPath; + this.readPath = readPath; + this.projectionPointer = projectionPointer; + this.projectionGeneration = projectionGeneration; + this.fileState = fileState; + } + + private static CredentialPathSnapshot capture(Path configuredPath) throws IOException { + Path normalizedPath = configuredPath.toAbsolutePath().normalize(); + if (Files.isSymbolicLink(normalizedPath)) { + Path fileTarget = Files.readSymbolicLink(normalizedPath); + if (fileTarget.getNameCount() > 1 + && PROJECTED_DATA_DIRECTORY.equals(fileTarget.getName(0).toString())) { + Path parent = normalizedPath.getParent(); + if (parent == null) { + throw new IOException("Projected TLS material has no parent directory"); + } + Path projectionPointer = parent.resolve(PROJECTED_DATA_DIRECTORY); + if (!Files.isSymbolicLink(projectionPointer)) { + throw new IOException("Projected TLS material has no stable ..data link"); + } + Path projectionGeneration = Files.readSymbolicLink(projectionPointer); + Path generationDirectory = + projectionGeneration.isAbsolute() + ? projectionGeneration + : parent.resolve(projectionGeneration); + Path relativeFile = fileTarget.subpath(1, fileTarget.getNameCount()); + Path readPath = generationDirectory.resolve(relativeFile).toAbsolutePath().normalize(); + return new CredentialPathSnapshot( + normalizedPath, + readPath, + projectionPointer, + projectionGeneration, + FileState.read(readPath)); + } + } + + Path readPath = normalizedPath.toRealPath(); + return new CredentialPathSnapshot( + normalizedPath, readPath, null, null, FileState.read(readPath)); + } + + private boolean isProjected() { + return projectionPointer != null; + } + + private boolean isCurrent() { + try { + if (isProjected()) { + return Files.isSymbolicLink(projectionPointer) + && projectionGeneration.equals(Files.readSymbolicLink(projectionPointer)) + && fileState.matches(readPath); + } + return readPath.equals(configuredPath.toRealPath()) && fileState.matches(readPath); + } catch (IOException ex) { + return false; + } + } + } + + private record FileState(Object fileKey, long size, FileTime modifiedTime) { + private static FileState read(Path path) throws IOException { + BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class); + return new FileState(attributes.fileKey(), attributes.size(), attributes.lastModifiedTime()); + } + + private boolean matches(Path path) throws IOException { + return equals(read(path)); + } + } + @Override public synchronized void stop() { running = false; + TlsCertificateWatcher watcher = certificateWatcher; + certificateWatcher = null; + tlsMaterialReloadHealthy = false; + if (watcher != null) { + try { + watcher.close(); + } catch (IOException ex) { + LOG.error("TCP Proxy internal TLS listener failed to stop its certificate watcher", ex); + } + } ScheduledFuture task = expiryTask; expiryTask = null; if (task != null) { @@ -233,6 +447,12 @@ public int boundPort() { return running && current != null && !current.isDisposed() ? current.port() : -1; } + /** Returns true only when the listener is serving the latest valid watched TLS material. */ + public boolean isTlsMaterialHealthy() { + TlsCertificateWatcher watcher = certificateWatcher; + return tlsMaterialReloadHealthy && watcher != null && watcher.isHealthy(); + } + int acceptedConnectionCount() { ChannelGroup channels = acceptedChannels; return channels == null ? 0 : channels.size(); @@ -240,9 +460,11 @@ int acceptedConnectionCount() { static final class InternalOnlyHttpHandler implements HttpHandler { private final HttpHandler delegate; + private final BooleanSupplier tlsMaterialHealthy; - InternalOnlyHttpHandler(HttpHandler delegate) { + InternalOnlyHttpHandler(HttpHandler delegate, BooleanSupplier tlsMaterialHealthy) { this.delegate = Objects.requireNonNull(delegate); + this.tlsMaterialHealthy = Objects.requireNonNull(tlsMaterialHealthy); } @Override @@ -252,14 +474,20 @@ public reactor.core.publisher.Mono handle( URI requestUri = request.getURI(); String decodedPath = requestUri.getPath(); String canonicalPath = requestUri.normalize().getPath(); + boolean gameplayPath = + canonicalPath != null + && (canonicalPath.equals("/ws/game") || canonicalPath.startsWith("/ws/game/")); + boolean readinessPath = "/actuator/health/readiness".equals(canonicalPath); + boolean livenessPath = "/actuator/health/liveness".equals(canonicalPath); if (decodedPath != null && !containsParentSegment(decodedPath) && canonicalPath != null && !containsDotSegment(canonicalPath) - && (canonicalPath.equals("/ws/game") - || canonicalPath.startsWith("/ws/game/") - || canonicalPath.equals("/actuator/health/readiness") - || canonicalPath.equals("/actuator/health/liveness"))) { + && (gameplayPath || readinessPath || livenessPath)) { + if ((gameplayPath || readinessPath) && !tlsMaterialHealthy.getAsBoolean()) { + response.setStatusCode(HttpStatus.SERVICE_UNAVAILABLE); + return response.setComplete(); + } return delegate.handle(request, response); } response.setStatusCode(HttpStatus.NOT_FOUND); @@ -299,4 +527,57 @@ private static boolean containsDotSegment(String path, boolean includeCurrentDir return false; } } + + /** Selects one complete TLS context for each new handshake without replacing the listener. */ + private static final class ReloadingSslContext extends SslContext { + private final AtomicReference current; + + private ReloadingSslContext(AtomicReference current) { + this.current = current; + } + + private SslContext current() { + return Objects.requireNonNull(current.get(), "TCP Proxy listener TLS context is unavailable"); + } + + @Override + public boolean isClient() { + return false; + } + + @Override + public List cipherSuites() { + return current().cipherSuites(); + } + + @Override + public ApplicationProtocolNegotiator applicationProtocolNegotiator() { + return current().applicationProtocolNegotiator(); + } + + @Override + public SSLEngine newEngine(ByteBufAllocator allocator) { + return current().newEngine(allocator); + } + + @Override + public SSLEngine newEngine(ByteBufAllocator allocator, String peerHost, int peerPort) { + return current().newEngine(allocator, peerHost, peerPort); + } + + @Override + public SSLSessionContext sessionContext() { + return current().sessionContext(); + } + + @Override + public long sessionCacheSize() { + return current().sessionCacheSize(); + } + + @Override + public long sessionTimeout() { + return current().sessionTimeout(); + } + } } diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/TcpProxyTlsListenerHealthIndicator.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/TcpProxyTlsListenerHealthIndicator.java index edfee576c3..2535a8991d 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/TcpProxyTlsListenerHealthIndicator.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/TcpProxyTlsListenerHealthIndicator.java @@ -35,7 +35,9 @@ public Health health() { details.put("configuredPort", properties.getPort()); details.put("boundPort", listener.boundPort()); details.put("trustProfile", properties.getTrustProfile()); - return listener.isRunning() + boolean tlsMaterialHealthy = listener.isTlsMaterialHealthy(); + details.put("tlsMaterial", tlsMaterialHealthy ? "healthy" : "unhealthy"); + return listener.isRunning() && tlsMaterialHealthy ? Health.up().withDetails(details).build() : Health.outOfService().withDetails(details).build(); } diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListenerTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListenerTest.java index acb405c05d..159dd3da93 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListenerTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListenerTest.java @@ -18,6 +18,7 @@ import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardCopyOption; import java.security.MessageDigest; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; @@ -27,10 +28,13 @@ import java.util.Objects; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.BooleanSupplier; import javax.net.ssl.SSLException; import net.firedevops.firemud.springcloudgateway.filter.TcpProxyTrustPolicy; +import net.firedevops.firemud.springcloudgateway.health.TcpProxyTlsListenerHealthIndicator; import net.firedevops.firemud.test.TlsTestSupport; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.springframework.context.support.GenericApplicationContext; @@ -104,6 +108,170 @@ void internalListenerRequiresClientCertificate() throws Exception { assertThat(listener.isRunning()).isFalse(); } + @Test + void rejectedCredentialUpdateKeepsLastKnownGoodContextAndMakesReadinessUnhealthy( + @TempDir Path directory) throws Exception { + Path certificate = Files.copy(fixture("dev-cert.pem"), directory.resolve("tls.crt")); + Path privateKey = Files.copy(fixture("dev-key.pem"), directory.resolve("tls.key")); + Path clientCa = Files.copy(fixture("dev-ca.pem"), directory.resolve("ca.crt")); + GatewayTcpProxyListenerProperties properties = tlsProperties(0); + properties.setCertificateChainPath(certificate.toString()); + properties.setPrivateKeyPath(privateKey.toString()); + properties.setTrustedClientCaPath(clientCa.toString()); + TcpProxyTrustPolicy policy = mock(TcpProxyTrustPolicy.class); + when(policy.requiresClientCertificate()).thenReturn(true); + when(policy.profileName()).thenReturn("breakglass_fingerprint"); + when(policy.timeUntilProfileExpiry()).thenReturn(null); + TcpProxyTlsListener listener = + new TcpProxyTlsListener( + properties, + policy, + (request, response) -> { + response.setStatusCode(HttpStatus.NO_CONTENT); + return response.setComplete(); + }); + + try { + listener.start(); + int port = listener.boundPort(); + assertThat(listener.isTlsMaterialHealthy()).isTrue(); + assertThat(requestStatus(port, clientContext(true), "/actuator/health/liveness")) + .isEqualTo(HttpStatus.NO_CONTENT.value()); + + Files.writeString(clientCa, "partial CA projection"); + await(() -> !listener.isTlsMaterialHealthy()); + + var readiness = new TcpProxyTlsListenerHealthIndicator(properties, listener).health(); + assertThat(readiness.getStatus().getCode()).isEqualTo("OUT_OF_SERVICE"); + assertThat(readiness.getDetails()).containsEntry("tlsMaterial", "unhealthy"); + assertThat(requestStatus(port, clientContext(true), "/actuator/health/liveness")) + .as("invalid trust material must not be installed for new no-SNI handshakes") + .isEqualTo(HttpStatus.NO_CONTENT.value()); + + Files.copy(fixture("dev-ca.pem"), clientCa, StandardCopyOption.REPLACE_EXISTING); + await(listener::isTlsMaterialHealthy); + assertThat(requestStatus(port, clientContext(true), "/actuator/health/liveness")) + .isEqualTo(HttpStatus.NO_CONTENT.value()); + } finally { + listener.stop(); + } + } + + @Test + void validClientCaRotationUpdatesNoSniHandshakesAndPreservesOpenBridge(@TempDir Path directory) + throws Exception { + Path clientCa = Files.copy(fixture("dev-ca.pem"), directory.resolve("ca.crt")); + GatewayTcpProxyListenerProperties properties = tlsProperties(0); + properties.setTrustedClientCaPath(clientCa.toString()); + TcpProxyTrustPolicy policy = mock(TcpProxyTrustPolicy.class); + when(policy.requiresClientCertificate()).thenReturn(true); + when(policy.profileName()).thenReturn("breakglass_fingerprint"); + when(policy.timeUntilProfileExpiry()).thenReturn(null); + + GenericApplicationContext appContext = new GenericApplicationContext(); + SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); + AtomicBoolean websocketOpened = new AtomicBoolean(); + WebSocketHandler websocketHandler = + session -> { + websocketOpened.set(true); + return session.receive().then(); + }; + mapping.setOrder(-1); + mapping.setUrlMap(Map.of("/ws/game", websocketHandler)); + appContext.getBeanFactory().registerSingleton("gameplayMapping", mapping); + appContext + .getBeanFactory() + .registerSingleton("gameplayWebSocketHandlerAdapter", new WebSocketHandlerAdapter()); + appContext.refresh(); + mapping.setApplicationContext(appContext); + HttpHandler webHandler = + WebHttpHandlerBuilder.webHandler(new DispatcherHandler(appContext)).build(); + HttpHandler httpHandler = + (request, response) -> { + if ("/actuator/health/liveness".equals(request.getURI().getPath())) { + response.setStatusCode(HttpStatus.NO_CONTENT); + return response.setComplete(); + } + return webHandler.handle(request, response); + }; + TcpProxyTlsListener listener = new TcpProxyTlsListener(properties, policy, httpHandler); + Disposable websocket = null; + + try { + listener.start(); + int port = listener.boundPort(); + assertThat(listener.isTlsMaterialHealthy()).isTrue(); + assertThat(requestStatus(port, clientContext(true), "/actuator/health/liveness")) + .isEqualTo(HttpStatus.NO_CONTENT.value()); + SslContext bridgeClientContext = clientContext(true); + websocket = + new ReactorNettyWebSocketClient( + HttpClient.create().secure(spec -> spec.sslContext(bridgeClientContext))) + .execute( + URI.create("wss://127.0.0.1:" + port + "/ws/game"), + session -> session.receive().then()) + .subscribe(); + await(websocketOpened::get); + assertThat(websocket.isDisposed()).isFalse(); + + Files.copy(fixture("tcp-proxy-client-ca.pem"), clientCa, StandardCopyOption.REPLACE_EXISTING); + SslContext rotatedClient = clientContext("tcp-proxy-client.pem", "tcp-proxy-client-key.pem"); + await( + () -> { + try { + return requestStatus(port, rotatedClient, "/actuator/health/liveness") + == HttpStatus.NO_CONTENT.value(); + } catch (RuntimeException handshakePending) { + return false; + } + }); + assertThat(listener.isTlsMaterialHealthy()).isTrue(); + assertThat(websocket.isDisposed()) + .as("ordinary TLS rotation leaves the established WebSocket bridge open") + .isFalse(); + Throwable oldIdentityFailure = + catchThrowable( + () -> requestStatus(port, clientContext(true), "/actuator/health/liveness")); + assertThat(oldIdentityFailure).isNotNull(); + assertThat(TlsTestSupport.isTlsHandshakeRejection(oldIdentityFailure)).isTrue(); + } finally { + if (websocket != null) { + websocket.dispose(); + } + listener.stop(); + appContext.close(); + } + } + + @Test + void projectedCredentialSnapshotRejectsGenerationSwapDuringContextLoad(@TempDir Path directory) + throws Exception { + Path generationOne = Files.createDirectory(directory.resolve("..generation-one")); + Path generationTwo = Files.createDirectory(directory.resolve("..generation-two")); + Files.copy(fixture("dev-cert.pem"), generationOne.resolve("tls.crt")); + Files.copy(fixture("dev-key.pem"), generationOne.resolve("tls.key")); + Files.copy(fixture("dev-cert.pem"), generationTwo.resolve("tls.crt")); + Files.copy(fixture("dev-key.pem"), generationTwo.resolve("tls.key")); + Path generationPointer = directory.resolve("..data"); + Files.createSymbolicLink(generationPointer, Path.of("..generation-one")); + Path certificate = + Files.createSymbolicLink(directory.resolve("tls.crt"), Path.of("..data/tls.crt")); + Path privateKey = + Files.createSymbolicLink(directory.resolve("tls.key"), Path.of("..data/tls.key")); + TcpProxyTlsListener.CredentialSnapshot snapshot = + TcpProxyTlsListener.captureCredentialSnapshot(certificate, privateKey, null); + + snapshot.requireConsistentCertificateKeyGeneration(); + assertThat(snapshot.isCurrent()).isTrue(); + + Files.delete(generationPointer); + Files.createSymbolicLink(generationPointer, Path.of("..generation-two")); + + assertThat(snapshot.isCurrent()) + .as("a projection swap during context construction invalidates the captured snapshot") + .isFalse(); + } + @Test void internalListenerRejectsMissingBindAddress() { GatewayTcpProxyListenerProperties properties = tlsProperties(0); @@ -214,7 +382,7 @@ void internalHandlerExposesOnlyGameplayAndHealthPaths() { return response.setComplete(); }; TcpProxyTlsListener.InternalOnlyHttpHandler handler = - new TcpProxyTlsListener.InternalOnlyHttpHandler(delegate); + new TcpProxyTlsListener.InternalOnlyHttpHandler(delegate, () -> true); MockServerHttpResponse gameplayResponse = new MockServerHttpResponse(); handler.handle(MockServerHttpRequest.get("/ws/game/demo").build(), gameplayResponse).block(); @@ -272,6 +440,44 @@ void internalHandlerExposesOnlyGameplayAndHealthPaths() { assertThat(pathlessResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } + @Test + void unhealthyProjectedTlsBlocksNewBridgeAndInternalReadinessButNotLiveness() { + AtomicBoolean delegated = new AtomicBoolean(); + AtomicBoolean tlsHealthy = new AtomicBoolean(true); + HttpHandler delegate = + (request, response) -> { + delegated.set(true); + response.setStatusCode(HttpStatus.NO_CONTENT); + return response.setComplete(); + }; + TcpProxyTlsListener.InternalOnlyHttpHandler handler = + new TcpProxyTlsListener.InternalOnlyHttpHandler(delegate, tlsHealthy::get); + + for (String path : new String[] {"/ws/game/demo", "/actuator/health/readiness"}) { + MockServerHttpResponse healthyResponse = new MockServerHttpResponse(); + handler.handle(MockServerHttpRequest.get(path).build(), healthyResponse).block(); + assertThat(delegated).as("healthy delegate for %s", path).isTrue(); + assertThat(healthyResponse.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); + } + + tlsHealthy.set(false); + for (String path : new String[] {"/ws/game/demo", "/actuator/health/readiness"}) { + delegated.set(false); + MockServerHttpResponse unhealthyResponse = new MockServerHttpResponse(); + handler.handle(MockServerHttpRequest.get(path).build(), unhealthyResponse).block(); + assertThat(delegated).as("unhealthy delegate for %s", path).isFalse(); + assertThat(unhealthyResponse.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); + } + + delegated.set(false); + MockServerHttpResponse livenessResponse = new MockServerHttpResponse(); + handler + .handle(MockServerHttpRequest.get("/actuator/health/liveness").build(), livenessResponse) + .block(); + assertThat(delegated).isTrue(); + assertThat(livenessResponse.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); + } + @Test void expiringTrustProfileTerminatesListenerAndExistingBridges() throws Exception { GatewayTcpProxyListenerProperties properties = tlsProperties(0); @@ -464,6 +670,22 @@ private static SslContext clientContext(boolean withCertificate) throws Exceptio return builder.build(); } + private static SslContext clientContext(String certificateName, String privateKeyName) + throws Exception { + return SslContextBuilder.forClient() + .trustManager(fixture("dev-ca.pem").toFile()) + .keyManager(fixture(certificateName).toFile(), fixture(privateKeyName).toFile()) + .build(); + } + + private static void await(BooleanSupplier condition) throws InterruptedException { + Instant deadline = Instant.now().plusSeconds(5); + while (!condition.getAsBoolean() && Instant.now().isBefore(deadline)) { + Thread.sleep(25); + } + assertThat(condition.getAsBoolean()).as("condition within bounded wait").isTrue(); + } + private static GatewayTcpProxyListenerProperties tlsProperties(int port) { GatewayTcpProxyListenerProperties properties = new GatewayTcpProxyListenerProperties(); properties.setEnabled(true); @@ -482,6 +704,11 @@ private static GatewayTcpProxyListenerProperties tlsProperties(int port) { private static Path fixture(String name) { Path workingDirectory = Path.of(System.getProperty("user.dir")).toAbsolutePath().normalize(); + Path moduleTestFixture = + workingDirectory.resolve("src/test/resources/certs").resolve(name).normalize(); + if (Files.isRegularFile(moduleTestFixture)) { + return moduleTestFixture; + } Path moduleSibling = workingDirectory .resolve("../common-test-support/src/testFixtures/resources/certs") diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/TcpProxyTlsListenerHealthIndicatorTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/TcpProxyTlsListenerHealthIndicatorTest.java index 00642d4258..14fdbdb46b 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/TcpProxyTlsListenerHealthIndicatorTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/TcpProxyTlsListenerHealthIndicatorTest.java @@ -29,12 +29,17 @@ void enabledListenerIsReadyOnlyAfterBinding() { TcpProxyTlsListener listener = mock(TcpProxyTlsListener.class); when(listener.boundPort()).thenReturn(-1); when(listener.isRunning()).thenReturn(false); + when(listener.isTlsMaterialHealthy()).thenReturn(false); assertThat(new TcpProxyTlsListenerHealthIndicator(properties, listener).health().getStatus()) .isEqualTo(Status.OUT_OF_SERVICE); when(listener.boundPort()).thenReturn(8443); when(listener.isRunning()).thenReturn(true); + when(listener.isTlsMaterialHealthy()).thenReturn(false); + assertThat(new TcpProxyTlsListenerHealthIndicator(properties, listener).health().getStatus()) + .isEqualTo(Status.OUT_OF_SERVICE); + when(listener.isTlsMaterialHealthy()).thenReturn(true); assertThat(new TcpProxyTlsListenerHealthIndicator(properties, listener).health().getStatus()) .isEqualTo(Status.UP); } @@ -47,6 +52,7 @@ void enabledListenerReportsNullTrustProfileWithoutThrowing() { TcpProxyTlsListener listener = mock(TcpProxyTlsListener.class); when(listener.boundPort()).thenReturn(-1); when(listener.isRunning()).thenReturn(false); + when(listener.isTlsMaterialHealthy()).thenReturn(false); var health = new TcpProxyTlsListenerHealthIndicator(properties, listener).health(); @@ -55,6 +61,7 @@ void enabledListenerReportsNullTrustProfileWithoutThrowing() { .containsEntry("listener", "tcp-proxy-internal-tls") .containsEntry("configuredPort", 8443) .containsEntry("boundPort", -1) - .containsEntry("trustProfile", null); + .containsEntry("trustProfile", null) + .containsEntry("tlsMaterial", "unhealthy"); } } diff --git a/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/health/TcpProxyTrafficReadinessHealthIndicator.java b/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/health/TcpProxyTrafficReadinessHealthIndicator.java index 98451d08bc..d54ed77bf2 100644 --- a/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/health/TcpProxyTrafficReadinessHealthIndicator.java +++ b/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/health/TcpProxyTrafficReadinessHealthIndicator.java @@ -43,6 +43,17 @@ public org.springframework.boot.health.contributor.Health health() { dependencies.put( "telnetListener", DependencyReadinessSupport.upDependency("bind", "tcp://0.0.0.0:telnet", "LISTENING")); + if (!server.isTlsMaterialHealthy()) { + dependencies.put( + "telnetTlsMaterial", + DependencyReadinessSupport.downDependency( + "tlsReload", "telnet://tls", "Telnet TLS certificate watcher unhealthy")); + return DependencyReadinessSupport.recordOutOfService( + readinessTransitionTracker, COMPONENT, CONTRACT, "telnetTlsMaterial", dependencies); + } + dependencies.put( + "telnetTlsMaterial", + DependencyReadinessSupport.upDependency("tlsReload", "telnet://tls", "READY")); if (!gatewayGameplayReadinessProbe.isReady()) { dependencies.put( "gatewayGameplayPath", diff --git a/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServer.java b/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServer.java index 1bebc5b1de..f24e65ef1d 100644 --- a/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServer.java +++ b/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServer.java @@ -20,14 +20,19 @@ import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import java.io.File; +import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BooleanSupplier; import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.tcpproxy.health.GatewayGameplayReadinessProbe; import net.firedevops.firemud.tcpproxy.service.TcpProxyEventService; @@ -79,7 +84,9 @@ public final class TelnetServer { private EventLoopGroup workerGroup; private volatile Channel serverChannel; private final AtomicBoolean running = new AtomicBoolean(false); - private SslContext sslContext; + private final Object tlsReloadMonitor = new Object(); + private volatile SslContext sslContext; + private volatile TlsCertificateWatcher tlsCertificateWatcher; @Autowired public TelnetServer( @@ -302,7 +309,90 @@ public TelnetServer( } private SslContext buildServerSslContext() throws SSLException { - return SslContextBuilder.forServer(new File(certPath), new File(keyPath)).build(); + Path certificatePath = Path.of(certPath).toAbsolutePath().normalize(); + Path privateKeyPath = Path.of(keyPath).toAbsolutePath().normalize(); + boolean certificateProjected = isProjectedSecretFile(certificatePath); + boolean privateKeyProjected = isProjectedSecretFile(privateKeyPath); + Path certificateParent = certificatePath.getParent(); + Path privateKeyParent = privateKeyPath.getParent(); + + if (certificateProjected || privateKeyProjected) { + if (!certificateProjected + || !privateKeyProjected + || certificateParent == null + || !certificateParent.equals(privateKeyParent)) { + throw new SSLException( + "TCP proxy Telnet TLS certificate and key must share one projected Secret"); + } + } + + try { + Path certificateSnapshot = certificatePath.toRealPath(); + Path privateKeySnapshot = privateKeyPath.toRealPath(); + Path certificateGeneration = certificateSnapshot.getParent(); + if (certificateProjected + && (certificateGeneration == null + || !certificateGeneration.equals(privateKeySnapshot.getParent()))) { + throw new SSLException( + "TCP proxy Telnet TLS certificate and key resolve to different Secret generations"); + } + + SslContext candidate = + SslContextBuilder.forServer(certificateSnapshot.toFile(), privateKeySnapshot.toFile()) + .build(); + + if (!certificateSnapshot.equals(certificatePath.toRealPath()) + || !privateKeySnapshot.equals(privateKeyPath.toRealPath())) { + throw new SSLException( + "TCP proxy Telnet TLS projection changed while the certificate and key were loading"); + } + return candidate; + } catch (IOException e) { + SSLException failure = new SSLException("TCP proxy Telnet TLS files could not be loaded"); + failure.initCause(e); + throw failure; + } + } + + private boolean isProjectedSecretFile(Path path) { + Path directory = path.getParent(); + return directory != null && Files.isSymbolicLink(directory.resolve("..data")); + } + + private void reloadServerSslContext() { + if (!tlsEnabled) { + return; + } + synchronized (tlsReloadMonitor) { + try { + SslContext replacement = buildServerSslContext(); + sslContext = replacement; + logger.info("TCP proxy Telnet TLS certificate and key reloaded"); + } catch (SSLException | RuntimeException e) { + tlsMisconfigCounter.increment(); + logger.error( + "TCP proxy Telnet TLS reload failed; retaining the last valid certificate and key", e); + throw new IllegalStateException("TCP proxy Telnet TLS reload failed", e); + } + } + } + + private void reloadServerSslContextFromWatcher() { + reloadServerSslContext(); + } + + private IOException closeTlsCertificateWatcher() { + TlsCertificateWatcher watcherToClose = tlsCertificateWatcher; + tlsCertificateWatcher = null; + if (watcherToClose == null) { + return null; + } + try { + watcherToClose.close(); + return null; + } catch (IOException e) { + return e; + } } private void validateTlsConfiguration() { @@ -337,6 +427,15 @@ public synchronized void start() throws InterruptedException { EventLoopGroup allocatedBossGroup = null; EventLoopGroup allocatedWorkerGroup = null; try { + if (tlsEnabled) { + TlsCertificateWatcher watcher = + new TlsCertificateWatcher( + List.of(Path.of(certPath), Path.of(keyPath)), + this::reloadServerSslContextFromWatcher); + tlsCertificateWatcher = watcher; + watcher.start(); + reloadServerSslContext(); + } allocatedBossGroup = new MultiThreadIoEventLoopGroup(1, NioIoHandler.newFactory()); allocatedWorkerGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()); bossGroup = allocatedBossGroup; @@ -350,6 +449,13 @@ public synchronized void start() throws InterruptedException { protected void initChannel(SocketChannel ch) { InetSocketAddress remoteAddress = ch.remoteAddress(); String clientIp = extractIp(remoteAddress); + if (tlsEnabled && !isTlsMaterialHealthy()) { + logger.warn( + "Rejecting Telnet TLS connection from {} because TLS material is unhealthy", + clientIp != null ? clientIp : remoteAddress); + ch.close(); + return; + } if (!tryAcquireSlot(clientIp)) { logger.warn( "Rejecting Telnet connection from {} due to connection limits", @@ -358,8 +464,9 @@ protected void initChannel(SocketChannel ch) { return; } var pipeline = ch.pipeline(); - if (tlsEnabled && sslContext != null) { - pipeline.addLast(sslContext.newHandler(ch.alloc())); + SslContext activeSslContext = sslContext; + if (tlsEnabled && activeSslContext != null) { + pipeline.addLast(activeSslContext.newHandler(ch.alloc())); } pipeline .addLast( @@ -401,12 +508,21 @@ public void channelInactive(ChannelHandlerContext ctx) logger.info("Telnet server started on port {}", boundPort); } catch (InterruptedException e) { running.set(false); + IOException watcherCloseFailure = closeTlsCertificateWatcher(); + if (watcherCloseFailure != null) { + e.addSuppressed(watcherCloseFailure); + } + closeServerChannelAfterStartFailure(e); shutdownEventLoopGroups(allocatedBossGroup, allocatedWorkerGroup); Thread.currentThread().interrupt(); throw e; } catch (Exception e) { running.set(false); - serverChannel = null; + IOException watcherCloseFailure = closeTlsCertificateWatcher(); + if (watcherCloseFailure != null) { + e.addSuppressed(watcherCloseFailure); + } + closeServerChannelAfterStartFailure(e); shutdownEventLoopGroups(allocatedBossGroup, allocatedWorkerGroup); String message = "Telnet server failed to start"; logger.error(message, e); @@ -417,8 +533,16 @@ public void channelInactive(ChannelHandlerContext ctx) @Timed(value = "tcpproxy.stop") public synchronized void stop() { if (!running.compareAndSet(true, false)) { + IOException watcherCloseFailure = closeTlsCertificateWatcher(); + if (watcherCloseFailure != null) { + logger.error("Failed to close Telnet TLS certificate watcher", watcherCloseFailure); + } return; } + IOException watcherCloseFailure = closeTlsCertificateWatcher(); + if (watcherCloseFailure != null) { + logger.error("Failed to close Telnet TLS certificate watcher", watcherCloseFailure); + } try { if (serverChannel != null) { serverChannel.close().sync(); @@ -434,6 +558,19 @@ public synchronized void stop() { logger.info("Telnet server stopped"); } + private void closeServerChannelAfterStartFailure(Exception failure) { + Channel channelToClose = serverChannel; + serverChannel = null; + if (channelToClose != null) { + try { + channelToClose.close().sync(); + } catch (InterruptedException closeFailure) { + failure.addSuppressed(closeFailure); + Thread.currentThread().interrupt(); + } + } + } + private void shutdownEventLoopGroups( EventLoopGroup allocatedBossGroup, EventLoopGroup allocatedWorkerGroup) { if (allocatedBossGroup != null) { @@ -459,6 +596,15 @@ public boolean isRunning() { return running.get() && serverChannel != null; } + /** Returns true when the listener is serving the latest valid watched TLS material. */ + public boolean isTlsMaterialHealthy() { + if (!tlsEnabled) { + return true; + } + TlsCertificateWatcher watcher = tlsCertificateWatcher; + return watcher != null && watcher.isHealthy(); + } + /** Current active connection count for metrics testing. */ int getActiveConnectionCount() { return activeConnections.get(); diff --git a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/health/TcpProxyTrafficReadinessHealthIndicatorTest.java b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/health/TcpProxyTrafficReadinessHealthIndicatorTest.java index a02d9ba014..c25f63a5a7 100644 --- a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/health/TcpProxyTrafficReadinessHealthIndicatorTest.java +++ b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/health/TcpProxyTrafficReadinessHealthIndicatorTest.java @@ -43,6 +43,7 @@ void healthReturnsOutOfServiceWhenListenerIsNotRunning() { void healthReturnsOutOfServiceWhenGatewayAdmissionPathIsDown() { TelnetServer telnetServer = mock(TelnetServer.class); when(telnetServer.isRunning()).thenReturn(true); + when(telnetServer.isTlsMaterialHealthy()).thenReturn(true); GatewayGameplayReadinessProbe probe = mock(GatewayGameplayReadinessProbe.class); when(probe.isReady()).thenReturn(false); when(probe.readinessUri()) @@ -64,10 +65,34 @@ void healthReturnsOutOfServiceWhenGatewayAdmissionPathIsDown() { assertEquals("DOWN", dependencies.get("gatewayGameplayPath").get("status")); } + @Test + void healthReturnsOutOfServiceWhenTelnetTlsWatcherIsUnhealthy() { + TelnetServer telnetServer = mock(TelnetServer.class); + when(telnetServer.isRunning()).thenReturn(true); + when(telnetServer.isTlsMaterialHealthy()).thenReturn(false); + GatewayGameplayReadinessProbe probe = mock(GatewayGameplayReadinessProbe.class); + when(probe.isReady()).thenReturn(true); + TcpProxyTrafficReadinessHealthIndicator indicator = + new TcpProxyTrafficReadinessHealthIndicator(providerFor(telnetServer), probe, tracker()); + + Health health = indicator.health(); + @SuppressWarnings("unchecked") + Map> dependencies = + (Map>) + Objects.requireNonNull(health.getDetails().get("dependencies")); + + assertEquals(Status.OUT_OF_SERVICE, health.getStatus()); + assertEquals("telnetTlsMaterial", health.getDetails().get("failingDependency")); + assertEquals("UP", dependencies.get("telnetListener").get("status")); + assertEquals("DOWN", dependencies.get("telnetTlsMaterial").get("status")); + assertEquals("tlsReload", dependencies.get("telnetTlsMaterial").get("check")); + } + @Test void healthReturnsUpWhenListenerAndGatewayPathAreReady() { TelnetServer telnetServer = mock(TelnetServer.class); when(telnetServer.isRunning()).thenReturn(true); + when(telnetServer.isTlsMaterialHealthy()).thenReturn(true); GatewayGameplayReadinessProbe probe = mock(GatewayGameplayReadinessProbe.class); when(probe.isReady()).thenReturn(true); when(probe.readinessUri()) diff --git a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/TelnetServerTest.java b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/TelnetServerTest.java index 992c8b2670..2d32f1920b 100644 --- a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/TelnetServerTest.java +++ b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/TelnetServerTest.java @@ -1,17 +1,22 @@ package net.firedevops.firemud.tcpproxy.telnet; 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.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.IOException; import java.io.InputStream; +import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardCopyOption; import java.security.KeyStore; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; @@ -22,6 +27,7 @@ import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.tcpproxy.health.GatewayGameplayReadinessProbe; import net.firedevops.firemud.tcpproxy.service.TcpProxyEventService; @@ -33,6 +39,8 @@ import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; +import org.springframework.boot.health.contributor.Health; +import org.springframework.boot.health.contributor.Status; class TelnetServerTest { private static final int TLS_CONNECT_TIMEOUT_MILLIS = 5_000; @@ -64,6 +72,7 @@ void serverStartsAndStops() throws Exception { readyProbe(), gatewayClient()); server.start(); + assertTrue(server.isTlsMaterialHealthy()); server.stop(); assertTrue(true); // no exception means success } @@ -90,6 +99,7 @@ void failedBindReleasesEventLoopGroupsForRetry() throws Exception { } server.start(); + assertTrue(server.isTlsMaterialHealthy()); assertTrue(server.isRunning()); } @@ -297,6 +307,81 @@ void configuredTlsCertificateAcceptsTlsHandshake(@TempDir Path tempDir) throws E } } + @Test + void projectedTlsRotationIsAtomicAndLeavesExistingConnectionsOpen(@TempDir Path tempDir) + throws Exception { + Path mount = Files.createDirectory(tempDir.resolve("telnet-tls")); + createProjectedGeneration( + mount, "..2026_09_24_00_00_00", "/certs/dev-cert.pem", "/certs/dev-key.pem"); + Files.createSymbolicLink(mount.resolve("..data"), Path.of("..2026_09_24_00_00_00")); + Files.createSymbolicLink(mount.resolve("tls.crt"), Path.of("..data/tls.crt")); + Files.createSymbolicLink(mount.resolve("tls.key"), Path.of("..data/tls.key")); + + var registry = new io.micrometer.core.instrument.simple.SimpleMeterRegistry(); + int activeWatchersBefore = activeWatcherCount(TlsCertificateWatcher.health()); + server = + new TelnetServer( + 0, + true, + mount.resolve("tls.crt").toString(), + mount.resolve("tls.key").toString(), + false, + 0, + 0, + 4096, + registry, + Mockito.mock(TcpProxyEventService.class), + readyProbe(), + gatewayClient()); + server.start(); + assertTrue(server.isTlsMaterialHealthy()); + + SSLContext clientContext = tlsClientContext(); + try (SSLSocket existingConnection = connectTls(server, clientContext)) { + X509Certificate initialCertificate = peerCertificate(existingConnection); + + switchProjectedGeneration( + mount, + "..2026_09_24_00_00_01", + "/certs/rotated-gateway-client.crt", + "/certs/rotated-gateway-client.key"); + assertEquals("SUCCEEDED", invokeWatcherReload(server)); + + java.math.BigInteger rotatedSerial; + try (SSLSocket rotatedConnection = connectTls(server, clientContext)) { + X509Certificate rotatedCertificate = peerCertificate(rotatedConnection); + assertFalse( + initialCertificate.getSerialNumber().equals(rotatedCertificate.getSerialNumber())); + rotatedSerial = rotatedCertificate.getSerialNumber(); + } + assertExistingTlsSession(existingConnection, initialCertificate); + + switchProjectedGeneration(mount, "..2026_09_24_00_00_02", "/certs/dev-cert.pem", null); + assertEquals("FAILED", invokeWatcherReload(server)); + assertFalse(server.isTlsMaterialHealthy()); + assertEquals(Status.OUT_OF_SERVICE, TlsCertificateWatcher.health().getStatus()); + assertTrue(registry.counter("tcpproxy.tls.misconfig").count() >= 1.0); + + assertThrows(IOException.class, () -> connectTls(server, clientContext)); + assertExistingTlsSession(existingConnection, initialCertificate); + + switchProjectedGeneration( + mount, "..2026_09_24_00_00_03", "/certs/dev-cert.pem", "/certs/dev-key.pem"); + assertEquals("SUCCEEDED", invokeWatcherReload(server)); + assertTrue(server.isTlsMaterialHealthy()); + assertEquals(Status.UP, TlsCertificateWatcher.health().getStatus()); + try (SSLSocket recoveredConnection = connectTls(server, clientContext)) { + assertEquals( + initialCertificate.getSerialNumber(), + peerCertificate(recoveredConnection).getSerialNumber()); + } + assertExistingTlsSession(existingConnection, initialCertificate); + } + + server.stop(); + assertEquals(activeWatchersBefore, activeWatcherCount(TlsCertificateWatcher.health())); + } + private GatewayGameplayReadinessProbe readyProbe() { GatewayGameplayReadinessProbe probe = Mockito.mock(GatewayGameplayReadinessProbe.class); Mockito.when(probe.isReady()).thenReturn(true); @@ -337,4 +422,105 @@ private TelnetServer newServerWithDefaults( new RuntimeIdentity( "tcp-proxy-service", "tcp-proxy-test", null, Instant.EPOCH, null, null, null)); } + + private static void createProjectedGeneration( + Path mount, String generation, String certificateResource, String keyResource) + throws IOException { + Path generationDirectory = Files.createDirectory(mount.resolve(generation)); + copyResource(certificateResource, generationDirectory.resolve("tls.crt")); + if (keyResource == null) { + Files.writeString(generationDirectory.resolve("tls.key"), "partial projected private key"); + } else { + copyResource(keyResource, generationDirectory.resolve("tls.key")); + } + } + + private static void copyResource(String resource, Path target) throws IOException { + try (InputStream input = TelnetServerTest.class.getResourceAsStream(resource)) { + assertNotNull(input, "Missing TLS test fixture " + resource); + Files.copy(input, target); + } + } + + private static void switchProjectedGeneration( + Path mount, String generation, String certificateResource, String keyResource) + throws IOException { + createProjectedGeneration(mount, generation, certificateResource, keyResource); + Path nextPointer = mount.resolve("..data-next"); + Files.createSymbolicLink(nextPointer, Path.of(generation)); + Files.move( + nextPointer, + mount.resolve("..data"), + StandardCopyOption.ATOMIC_MOVE, + StandardCopyOption.REPLACE_EXISTING); + } + + private static String invokeWatcherReload(TelnetServer server) throws Exception { + Field watcherField = TelnetServer.class.getDeclaredField("tlsCertificateWatcher"); + watcherField.setAccessible(true); + TlsCertificateWatcher watcher = (TlsCertificateWatcher) watcherField.get(server); + assertNotNull(watcher); + Method invokeReload = + TlsCertificateWatcher.class.getDeclaredMethod("invokeReloadCallback", boolean.class); + invokeReload.setAccessible(true); + return invokeReload.invoke(watcher, false).toString(); + } + + private static SSLContext tlsClientContext() throws Exception { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + for (String fixture : + new String[] {"/certs/dev-cert.pem", "/certs/rotated-gateway-client.crt"}) { + try (InputStream certificate = TelnetServerTest.class.getResourceAsStream(fixture)) { + assertNotNull(certificate); + X509Certificate x509Certificate = + (X509Certificate) + CertificateFactory.getInstance("X.509").generateCertificate(certificate); + trustStore.setCertificateEntry(fixture, x509Certificate); + } + } + TrustManagerFactory trustManagers = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagers.init(trustStore); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, trustManagers.getTrustManagers(), null); + return context; + } + + private static SSLSocket connectTls(TelnetServer server, SSLContext clientContext) + throws IOException { + Socket plainSocket = new Socket(); + plainSocket.setSoTimeout(TLS_READ_TIMEOUT_MILLIS); + plainSocket.connect( + new InetSocketAddress("localhost", server.getPort()), TLS_CONNECT_TIMEOUT_MILLIS); + SSLSocket tlsSocket = + (SSLSocket) + clientContext + .getSocketFactory() + .createSocket(plainSocket, "localhost", server.getPort(), true); + try { + tlsSocket.setSoTimeout(TLS_READ_TIMEOUT_MILLIS); + tlsSocket.startHandshake(); + return tlsSocket; + } catch (IOException e) { + tlsSocket.close(); + throw e; + } + } + + private static X509Certificate peerCertificate(SSLSocket socket) throws Exception { + return (X509Certificate) socket.getSession().getPeerCertificates()[0]; + } + + private static void assertExistingTlsSession(SSLSocket socket, X509Certificate initialCertificate) + throws Exception { + assertTrue(socket.isConnected()); + assertFalse(socket.isClosed()); + assertTrue(socket.getSession().isValid()); + assertEquals(initialCertificate.getSerialNumber(), peerCertificate(socket).getSerialNumber()); + } + + private static int activeWatcherCount(Health health) { + return ((Number) health.getDetails().get("activeWatchers")).intValue(); + } }