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/rdte-wininspect-semantic.yml b/.github/workflows/rdte-wininspect-semantic.yml new file mode 100644 index 00000000..e2f893e0 --- /dev/null +++ b/.github/workflows/rdte-wininspect-semantic.yml @@ -0,0 +1,28 @@ +name: RDTE WineBot WinInspect semantic readiness (public synthetic) +on: + pull_request: + branches: [main] + paths: + - .github/workflows/rdte-wininspect-semantic.yml + - scripts/ci/rdte-wininspect-semantic-runtime.sh + - api/core/wininspect.py + - tests/test_wininspect_portable_layout.py + +permissions: + contents: read + +env: + DOCKER_BUILD_RECORD_UPLOAD: 'false' + +jobs: + semantic-bridge: + runs-on: ubuntu-latest + timeout-minutes: 40 + steps: + - name: Checkout exact disposable WineBot candidate + uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 + with: + persist-credentials: false + - name: Start WineBot and qualify read-only WinInspect with synthetic Notepad + shell: bash + run: bash scripts/ci/rdte-wininspect-semantic-runtime.sh 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/api/core/wininspect.py b/api/core/wininspect.py index 0bc039d9..be928edc 100644 --- a/api/core/wininspect.py +++ b/api/core/wininspect.py @@ -15,6 +15,8 @@ DEFAULT_HOST = "127.0.0.1" DEFAULT_PORT = 1985 DEFAULT_TIMEOUT_SECONDS = 3.0 +# WinInspect v0.4.4 release uses the v0.3.0 wire protocol (types.hpp). +WININSPECT_PROTOCOL_VERSION = "0.3.0" MAX_MESSAGE_SIZE = 10 * 1024 * 1024 READ_ONLY_METHODS = { "daemon.health", @@ -83,11 +85,23 @@ def timeout_seconds() -> float: return max(0.1, min(value, 30.0)) +WININSPECT_DEFAULT_DIR = "/opt/winebot/windows-tools/WinSpy" +WININSPECT_REQUIRED_FILES = ("wininspectd.exe", "wininspect.exe") + + def tool_dir() -> Path: - return Path( - os.getenv("WINEBOT_WININSPECT_DIR", "/opt/winebot/windows-tools/WinSpy").strip() - or "/opt/winebot/windows-tools/WinSpy" - ) + """Locate a complete WinInspect installation without mixing layouts. + + WinInspect Portable v0.4.4 stages its binaries under App/WinInspect, + whereas older installations use a flat directory. An explicit + WINEBOT_WININSPECT_DIR may point to either layout. Fail closed if neither + contains both required executables; never scan other installed programs. + """ + root = Path(os.getenv("WINEBOT_WININSPECT_DIR", "").strip() or WININSPECT_DEFAULT_DIR) + for candidate in (root, root / "App" / "WinInspect"): + if all((candidate / name).is_file() for name in WININSPECT_REQUIRED_FILES): + return candidate + return root def daemon_exe() -> Path: @@ -172,7 +186,17 @@ def ensure_daemon(start: bool = True) -> dict[str, Any]: log_file = open(_log_path(), "ab") try: proc = subprocess.Popen( - ["wine", str(daemon_exe())], + [ + "wine", str(daemon_exe()), + "--no-config", + "--bind", DEFAULT_HOST, + "--ipv4", + "--port", str(port()), + "--no-discovery", + "--no-mdns", + "--headless", + "--read-only", + ], stdout=log_file, stderr=subprocess.STDOUT, start_new_session=True, @@ -276,8 +300,8 @@ def request(method: str, params: dict[str, Any] | None = None) -> dict[str, Any] "id": request_id, "method": method, "params": { - "protocol_version": "0.4.0", **(params or {}), + "protocol_version": WININSPECT_PROTOCOL_VERSION, }, } with socket.create_connection((host(), port()), timeout=timeout_seconds()) as sock: 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/docs/rdte-wine-ui-three-audience-execution-20261023.md b/docs/rdte-wine-ui-three-audience-execution-20261023.md new file mode 100644 index 00000000..71a0aa6a --- /dev/null +++ b/docs/rdte-wine-ui-three-audience-execution-20261023.md @@ -0,0 +1,54 @@ +# WineBot Windows application qualification work plan — 2026-10-23 + +**Execution authority:** WineBot project draft PRs, security `SemperSupra/agent-dispatch-private#515` and project/portfolio handoff `SemperSupra/agent-dispatch-private#107`. This is a staged DLE (**Durable, Legible, Executable**) plan, not authorization to merge, publish, or bypass controls. + +## Observed baseline + +- Real WineBot `intent-rel` in disposable Linux CI under Xvfb/Wine: Notepad, Wine File Manager, Wine Configuration, Registry Editor all **launched with visible X11 windows and window-only screenshots** in the synthetic 96/144 DPI trials. RDTE #131: [run 39994111643](https://github.com/SemperSupra/WineBot/actions/runs/39994111643), [run 39995188180](https://github.com/SemperSupra/WineBot/actions/runs/39995188180). +- 144 DPI grayscale materially improves classic-menu/dialog legibility but may clip content in fixed-size file-manager/registry windows. At 144 DPI ClearType did not produce an observed static-font improvement under Xvfb; grayscale is the validated deterministic screenshot baseline. +- Authenticated `GET /windows` succeeds during Notepad; `GET /wininspect/capabilities` and `GET /wininspect/windows` were unavailable. Container diagnostic: WinInspect enabled but expected **flat-root** `wininspectd.exe` and `wininspect.exe` missing. Release `v0.4.4` build script stages binaries under **`App/WinInspect/`**; WineBot unzips its verified package under `/opt/winebot/windows-tools/WinSpy`. Last runtime evidence: [run 39997099944](https://github.com/SemperSupra/WineBot/actions/runs/39997099944). +- Production main still pins missing WinInspect `v0.4.0`; distinct draft **#124** fixes the verified package download to `v0.4.4`. Draft **#125** suppresses automatic BuildKit uploads, **#127** minimizes public conformance reports/console payloads, **#129** distinguishes source from tested checkout. All remain separate and gated. Legacy v1 conformance **54 pass / 8 fail / 9 skip** remains red under **#123** contract-policy review. + +## Dependency-aware execution + +### READY A — exact executable path and semantic startup, independent of graphics research + +1. Preserve flat-install compatibility, discover the **complete** nested `App/WinInspect` directory when both daemon and CLI are present; honor explicit env path and fail closed for incomplete or unrelated tool directories. +2. Add positive/negative synthetic path tests and include them in normal unit lane (prior `test_wininspect.py` is not run by the default unit script and has stale protocol assertions; fix those independently). +3. Qualify with a **disposable public** WineBot release-intent image using the previously verified, unmerged safe image/build composition from closed #130. Do not merge security drafts just to test. +4. Launch synthetic Notepad, probe `/windows`, `/health/wininspect`, `/wininspect/capabilities`, and `/wininspect/windows` via read-only authenticated API calls, record **booleans + count classes + allowlisted component versions only**. Never upload full WinInspect responses, screenshot root or runtime process/host paths. +5. Distinguish installation, daemon readiness, transport, protocol negotiation and semantic window results. A successful build is not a semantic acceptance. Record first failure and next minimal correction; maintain draft until reviewed. + +### READY B — independent CPU software 3D / gaming + +- [Draft renderer PR #132](https://github.com/SemperSupra/WineBot/pull/132): qualification of CPU LLVMpipe GLX and Lavapipe Vulkan, SwiftShader only when a pinned ICD is explicitly admitted. Do not promote generic GPU acceleration, CV-training quality or Direct3D parity from renderer smoke. +- [Draft game PR #133](https://github.com/SemperSupra/WineBot/pull/133): bounded Windows OpenTTD 15.3/OpenGFX 8.0 executable launch. Require actual visible window; input, FPS, save/readback, screenshot correctness and sustained game performance are subsequent gates. +- Keep both branches independently qualified, record exact run/source/pinned input checksums, avoid duplicate runners/parallel execution on the same authority branch. + +### READY C — visual and audience UX specification + +- **Human:** readable `144 DPI` default candidate with DPI-aware window placement/minimum client sizes, clearly described active app/focus and observer/control holder, responsive dashboard, visible safety controls and no untrusted state optimism. +- **Assistive technology:** keyboard focus/labels and real Wine/WinInspect semantic tree to assistive clients. Do not equate successful X11 screenshot with assistive technology acceptance. +- **Automation:** pinned profile (`DPI`, resolution, smoothing, window geometry), typed application lifecycle and stable operation receipts with deterministic output hash. +- **Agents:** observe (WinInspect/Win32 and X11) → bounded plan → broker-authorized action → independent readback → durable receipt. Distinguish Linux X11 ID vs Windows HWND and note provider capability limitations. Preserve revoked/denied actions as such. +- Add *orthogonal* visual profile selector in a separately reviewed PR after experiments; don't silently mutate use-case/performance profiles. + +### WAITING D — brokered transactional WinBot app UX + +After WinInspect observation and actor/lease admission: Notepad **broker-mediated** launch, locate editor, input synthetic data, save, content readback and crop/hash verification; then File Manager navigation and Paint-like canvas case. Confirm correct lease epoch/generation, idempotency key, human handback/STOP_NOW, and independent input outcome. No direct Wine shell/xdotool or raw Python mutation may count as this gate. + +### WAITING E — CV / held-out capture training + +Private `desktop-ui-cv` draft #44's schema/validator qualifies synthetic manifests locally. Requires independent candidate inventory digest, dated pre-capture checkpoint witness, private image/data custody, explicit human review and qualified target model before actual capture/model fine-tuning. No private GitHub Actions minutes or model/cloud data spill by default. + +### WAITING F — production/release + +Independent security #515 review/approval of #125/#127/#129, packaging #124, #123 v1/vNext conformance semantics; changes must be requalified after merge ordering. Keep all experimental PRs draft/unmerged and preserve first failures, worktrees and immutable receipts. Do not prune branches or archive until source history/worktree/consumer gates are satisfied. + +## Version and proof fields required on every new app qualification run + +`source_sha`, `tested_checkout_sha`, image digest if available, image base tag, actual `wine --version`, package versions for Xvfb/Openbox/Mesa/GLX/Vulkan when probed, WinInspect release and API protocol outcome, `WINE_DPI`, smoothing, `DISPLAY` class (not host address), screenshot digest/size if publication admitted, app name+free-license provenance and exact read-only/interaction outcome. + +Public logs/artifacts may include **only software/version and safe abstract status fields**. Do not disclose hostname, hardware, CPU/GPU model, device configuration, username, IP, local paths or actual runtime window titles. Hold raw evidence job-local/private as appropriate. + +**Next baton:** execute A with exact-head local unit tests and combined public CI runtime probe; in parallel reconcile B terminal workflows and record first failures. Leave D/E/F blocked until their independently owned gates pass. 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" </dev/null 2>&1 || true +} +trap cleanup EXIT +echo "WININSPECT_IMAGE_BUILD=START" +if ! docker build --target intent-rel -f docker/Dockerfile -t winebot:uxref-rel . >/tmp/winebot-wininspect-build.log 2>&1; then + echo "WININSPECT_IMAGE_BUILD=FAIL" + exit 1 +fi +echo "WININSPECT_IMAGE_BUILD=PASS" +docker compose -f compose/docker-compose.yml --profile headless up -d --no-build winebot >/dev/null +cid="$(docker compose -f compose/docker-compose.yml ps -q winebot)" +test -n "$cid" || { echo "WINEBOT_SERVICE=ABSENT"; exit 1; } +health=unknown +for _ in $(seq 1 100); do + health="$(docker inspect -f '{{.State.Health.Status}}' "$cid" 2>/dev/null || echo absent)" + test "$health" = healthy && break + sleep 3 +done +echo "WINEBOT_SERVICE_HEALTH=$health" +test "$health" = healthy || exit 1 +docker exec -u winebot "$cid" sh -lc \ + 'mkdir -p /tmp/winebot-wininspect-qual; printf "%s\n" "WinInspect synthetic Notepad fixture" > /tmp/winebot-wininspect-qual/fixture.txt' +docker exec -d -u winebot -e DISPLAY=:99 -e WINEDEBUG=-all "$cid" \ + bash -lc 'wine notepad.exe "$(winepath -w /tmp/winebot-wininspect-qual/fixture.txt)" >/tmp/winebot-wininspect-qual/notepad.log 2>&1' +visible=false +for _ in $(seq 1 25); do + ids="$(docker exec -u winebot -e DISPLAY=:99 "$cid" xdotool search --onlyvisible --name '[Nn]otepad' 2>/dev/null || true)" + if printf '%s\n' "$ids" | grep -Eq '^[0-9]+$'; then visible=true; break; fi + sleep 1 +done +echo "WININSPECT_SYNTHETIC_NOTEPAD_X11_VISIBLE=$visible" +docker exec -i -u winebot -e API_TOKEN="$API_TOKEN" "$cid" python3 - <<'PY' +import json, os, re, subprocess, urllib.error, urllib.request +from pathlib import Path +from api.core import wininspect as wi +def boolean(v): + return str(bool(v)).lower() +def get(path): + req=urllib.request.Request("http://127.0.0.1:8000"+path, + headers={"X-API-Key":os.environ["API_TOKEN"]}) + try: + with urllib.request.urlopen(req, timeout=24) as resp: + return resp.status, json.load(resp) + except urllib.error.HTTPError as ex: + return ex.code, None + except Exception: + return 0, None +default_root=Path("/opt/winebot/windows-tools/WinSpy") +nested=default_root/"App"/"WinInspect" +nested_complete=all((nested/name).is_file() for name in wi.WININSPECT_REQUIRED_FILES) +flat_complete=all((default_root/name).is_file() for name in wi.WININSPECT_REQUIRED_FILES) +print("WININSPECT_NESTED_COMPLETE="+boolean(nested_complete)) +print("WININSPECT_LEGACY_FLAT_COMPLETE="+boolean(flat_complete)) +print("WININSPECT_RESOLVED_COMPLETE="+boolean(wi.installed())) +x_status,windows=get("/windows") +c_status,capabilities=get("/wininspect/capabilities") +w_status,semantic=get("/wininspect/windows?include_info=false") +h_status,health=get("/health/wininspect") +print("WININSPECT_CAPABILITIES_HTTP_STATUS="+str(c_status)) +print("WININSPECT_WINDOWS_HTTP_STATUS="+str(w_status)) +# Only whitelisted diagnostic categories cross the public boundary. Never +# emit raw response JSON, WinInspect hello fields, window titles or exception text. +def rpc_diagnostic(): + try: + wi.request("daemon.capabilities") + return "rpc_success" + except Exception as exc: + message=str(exc).lower() + if "e_protocol_version" in message or "expected 0.3.0" in message: + return "protocol_version_rejected" + if "authentication required" in message or "unauthorized" in message: + return "rpc_unauthorized" + if "bad method" in message or "method not implemented" in message: + return "method_unsupported" + if "unexpected wininspect response id" in message: + return "response_id_mismatch" + if "invalid wininspect json" in message or "frame too large" in message: + return "response_framing" + if "connection closed while reading frame" in message: + return "connection_closed" + if "timed out" in message or "timeout" in message: + return "timeout" + if "read-only mode" in message: + return "read_only_refusal" + return "other_redacted" +print("WININSPECT_RPC_DIAGNOSTIC="+rpc_diagnostic()) +def klass(items): + if not isinstance(items,list):return "unavailable" + if len(items)==0:return "zero" + if len(items)==1:return "one" + return "two-plus" +print("X11_WINDOWS_API_OK="+boolean(x_status==200)) +print("WININSPECT_CAPABILITIES_API_OK="+boolean(c_status==200)) +print("WININSPECT_WINDOWS_API_OK="+boolean(w_status==200)) +print("WININSPECT_HEALTH_API_OK="+boolean(h_status==200)) +print("X11_WINDOW_COUNT_CLASS="+klass(windows.get("windows") if isinstance(windows,dict) else None)) +print("WININSPECT_WINDOW_COUNT_CLASS="+klass(semantic.get("windows") if isinstance(semantic,dict) else None)) +state=wi.ensure_daemon(start=False) +print("WININSPECT_TCP_READY="+boolean(wi._tcp_ready())) +print("WININSPECT_DAEMON_RUNNING="+boolean(state.get("running"))) +def version(command): + try: + r=subprocess.run(command,timeout=7,capture_output=True,text=True,check=False) + lines=r.stdout.strip().splitlines() + value=lines[0].strip()[:100] if r.returncode==0 and lines else "" + if re.fullmatch(r"[A-Za-z0-9.+_~:() -]{1,100}",value): + return value.replace(" ","_") + except Exception: + pass + return "unavailable" +print("WINE_EXECUTABLE_VERSION="+version(["wine","--version"])) +for package,key in (("wine","WINE_DEBIAN_VERSION"),("xvfb","XVFB_DEBIAN_VERSION"), + ("openbox","OPENBOX_DEBIAN_VERSION"), + ("libgl1-mesa-dri","MESA_DRI_VERSION"), + ("mesa-vulkan-drivers","MESA_VULKAN_VERSION")): + print(key+"="+version(["dpkg-query","-W","-f=$"+"{Version}",package])) +ok=bool(wi.installed() and wi._tcp_ready() and c_status==200 and w_status==200) +print("WININSPECT_SEMANTIC_QUALIFICATION="+("PASS" if ok else "UNQUALIFIED")) +raise SystemExit(0 if ok else 1) +PY 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/scripts/ci/test.sh b/scripts/ci/test.sh index 572871e1..d2f81dde 100755 --- a/scripts/ci/test.sh +++ b/scripts/ci/test.sh @@ -22,4 +22,7 @@ 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_wininspect_portable_layout.py \ + tests/test_wininspect_loopback.py \ + tests/test_wininspect_rpc_version.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 diff --git a/tests/test_wininspect_loopback.py b/tests/test_wininspect_loopback.py new file mode 100644 index 00000000..3774be5d --- /dev/null +++ b/tests/test_wininspect_loopback.py @@ -0,0 +1,56 @@ +"""WinInspect daemon must be local-only and non-mutating until broker-qualified.""" + +from unittest.mock import MagicMock, patch + +from api.core import wininspect as wi + + +def test_daemon_spawn_is_explicit_loopback_and_read_only(tmp_path): + proc = MagicMock() + proc.pid = 1234 + proc.poll.return_value = None + with ( + patch.object(wi, "enabled", return_value=True), + patch.object(wi, "installed", return_value=True), + patch.object(wi, "_tcp_ready", side_effect=[False, False, True]), + patch.object(wi, "_log_path", return_value=str(tmp_path / "local-daemon.log")), + patch.object(wi, "manage_process"), + patch.object(wi.subprocess, "Popen", return_value=proc) as spawn, + ): + result = wi.ensure_daemon(start=True) + assert result["running"] is True + assert result["started"] is True + args = spawn.call_args.args[0] + assert args[:2] == ["wine", str(wi.daemon_exe())] + for flag in ("--no-config", "--ipv4", "--no-discovery", "--no-mdns", "--headless", "--read-only"): + assert flag in args + assert args[args.index("--bind") + 1] == "127.0.0.1" + assert args[args.index("--port") + 1] == str(wi.port()) + assert "0.0.0.0" not in args + assert "::" not in args + assert spawn.call_args.kwargs["start_new_session"] is True + + +def test_not_installed_never_attempts_process_spawn(): + with ( + patch.object(wi, "enabled", return_value=True), + patch.object(wi, "installed", return_value=False), + patch.object(wi.subprocess, "Popen") as spawn, + ): + result = wi.ensure_daemon(start=True) + assert result["installed"] is False + assert result["running"] is False + spawn.assert_not_called() + + +def test_read_only_state_probe_never_spawns_daemon(): + with ( + patch.object(wi, "enabled", return_value=True), + patch.object(wi, "installed", return_value=True), + patch.object(wi, "_tcp_ready", return_value=False), + patch.object(wi, "_process_running", return_value=False), + patch.object(wi.subprocess, "Popen") as spawn, + ): + result = wi.ensure_daemon(start=False) + assert result["running"] is False + spawn.assert_not_called() diff --git a/tests/test_wininspect_portable_layout.py b/tests/test_wininspect_portable_layout.py new file mode 100644 index 00000000..6322028e --- /dev/null +++ b/tests/test_wininspect_portable_layout.py @@ -0,0 +1,74 @@ +"""WinInspect PortableApps/legacy executable discovery, synthetic only.""" + +from pathlib import Path + +from api.core import wininspect + + +def _binaries(directory: Path, *filenames: str) -> None: + directory.mkdir(parents=True, exist_ok=True) + for name in filenames: + (directory / name).write_bytes(b"synthetic executable placeholder") + + +def test_portable_v044_nested_layout(monkeypatch, tmp_path): + root = tmp_path / "WinSpy" + nested = root / "App" / "WinInspect" + _binaries(nested, "wininspectd.exe", "wininspect.exe", "wininspect-gui.exe") + monkeypatch.setenv("WINEBOT_WININSPECT_DIR", str(root)) + assert wininspect.tool_dir() == nested + assert wininspect.daemon_exe() == nested / "wininspectd.exe" + assert wininspect.cli_exe() == nested / "wininspect.exe" + assert wininspect.gui_exe() == nested / "wininspect-gui.exe" + assert wininspect.installed() is True + + +def test_flat_legacy_layout_has_priority(monkeypatch, tmp_path): + root = tmp_path / "WinSpy" + _binaries(root, "wininspectd.exe", "wininspect.exe") + _binaries(root / "App" / "WinInspect", "wininspectd.exe", "wininspect.exe") + monkeypatch.setenv("WINEBOT_WININSPECT_DIR", str(root)) + assert wininspect.tool_dir() == root + assert wininspect.installed() is True + + +def test_explicit_nested_directory(monkeypatch, tmp_path): + nested = tmp_path / "Portable" / "App" / "WinInspect" + _binaries(nested, "wininspectd.exe", "wininspect.exe") + monkeypatch.setenv("WINEBOT_WININSPECT_DIR", str(nested)) + assert wininspect.tool_dir() == nested + assert wininspect.installed() is True + + +def test_incomplete_install_cannot_mix_executables(monkeypatch, tmp_path): + root = tmp_path / "WinSpy" + _binaries(root, "wininspectd.exe") + _binaries(root / "App" / "WinInspect", "wininspect.exe") + monkeypatch.setenv("WINEBOT_WININSPECT_DIR", str(root)) + assert wininspect.tool_dir() == root + assert wininspect.installed() is False + + +def test_unrelated_neighbor_directory_not_scanned(monkeypatch, tmp_path): + root = tmp_path / "WinSpy" + _binaries(tmp_path / "OtherTool", "wininspectd.exe", "wininspect.exe") + monkeypatch.setenv("WINEBOT_WININSPECT_DIR", str(root)) + assert wininspect.tool_dir() == root + assert wininspect.installed() is False + + +def test_missing_custom_root_does_not_fallback_to_default(monkeypatch, tmp_path): + root = tmp_path / "custom-missing" + monkeypatch.setenv("WINEBOT_WININSPECT_DIR", str(root)) + assert wininspect.tool_dir() == root + assert wininspect.installed() is False + + +def test_nested_without_optional_gui_still_installed(monkeypatch, tmp_path): + root = tmp_path / "WinSpy" + nested = root / "App" / "WinInspect" + _binaries(nested, "wininspectd.exe", "wininspect.exe") + monkeypatch.setenv("WINEBOT_WININSPECT_DIR", str(root)) + assert wininspect.installed() is True + assert wininspect.gui_exe() == nested / "wininspect-gui.exe" + assert wininspect.gui_exe().is_file() is False diff --git a/tests/test_wininspect_rpc_version.py b/tests/test_wininspect_rpc_version.py new file mode 100644 index 00000000..16079103 --- /dev/null +++ b/tests/test_wininspect_rpc_version.py @@ -0,0 +1,81 @@ +"""Pinned WinInspect v0.4.4 RPC protocol compatibility, synthetic-only.""" + +import json +import struct +from unittest.mock import patch + +import pytest + +from api.core import wininspect + + +class FakeSocket: + def __init__(self, responses): + self.recv_bytes = bytearray() + self.sent = bytearray() + for response in responses: + raw = json.dumps(response).encode("utf-8") + self.recv_bytes.extend(struct.pack("!I", len(raw)) + raw) + + def recv(self, length): + chunk = self.recv_bytes[:length] + del self.recv_bytes[:length] + return bytes(chunk) + + def sendall(self, data): + self.sent.extend(data) + + def settimeout(self, _timeout): + pass + + def __enter__(self): + return self + + def __exit__(self, *_args): + return False + + +def _invoke(response, params=None): + sock = FakeSocket([{"type": "hello", "version": "0.3.0"}, response]) + with ( + patch.object(wininspect, "ensure_daemon", return_value={"running": True}), + patch.object(wininspect.uuid, "uuid4") as uid, + patch.object(wininspect.socket, "create_connection", return_value=sock), + ): + uid.return_value.hex = "abc123456789abcdef" + if response["ok"]: + outcome = wininspect.request("daemon.capabilities", params) + else: + with pytest.raises(wininspect.WinInspectError, match="expected 0.3.0"): + wininspect.request("daemon.capabilities", params) + outcome = None + length = struct.unpack("!I", sock.sent[:4])[0] + return outcome, json.loads(sock.sent[4:4 + length]) + + +def test_release_v044_uses_rpc_v030_in_params(): + result, wire = _invoke({ + "id": "winebot-abc123456789", "ok": True, + "result": {"features": {"ui": True}}, + }) + assert wininspect.WININSPECT_PROTOCOL_VERSION == "0.3.0" + assert wire["params"]["protocol_version"] == "0.3.0" + assert "protocol_version" not in {k: v for k, v in wire.items() if k != "params"} + assert result["result"]["features"]["ui"] is True + + +def test_rpc_version_cannot_be_overridden_by_caller_params(): + _, wire = _invoke({ + "id": "winebot-abc123456789", "ok": True, + "result": {}, + }, {"protocol_version": "0.4.0", "title_regex": "synthetic"}) + assert wire["params"]["protocol_version"] == "0.3.0" + assert wire["params"]["title_regex"] == "synthetic" + + +def test_server_version_error_fails_closed(): + _, wire = _invoke({ + "id": "winebot-abc123456789", "ok": False, + "error": {"code": "E_PROTOCOL_VERSION", "message": "expected 0.3.0, got 0.4.0"}, + }) + assert wire["params"]["protocol_version"] == "0.3.0"