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/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 index 82c6604c..d2f802b6 100755 --- 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} 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/scripts/ci/lint.sh b/scripts/ci/lint.sh index 4ede1cbf..51f8560f 100755 --- a/scripts/ci/lint.sh +++ b/scripts/ci/lint.sh @@ -18,6 +18,8 @@ else echo "Warning: shellcheck not found, skipping shell script linting." fi +# Independent, dependency-free check before any Dockerfile-dependent unit-image build. +python3 tests/test_ci_dockerbuild_artifact_policy.py python3 scripts/ci/verify-capability-matrix.py python3 scripts/ci/generate-python-sbom.py --output artifacts/ci/python-sbom.cdx.json python3 scripts/ci/validate-sbom.py --input artifacts/ci/python-sbom.cdx.json diff --git a/scripts/ci/sanitize-conformance-results.py b/scripts/ci/sanitize-conformance-results.py new file mode 100644 index 00000000..9fffd2e3 --- /dev/null +++ b/scripts/ci/sanitize-conformance-results.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Project raw conformance results into a minimal public evidence artifact. + +The underlying report may contain runtime responses, host identity, credentials, +or user-facing window titles. Never copy its free-form fields to a public artifact. +""" + +from __future__ import annotations + +import argparse +import json +import re +from pathlib import Path + +MAX_RAW_BYTES = 1_048_576 +COUNT_FIELDS = ("total", "passed", "failed", "skipped", "xfailed", "xpassed", "errors") +SAFE_TEST_ID = re.compile( + r"(?:(?:contracts/)?tests/conformance/)?test_[A-Za-z0-9_]+\.py" + r"(?:::\w+)*::test_[A-Za-z0-9_]+" +) + + +def project_public_result(raw: object) -> 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/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