diff --git a/.github/workflows/base-image.yml b/.github/workflows/base-image.yml index 6928ee81..2e209c02 100644 --- a/.github/workflows/base-image.yml +++ b/.github/workflows/base-image.yml @@ -17,6 +17,11 @@ permissions: packages: write id-token: write +# Public-source security hold: BuildKit history may contain unreviewed build diagnostics. +# Retain normal job logs/explicit artifacts; suppress automatic .dockerbuild upload. +env: + DOCKER_BUILD_RECORD_UPLOAD: 'false' + defaults: run: shell: bash -euo pipefail {0} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0383b5c7..7bbb8153 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -97,8 +97,12 @@ jobs: if [ -z "$TOKEN" ]; then TOKEN=$(docker compose -f compose/docker-compose.yml exec -T winebot cat /winebot-shared/winebot_api_token 2>/dev/null || true) fi + if [ -z "$TOKEN" ]; then + echo "Conformance token unavailable" >&2 + exit 1 + fi + echo "::add-mask::$TOKEN" echo "token=$TOKEN" >> "$GITHUB_OUTPUT" - echo "API token read: ${TOKEN:0:8}..." >> "$GITHUB_STEP_SUMMARY" - name: Run conformance tests env: @@ -109,14 +113,23 @@ jobs: --api-url "$API_URL" \ --api-token "$API_TOKEN" \ --results-file conformance-results.json \ - -v --tb=short + -v --tb=no --show-capture=no -rN - - name: Upload conformance results + - name: Project safe public conformance evidence + id: public-conformance-summary if: always() + run: | + python3 winebot/scripts/ci/sanitize-conformance-results.py \ + --input conformance-results.json \ + --output conformance-summary-public.json + + - name: Upload conformance results + if: ${{ always() && steps.public-conformance-summary.outcome == 'success' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a with: name: conformance-results - path: conformance-results.json + path: conformance-summary-public.json + if-no-files-found: error - name: Stop services if: always() diff --git a/.github/workflows/nightly-soak.yml b/.github/workflows/nightly-soak.yml index e5924da7..2c1bc465 100644 --- a/.github/workflows/nightly-soak.yml +++ b/.github/workflows/nightly-soak.yml @@ -8,6 +8,11 @@ on: permissions: contents: read +# Public-source security hold: BuildKit history may contain unreviewed build diagnostics. +# Retain normal job logs/explicit artifacts; suppress automatic .dockerbuild upload. +env: + DOCKER_BUILD_RECORD_UPLOAD: 'false' + defaults: run: shell: bash -euo pipefail {0} diff --git a/.github/workflows/openttd-win-cpu-rdte.yml b/.github/workflows/openttd-win-cpu-rdte.yml new file mode 100644 index 00000000..825c3d4a --- /dev/null +++ b/.github/workflows/openttd-win-cpu-rdte.yml @@ -0,0 +1,299 @@ +name: OpenTTD Windows Game CPU RDTE +on: + workflow_dispatch: + pull_request: + paths: + - .github/workflows/openttd-win-cpu-rdte.yml + - docker/openttd-software-gl.Dockerfile +permissions: + contents: read +concurrency: + group: openttd-win-rdte-${{ github.ref }} + cancel-in-progress: true + +jobs: + openttd-win64-cpu: + runs-on: ubuntu-24.04 + timeout-minutes: 20 + env: + DOCKER_BUILD_RECORD_UPLOAD: 'false' + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + - name: Fetch officially checksummed game and free graphics assets + timeout-minutes: 5 + run: | + mkdir -p "$RUNNER_TEMP/win-game" "$RUNNER_TEMP/opengfx" + curl -fsSL --retry 1 --connect-timeout 10 --max-time 120 \ + https://cdn.openttd.org/openttd-releases/15.3/openttd-15.3-windows-win64.zip \ + -o "$RUNNER_TEMP/openttd.zip" + echo "61c0a6a43d81008c7ff4330fb56351bbf66a980cdad041f1d0e08b51f2eeb34c $RUNNER_TEMP/openttd.zip" | sha256sum -c --status + curl -fsSL --retry 1 --connect-timeout 10 --max-time 120 \ + https://cdn.openttd.org/opengfx-releases/8.0/opengfx-8.0-all.zip \ + -o "$RUNNER_TEMP/opengfx.zip" + echo "43a0c1dabf39cb865394f3a6cc36d4da5c10ecfaaf55652043104806810903be $RUNNER_TEMP/opengfx.zip" | sha256sum -c --status + unzip -qq "$RUNNER_TEMP/openttd.zip" -d "$RUNNER_TEMP/win-game" + unzip -qq "$RUNNER_TEMP/opengfx.zip" -d "$RUNNER_TEMP/opengfx" + game="$(find "$RUNNER_TEMP/win-game" -type f -iname openttd.exe -print -quit)" + test -n "$game" + basedir="$(dirname "$game")/baseset" + mkdir -p "$basedir" + find "$RUNNER_TEMP/opengfx" -type f \( -iname '*.tar' -o -iname '*.obg' -o -iname '*.grf' \) -exec cp -n '{}' "$basedir" \; + test "$(find "$basedir" -type f | wc -l)" -ge 1 + echo 'PASS: official game and free base graphics integrity and staging' + - name: Build WineBot experiment image without publication + timeout-minutes: 13 + run: | + docker build -f docker/Dockerfile --target intent-slim -t winebot:openttd-rdte . + docker build -f docker/openttd-software-gl.Dockerfile -t winebot:openttd-cpu . + - name: Launch actual Windows OpenTTD through Wine and confirm visible game window + timeout-minutes: 3 + run: | + timeout -k 10s 155s docker run --rm --init --network none \ + --cpus=2 --memory=3g --pids-limit=256 \ + -e WINEPREFIX=/tmp/winebot-openttd-fixture \ + -e WINEDEBUG=-all -e LIBGL_ALWAYS_SOFTWARE=1 \ + -e GALLIUM_DRIVER=llvmpipe -e LP_NUM_THREADS=4 \ + -v "$RUNNER_TEMP/win-game:/game:ro" \ + --entrypoint /usr/bin/xvfb-run winebot:openttd-cpu \ + -a -s '-screen 0 1280x720x24 +extension GLX -nolisten tcp' \ + /bin/bash -euo pipefail -c ' + # Qualify this very Xvfb/Wine context before blaming the game. + if ! glxinfo -B 2>/dev/null | grep -qi llvmpipe; then + echo "UNQUALIFIED: LLVMpipe renderer unavailable inside game cell" + exit 2 + fi + echo "PASS: game-cell software GLX" + wine notepad.exe >/tmp/wine-builtin-local.log 2>&1 & + baseline=0 + for i in $(seq 1 60); do + if xdotool search --onlyvisible --name Notepad >/dev/null 2>&1; then + baseline=1 + break + fi + sleep 0.5 + done + wineserver -k >/dev/null 2>&1 || true + if [ "$baseline" -ne 1 ]; then + echo "UNQUALIFIED: Wine built-in X11 window control" + exit 2 + fi + echo "PASS: Wine built-in X11 window control" + exe="$(find /game -type f -iname openttd.exe -print -quit)" + test -n "$exe" + cd "$(dirname "$exe")" + # Select the documented Win32 video driver for a GDI baseline. + wine "$exe" -v win32 -m null -s null -x >/tmp/wine-game-local.log 2>&1 & + game_pid=$! + found=0 + for i in $(seq 1 100); do + if xdotool search --onlyvisible --name OpenTTD >/dev/null 2>&1 || \ + xdotool search --onlyvisible --class openttd >/dev/null 2>&1; then + found=1 + break + fi + # Wine launchers can return before the child X11 window appears. + sleep 0.6 + done + if [ "$found" -ne 1 ]; then + echo "UNQUALIFIED: Windows game window not visible after qualified Wine/X11 control" + exit 2 + fi + echo "PASS: Windows OpenTTD game window visible under Wine" + # Window-scoped local-only capture; publish only dimensions and color diversity. + wid="$(xdotool search --onlyvisible --name OpenTTD 2>/dev/null | head -1 || true)" + if [ -z "$wid" ]; then + wid="$(xdotool search --onlyvisible --class openttd 2>/dev/null | head -1 || true)" + fi + if [[ ! "$wid" =~ ^[0-9]{1,16}$ ]]; then + echo "UNQUALIFIED: game window id selection" + exit 2 + fi + sleep 2 + if ! import -window "$wid" /tmp/wine-openttd-scoped.png >/dev/null 2>&1; then + echo "UNQUALIFIED: scoped window capture" + exit 2 + fi + read -r image_w image_h image_colors <<< "$(identify -format "%w %h %k" /tmp/wine-openttd-scoped.png 2>/dev/null || true)" + if [[ ! "${image_w:-}" =~ ^[0-9]{1,4}$ || + ! "${image_h:-}" =~ ^[0-9]{1,4}$ || + ! "${image_colors:-}" =~ ^[0-9]{1,9}$ ]] || + [ "$image_w" -lt 200 ] || [ "$image_h" -lt 120 ] || + [ "$image_colors" -lt 40 ]; then + echo "UNQUALIFIED: window content variety/dimensions" + exit 2 + fi + echo "PASS: OpenTTD scoped color-content smoke" + kill "$game_pid" 2>/dev/null || true + wineserver -k >/dev/null 2>&1 || true + # PNG is deleted with the disposable container; never uploaded. + ' + - name: Qualify unprivileged Wine home and X11 controls independently + timeout-minutes: 3 + run: | + echo 'BEGIN: unprivileged synthetic Wine X11 control' + timeout -k 10s 160s docker run --rm --init --network none \ + --user 1000:1000 --cpus=2 --memory=3g --pids-limit=256 \ + --tmpfs /tmp:rw,exec,nosuid,size=512m,mode=1777 \ + -e HOME=/home/winebot -e WINEPREFIX=/tmp/winebot-nonroot-fixture \ + -e WINEDEBUG=-all -e LIBGL_ALWAYS_SOFTWARE=1 -e GALLIUM_DRIVER=llvmpipe \ + --entrypoint /usr/bin/xvfb-run winebot:openttd-cpu \ + -a -s '-screen 0 640x480x24 +extension GLX -nolisten tcp' \ + /bin/bash -euo pipefail -c ' + if [ "$(id -u)" -ne 1000 ] || [ ! -w "$HOME" ] || [ ! -w /tmp ]; then + echo "UNQUALIFIED: nonroot identity or writable home/tmp" + exit 2 + fi + echo "PASS: unprivileged identity and writable home/tmp" + if ! command -v wineboot >/dev/null 2>&1 || + ! wine --version >/dev/null 2>&1; then + echo "UNQUALIFIED: nonroot Wine binary/launcher unavailable" + exit 2 + fi + tmp_rc=0 + timeout -k 5s 45s wineboot -u >/tmp/wineboot-job-local.log 2>&1 || tmp_rc=$? + if [ "$tmp_rc" -ne 0 ]; then + echo "OBS: nonroot tmpfs Wine prefix initialization failed rc=$tmp_rc" + export WINEPREFIX="$HOME/.winebot-nonroot-fixture" + home_rc=0 + timeout -k 5s 45s wineboot -u >/tmp/wineboot-home-local.log 2>&1 || home_rc=$? + if [ "$home_rc" -ne 0 ]; then + echo "UNQUALIFIED: nonroot Wine prefix tmp_rc=$tmp_rc home_rc=$home_rc" + exit 2 + fi + echo "PASS: nonroot Wine prefix under writable home" + else + echo "PASS: nonroot Wine prefix on isolated tmpfs" + fi + wine notepad.exe >/tmp/notepad-job-local.log 2>&1 & + found=0 + for i in $(seq 1 60); do + if xdotool search --onlyvisible --name Notepad >/dev/null 2>&1; then + found=1 + break + fi + sleep 0.5 + done + wineserver -k >/dev/null 2>&1 || true + if [ "$found" -ne 1 ]; then + echo "UNQUALIFIED: unprivileged Wine X11 visible window" + exit 2 + fi + echo "PASS: unprivileged Wine X11 visible window" + ' + - name: Start real Windows OpenTTD with verified unprivileged HOME prefix + timeout-minutes: 3 + run: | + timeout -k 10s 160s docker run --rm --init --network none \ + --user 1000:1000 --cpus=2 --memory=3g --pids-limit=256 \ + --tmpfs /tmp:rw,exec,nosuid,size=512m,mode=1777 \ + -e HOME=/home/winebot -e WINEDEBUG=-all \ + -e LIBGL_ALWAYS_SOFTWARE=1 -e GALLIUM_DRIVER=llvmpipe \ + -v "$RUNNER_TEMP/win-game:/game:ro" \ + --entrypoint /usr/bin/xvfb-run winebot:openttd-cpu \ + -a -s '-screen 0 1280x720x24 +extension GLX -nolisten tcp' \ + /bin/bash -euo pipefail -c ' + if [ "$(id -u)" -ne 1000 ] || [ ! -w "$HOME" ]; then + echo "UNQUALIFIED: nonroot writable HOME" + exit 2 + fi + export WINEPREFIX="$HOME/.winebot-game-fixture" + if ! timeout -k 5s 65s wineboot -u >/tmp/wineboot-game-local.log 2>&1; then + echo "UNQUALIFIED: nonroot HOME prefix initialization" + exit 2 + fi + exe="$(find /game -type f -iname openttd.exe -print -quit)" + if [ -z "$exe" ]; then + echo "UNQUALIFIED: verified Windows executable missing" + exit 2 + fi + cd "$(dirname "$exe")" + wine "$exe" -v win32 -m null -s null -x >/tmp/wine-game-nonroot-local.log 2>&1 & + proc=$! + wid="" + for i in $(seq 1 100); do + wid="$(xdotool search --onlyvisible --name OpenTTD 2>/dev/null | head -1 || true)" + if [[ "$wid" =~ ^[0-9]{1,16}$ ]]; then break; fi + sleep 0.4 + done + if [[ ! "$wid" =~ ^[0-9]{1,16}$ ]]; then + echo "UNQUALIFIED: nonroot Windows game window" + exit 2 + fi + sleep 2 + if ! import -window "$wid" /tmp/wine-nonroot-scoped.png >/dev/null 2>&1; then + echo "UNQUALIFIED: nonroot window capture" + exit 2 + fi + read -r w h colors <<< "$(identify -format "%w %h %k" /tmp/wine-nonroot-scoped.png 2>/dev/null || true)" + if [[ ! "${w:-}" =~ ^[0-9]{1,4}$ || ! "${h:-}" =~ ^[0-9]{1,4}$ || ! "${colors:-}" =~ ^[0-9]{1,9}$ ]] || + [ "$w" -lt 200 ] || [ "$h" -lt 120 ] || [ "$colors" -lt 40 ]; then + echo "UNQUALIFIED: nonroot game framebuffer" + exit 2 + fi + echo "PASS: real Windows game visual frame under UID1000 HOME-owned Wine prefix" + kill "$proc" >/dev/null 2>&1 || true + wineserver -k >/dev/null 2>&1 || true + ' + - name: Source-backed deterministic Win32 OpenTTD new-world smoke + timeout-minutes: 3 + run: | + timeout -k 10s 160s docker run --rm --init --network none \ + --user 1000:1000 --cpus=2 --memory=3g --pids-limit=256 \ + --tmpfs /tmp:rw,exec,nosuid,size=512m,mode=1777 \ + -e HOME=/home/winebot -e WINEDEBUG=-all \ + -e LIBGL_ALWAYS_SOFTWARE=1 -e GALLIUM_DRIVER=llvmpipe \ + -v "$RUNNER_TEMP/win-game:/game:ro" \ + --entrypoint /usr/bin/xvfb-run winebot:openttd-cpu \ + -a -s '-screen 0 1280x720x24 +extension GLX -nolisten tcp' \ + /bin/bash -euo pipefail -c ' + export WINEPREFIX="$HOME/.winebot-newworld-fixture" + if ! timeout -k 5s 65s wineboot -u >/tmp/openttd-prefix-local.log 2>&1; then + echo "UNQUALIFIED: deterministic world HOME Wine prefix" + exit 2 + fi + exe="$(find /game -type f -iname openttd.exe -print -quit)" + if [ -z "$exe" ]; then echo "UNQUALIFIED: pinned game executable absent"; exit 2; fi + cd "$(dirname "$exe")" + # OpenTTD 15.3 src/openttd.cpp ShowHelp: + # -g creates a game and -G supplies its PRNG seed. + wine "$exe" -v win32 -m null -s null -g -G 61731 \ + >/tmp/openttd-world-local.log 2>&1 & + proc=$! + wid="" + for i in $(seq 1 100); do + wid="$(xdotool search --onlyvisible --name OpenTTD 2>/dev/null | head -1 || true)" + if [[ "$wid" =~ ^[0-9]{1,16}$ ]]; then break; fi + if ! kill -0 "$proc" 2>/dev/null; then + echo "UNQUALIFIED: deterministic world process exited" + exit 2 + fi + sleep 0.5 + done + if [[ ! "$wid" =~ ^[0-9]{1,16}$ ]]; then + echo "UNQUALIFIED: deterministic world window absent" + exit 2 + fi + sleep 5 + if ! import -window "$wid" /tmp/openttd-world-a.png >/dev/null 2>&1; then + echo "UNQUALIFIED: deterministic world scoped frame" + exit 2 + fi + read -r w h colors <<< "$(identify -format "%w %h %k" /tmp/openttd-world-a.png 2>/dev/null || true)" + if [[ ! "$w" =~ ^[0-9]{1,4}$ || ! "$h" =~ ^[0-9]{1,4}$ || + ! "$colors" =~ ^[0-9]{1,9}$ ]]; then + echo "UNQUALIFIED: deterministic world frame stats" + exit 2 + fi + echo "OBS: seeded-game window_width=$w height=$h colors=$colors" + if [ "$w" -lt 250 ] || [ "$h" -lt 180 ] || [ "$colors" -lt 70 ]; then + echo "UNQUALIFIED: seeded-game nonblank frame" + exit 2 + fi + echo "PASS: documented seeded new-game startup and Win32 visible pixels" + kill "$proc" >/dev/null 2>&1 || true + wineserver -k >/dev/null 2>&1 || true + ' + # This checks requested game initialization, not an independently + # decoded map, town, train, or in-world control. + # No screenshots, raw Wine logs, VNC listeners, game saves, secrets, + # machine identifiers, or artifacts uploaded by this RDTE. diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7f71529d..739c4f8f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,6 +12,11 @@ on: permissions: contents: read +# Public-source security hold: BuildKit history may contain unreviewed build diagnostics. +# Retain normal job logs/explicit artifacts; suppress automatic .dockerbuild upload. +env: + DOCKER_BUILD_RECORD_UPLOAD: 'false' + defaults: run: shell: bash -euo pipefail {0} @@ -140,6 +145,11 @@ jobs: if [ -z "$TOKEN" ]; then TOKEN=$(docker compose -f compose/docker-compose.yml exec -T winebot cat /winebot-shared/winebot_api_token 2>/dev/null || true) fi + if [ -z "$TOKEN" ]; then + echo "Conformance token unavailable" >&2 + exit 1 + fi + echo "::add-mask::$TOKEN" echo "token=$TOKEN" >> "$GITHUB_OUTPUT" - name: Run conformance tests @@ -151,14 +161,23 @@ jobs: --api-url "$API_URL" \ --api-token "$API_TOKEN" \ --results-file conformance-results.json \ - -v --tb=short + -v --tb=no --show-capture=no -rN - - name: Upload conformance results + - name: Project safe public conformance evidence + id: public-conformance-summary if: always() + run: | + python3 winebot/scripts/ci/sanitize-conformance-results.py \ + --input conformance-results.json \ + --output conformance-summary-public.json + + - name: Upload conformance results + if: ${{ always() && steps.public-conformance-summary.outcome == 'success' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a with: name: conformance-results-release - path: conformance-results.json + path: conformance-summary-public.json + if-no-files-found: error - name: Fail on conformance failure if: failure() diff --git a/.github/workflows/reusable-build-smoke-gate.yml b/.github/workflows/reusable-build-smoke-gate.yml old mode 100755 new mode 100644 index 82c6604c..48d669e8 --- a/.github/workflows/reusable-build-smoke-gate.yml +++ b/.github/workflows/reusable-build-smoke-gate.yml @@ -60,6 +60,11 @@ on: permissions: contents: read +# Public-source security hold: BuildKit history may contain unreviewed build diagnostics. +# Retain normal job logs/explicit artifacts; suppress automatic .dockerbuild upload. +env: + DOCKER_BUILD_RECORD_UPLOAD: 'false' + defaults: run: shell: bash -euo pipefail {0} @@ -177,6 +182,9 @@ jobs: - name: Generate trust pack artifact if: ${{ inputs.generate_trust_pack }} + env: + # Checkout of a PR may be a synthetic merge; preserve the actual source head. + WINEBOT_SOURCE_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} run: scripts/ci/generate-trust-pack.sh "${{ inputs.trust_pack_dir }}" - name: Upload trust pack diff --git a/docker/Dockerfile b/docker/Dockerfile index f23f878b..a7b84085 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -33,11 +33,11 @@ RUN bash /download_tool.sh "Python" \ && find /opt/winebot/windows-tools -name "*.txt" -delete FROM tool-base AS builder-winspy -# WinInspect v0.4.0 - UIA-enabled window inspection tool -# Replaces original strobejb/winspy v1.8.4 (no UIA support, 2022 vintage) +# WinInspect v0.4.4 - immutable portable release fixture (release asset SHA-256). +# Preserve checksum verification fail-closed; package promotion is independent. RUN bash /download_tool.sh "WinInspect" \ - "https://github.com/SemperSupra/WinInspect/releases/download/v0.4.0/WinInspectPortable-v0.4.0.zip" \ - "83b64999fef9ab01d749ab94193899e3915774d217900ac80c3c34021ff3e416" \ + "https://github.com/SemperSupra/WinInspect/releases/download/v0.4.4/WinInspectPortable-v0.4.4.zip" \ + "6ac0a65f774ffe69672f1c459254931ebfddb1e52c9fbec14b5db1348ccaad04" \ "/opt/winebot/windows-tools/WinSpy" \ && find /opt/winebot/windows-tools -name "*.txt" -delete diff --git a/docker/openttd-software-gl.Dockerfile b/docker/openttd-software-gl.Dockerfile new file mode 100644 index 00000000..aa1cce75 --- /dev/null +++ b/docker/openttd-software-gl.Dockerfile @@ -0,0 +1,10 @@ +# Disposable WineBot/OpenTTD software graphics layer; no production promotion. +ARG BASE_IMAGE=winebot:openttd-rdte +FROM ${BASE_IMAGE} +USER root +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update && apt-get install -y --no-install-recommends \ + libgl1 libgl1-mesa-dri libglx-mesa0 mesa-vulkan-drivers mesa-utils \ + && rm -rf /var/lib/apt/lists/* +ENV LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe LP_NUM_THREADS=4 +LABEL io.winebot.experimental.openttd_rdte="not-for-release" diff --git a/scripts/ci/generate-trust-pack.sh b/scripts/ci/generate-trust-pack.sh index 4c229533..ede0863c 100755 --- a/scripts/ci/generate-trust-pack.sh +++ b/scripts/ci/generate-trust-pack.sh @@ -2,18 +2,29 @@ set -euo pipefail OUT_DIR="${1:-artifacts/trust-pack}" -mkdir -p "$OUT_DIR" -timestamp="$(date -u +%Y-%m-%dT%H:%M:%SZ)" -sha="$(git rev-parse --short HEAD 2>/dev/null || echo unknown)" +# The checkout can be a synthetic PR merge commit rather than the source head. +# Record both IDs with unambiguous names; refuse provenance-free evidence. +checkout_sha="$(git rev-parse HEAD 2>/dev/null || true)" +source_sha="${WINEBOT_SOURCE_HEAD_SHA:-$checkout_sha}" +for candidate in "$checkout_sha" "$source_sha"; do + if [[ ! "$candidate" =~ ^[0-9a-f]{40}$ ]]; then + echo "Trust pack requires valid full checkout/source Git SHAs" >&2 + exit 1 + fi +done branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo unknown)" +timestamp="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +mkdir -p "$OUT_DIR" cat > "${OUT_DIR}/summary.md" < dict: + """Build output solely from validated, bounded, allowlisted fields.""" + if not isinstance(raw, dict) or not isinstance(raw.get("summary"), dict): + raise ValueError("missing or invalid conformance summary") + + summary = raw["summary"] + counts = {} + for key in COUNT_FIELDS: + value = summary.get(key) + if type(value) is not int or value < 0: + raise ValueError("invalid conformance count") + counts[key] = value + if sum(counts[k] for k in COUNT_FIELDS if k != "total") != counts["total"]: + raise ValueError("inconsistent conformance counts") + + failures = raw.get("failures") + if not isinstance(failures, list) or len(failures) != counts["failed"]: + raise ValueError("inconsistent failure inventory") + + tests = [] + for item in failures: + if not isinstance(item, dict): + raise ValueError("invalid failure entry") + name = item.get("test") + safe_name = ( + name + if isinstance(name, str) and len(name) <= 200 and SAFE_TEST_ID.fullmatch(name) + else "redacted" + ) + tests.append({"test_id": safe_name}) + + return { + "schema": "winebot.public-conformance.v1", + "summary": counts, + "failed_tests": tests, + "note": "Raw failure payloads and environment details remain job-local.", + } + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--input", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + + if not args.input.is_file() or args.input.stat().st_size > MAX_RAW_BYTES: + raise SystemExit("Conformance source unavailable or exceeds the public projection limit") + try: + original = json.loads(args.input.read_text(encoding="utf-8")) + public = project_public_result(original) + except (ValueError, UnicodeError, OSError): + raise SystemExit("Conformance report cannot be safely projected") from None + + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(public, indent=2, sort_keys=True) + "\n", encoding="utf-8") + print("Public conformance report projected without raw failure/environment fields") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/ci/test.sh b/scripts/ci/test.sh index 572871e1..bfe80059 100755 --- a/scripts/ci/test.sh +++ b/scripts/ci/test.sh @@ -22,4 +22,5 @@ pytest \ tests/test_diag_bundle.py \ tests/test_auto_view.py \ tests/test_ui_dashboard.py \ - tests/test_ui_accessibility.py + tests/test_ui_accessibility.py \ + tests/test_ci_trust_pack_provenance.py diff --git a/tests/test_ci_dockerbuild_artifact_policy.py b/tests/test_ci_dockerbuild_artifact_policy.py new file mode 100644 index 00000000..9a683120 --- /dev/null +++ b/tests/test_ci_dockerbuild_artifact_policy.py @@ -0,0 +1,54 @@ +"""Fail closed on automatic Docker BuildKit record publication from public CI.""" + +from __future__ import annotations + +import re +from pathlib import Path + +WORKFLOW_DIR = Path(__file__).resolve().parents[1] / ".github" / "workflows" +BUILD_ACTION = "uses: docker/build-push-action@" +WORKFLOW_GUARD = "\nenv:\n DOCKER_BUILD_RECORD_UPLOAD: 'false'\n" +DECLARATION = re.compile(r"(?m)^\s*DOCKER_BUILD_RECORD_UPLOAD:\s*(.*?)\s*$") + + +def _has_fail_closed_record_policy(source: str) -> bool: + header, boundary, _ = source.partition("\njobs:\n") + if not boundary: + return False + return WORKFLOW_GUARD in (header + "\n") and DECLARATION.findall(source) == ["'false'"] + + +def test_public_build_workflows_disable_automatic_build_record_upload() -> None: + workflows = sorted(WORKFLOW_DIR.glob("*.yml")) + build_workflows = [p for p in workflows if BUILD_ACTION in p.read_text(encoding="utf-8")] + assert build_workflows, "No Docker build workflows found; re-evaluate policy scope" + missing = [ + p.name + for p in build_workflows + if not _has_fail_closed_record_policy(p.read_text(encoding="utf-8")) + ] + assert not missing, f"Automatic unreviewed .dockerbuild publication enabled: {missing}" + + +def test_record_policy_fails_closed_on_missing_or_overridden_guard() -> None: + protected = ( + "name: Build\n" + "env:\n" + " DOCKER_BUILD_RECORD_UPLOAD: 'false'\n" + "jobs:\n" + " build:\n" + " steps:\n" + " - uses: docker/build-push-action@v6\n" + ) + assert _has_fail_closed_record_policy(protected) + assert not _has_fail_closed_record_policy(protected.replace("env:\n", "not-env:\n")) + assert not _has_fail_closed_record_policy( + protected.replace("'false'\n", "'true'\n") + ) + assert not _has_fail_closed_record_policy( + protected + " - env:\n DOCKER_BUILD_RECORD_UPLOAD: 'true'\n" + ) + +if __name__ == "__main__": + test_public_build_workflows_disable_automatic_build_record_upload() + test_record_policy_fails_closed_on_missing_or_overridden_guard() diff --git a/tests/test_ci_public_conformance_summary.py b/tests/test_ci_public_conformance_summary.py new file mode 100644 index 00000000..8ea2882d --- /dev/null +++ b/tests/test_ci_public_conformance_summary.py @@ -0,0 +1,142 @@ +"""Regression checks for minimizing public conformance evidence.""" + +from __future__ import annotations + +import json +import runpy +import subprocess +import sys +from pathlib import Path + +import pytest + +PROJECT = runpy.run_path("scripts/ci/sanitize-conformance-results.py")["project_public_result"] +SCRIPT = Path("scripts/ci/sanitize-conformance-results.py") + + +def sample_report() -> dict: + return { + "summary": { + "total": 3, + "passed": 1, + "failed": 1, + "skipped": 1, + "xfailed": 0, + "xpassed": 0, + "errors": 0, + }, + "environment": { + "hostname": "sensitive-host-alias", + "api_token": "SENSITIVE-TOKEN-VALUE", + }, + "failures": [ + { + "test": "contracts/tests/conformance/test_health.py::TestHealth::test_health", + "message": "secret SENSITIVE-TOKEN-VALUE; actual host sensitive-host-alias", + } + ], + "other_untrusted": "SENSITIVE-TOKEN-VALUE", + } + + +def test_projection_preserves_counts_and_only_static_test_identifiers() -> None: + report = PROJECT(sample_report()) + assert report["summary"]["total"] == 3 + assert report["summary"]["failed"] == 1 + assert report["failed_tests"] == [ + {"test_id": "contracts/tests/conformance/test_health.py::TestHealth::test_health"} + ] + rendered = json.dumps(report) + assert "sensitive-host-alias" not in rendered + assert "SENSITIVE-TOKEN-VALUE" not in rendered + assert "message" not in rendered + assert "environment" not in rendered + + +def test_bare_pytest_basename_is_preserved_without_runtime_text() -> None: + raw = sample_report() + raw["failures"][0]["test"] = "test_automation.py::TestWindows::test_windows_has_count" + report = PROJECT(raw) + assert report["failed_tests"] == [ + {"test_id": "test_automation.py::TestWindows::test_windows_has_count"} + ] + assert "SENSITIVE-TOKEN-VALUE" not in json.dumps(report) + + +def test_untrusted_test_id_is_redacted_instead_of_republished() -> None: + raw = sample_report() + raw["failures"][0]["test"] = "tests/conformance/test_health.py::test_a[param=private-token]" + assert PROJECT(raw)["failed_tests"] == [{"test_id": "redacted"}] + + +@pytest.mark.parametrize( + "change", + [ + lambda raw: raw["summary"].update({"failed": True}), + lambda raw: raw["summary"].update({"total": 7}), + lambda raw: raw.update({"failures": []}), + lambda raw: raw.update({"summary": "bad"}), + ], +) +def test_invalid_reports_fail_closed(change) -> None: + raw = sample_report() + change(raw) + with pytest.raises(ValueError): + PROJECT(raw) + + +def test_command_does_not_write_artifact_if_input_invalid(tmp_path: Path) -> None: + raw = sample_report() + raw["summary"]["total"] = 9 + input_path = tmp_path / "raw.json" + out = tmp_path / "public.json" + input_path.write_text(json.dumps(raw), encoding="utf-8") + process = subprocess.run( + [sys.executable, str(SCRIPT), "--input", str(input_path), "--output", str(out)], + capture_output=True, + text=True, + check=False, + ) + assert process.returncode != 0 + assert not out.exists() + +@pytest.mark.parametrize( + "workflow_path", + [".github/workflows/ci.yml", ".github/workflows/release.yml"], +) +def test_public_workflows_do_not_publish_raw_conformance_data(workflow_path: str) -> None: + source = Path(workflow_path).read_text(encoding="utf-8") + assert "--tb=no --show-capture=no -rN" in source + assert "path: conformance-summary-public.json" in source + assert "path: conformance-results.json" not in source + assert "steps.public-conformance-summary.outcome == 'success'" in source + assert "TOKEN:0:8" not in source + +def test_quiet_pytest_console_does_not_echo_assertion_response(tmp_path: Path) -> None: + fixture = tmp_path / "test_probe_private_payload.py" + fixture.write_text( + 'def test_probe():\n' + ' payload = {"value": "SYNTHETIC-UNPUBLISHED-MARKER"}\n' + ' assert "count" in payload\n', + encoding="utf-8", + ) + process = subprocess.run( + [ + sys.executable, + "-m", + "pytest", + str(fixture), + "-v", + "--tb=no", + "--show-capture=no", + "-rN", + ], + capture_output=True, + text=True, + check=False, + timeout=30, + ) + assert process.returncode == 1 + assert "1 failed" in process.stdout + assert "SYNTHETIC-UNPUBLISHED-MARKER" not in process.stdout + assert "SYNTHETIC-UNPUBLISHED-MARKER" not in process.stderr diff --git a/tests/test_ci_trust_pack_provenance.py b/tests/test_ci_trust_pack_provenance.py new file mode 100644 index 00000000..bbba38dd --- /dev/null +++ b/tests/test_ci_trust_pack_provenance.py @@ -0,0 +1,93 @@ +"""Guard exact Git source-versus-checkout provenance in public trust packs.""" + +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + +import pytest + +GENERATOR = Path(__file__).resolve().parents[1] / "scripts/ci/generate-trust-pack.sh" +WORKFLOW = ( + Path(__file__).resolve().parents[1] / ".github/workflows/reusable-build-smoke-gate.yml" +) +CHECKOUT = "b" * 40 +SOURCE = "a" * 40 + + +@pytest.fixture +def workspace(tmp_path: Path) -> Path: + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + fake_git = bin_dir / "git" + fake_git.write_text( + "#!/bin/sh\n" + 'if [ "$1" = "rev-parse" ] && [ "$2" = "HEAD" ]; then\n' + ' printf "%s\\n" "$FAKE_CHECKOUT_SHA"\n' + 'elif [ "$1" = "rev-parse" ] && [ "$2" = "--abbrev-ref" ]; then\n' + ' printf "HEAD\\n"\n' + "else\n" + " exit 7\n" + "fi\n", + encoding="utf-8", + ) + fake_git.chmod(0o755) + return tmp_path + + +def generate(workspace: Path, source: str | None = SOURCE, checkout: str = CHECKOUT): + env = { + **os.environ, + "PATH": f"{workspace / 'bin'}:{os.environ.get('PATH', '')}", + "FAKE_CHECKOUT_SHA": checkout, + } + if source is None: + env.pop("WINEBOT_SOURCE_HEAD_SHA", None) + else: + env["WINEBOT_SOURCE_HEAD_SHA"] = source + output = workspace / "pack" + result = subprocess.run( + ["bash", str(GENERATOR), str(output)], + cwd=workspace, + env=env, + text=True, + capture_output=True, + check=False, + timeout=30, + ) + return result, output + + +def test_merged_checkout_not_misrepresented_as_source(workspace: Path) -> None: + result, out = generate(workspace) + assert result.returncode == 0, result.stderr + summary = (out / "summary.md").read_text(encoding="utf-8") + assert f"- Tested checkout commit: {CHECKOUT}" in summary + assert f"- Source head commit: {SOURCE}" in summary + assert "- Commit: " not in summary + assert (out / "inventory.json").is_file() + + +def test_direct_checkout_defaults_source_to_tested_commit(workspace: Path) -> None: + result, out = generate(workspace, source=None) + assert result.returncode == 0, result.stderr + summary = (out / "summary.md").read_text(encoding="utf-8") + assert f"- Source head commit: {CHECKOUT}" in summary + + +@pytest.mark.parametrize( + ("source", "checkout"), + [("not-a-commit", CHECKOUT), (SOURCE, "invalid-checkout")], +) +def test_invalid_identity_fails_before_publishing( + workspace: Path, source: str, checkout: str +) -> None: + result, out = generate(workspace, source=source, checkout=checkout) + assert result.returncode != 0 + assert not (out / "summary.md").exists() + + +def test_reusable_workflow_supplies_pr_source_head() -> None: + workflow = WORKFLOW.read_text(encoding="utf-8") + assert "WINEBOT_SOURCE_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}" in workflow