Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
ci(cua-driver): resume private evidence downloads by artifact digest (#4043)
Francesco Bonacci912a4550b72a
diff --git a/.github/workflows/ci-test-scripts.yml b/.github/workflows/ci-test-scripts.ymlindex 1108e350d6..0126eac944 100644--- a/.github/workflows/ci-test-scripts.yml+++ b/.github/workflows/ci-test-scripts.yml@@ -80,7 +80,7 @@ jobs:- name: Install dependenciesrun: |python -m pip install --upgrade pip- pip install jsonschema pyyaml pytest toml+ pip install cryptography jsonschema pyyaml pytest toml- name: Run testsrun: |@@ -90,6 +90,12 @@ jobs:- name: Test Cua Driver uninstall scriptsrun: python -m pytest libs/cua-driver/scripts/tests/ -v+ - name: Test private evidence cache and envelope contracts+ run: |+ python -m pytest \+ libs/cua-driver/tests/perception-demo/test_cache_evidence.py \+ libs/cua-driver/tests/perception-demo/test_evidence_envelope.py -v+- uses: actions/setup-node@v4with:node-version: "22"diff --git a/libs/cua-driver/tests/perception-demo/README.md b/libs/cua-driver/tests/perception-demo/README.mdindex 8bf01c3dbf..1a3052975e 100644--- a/libs/cua-driver/tests/perception-demo/README.md+++ b/libs/cua-driver/tests/perception-demo/README.md@@ -106,6 +106,38 @@ keep raw, mock, and validated plaintext evidence beneath the runner's temporarydirectory and remove those exact directories in an `always()` step after theupload step.+### Resume private collection without rerunning the desktop test++If an artifact transfer or a local reel render fails after a successful live+run, cache the encrypted Actions artifact by its immutable ID. First verify+the run ID, workflow path, source SHA, artifact ID, and artifact name against+the reviewed certification record. In a private, mode-0700 directory, run:++```bash+python3 libs/cua-driver/tests/perception-demo/cache_evidence.py fetch \+ --run-id RUN_ID --artifact-id ARTIFACT_ID --source-sha SOURCE_SHA \+ --workflow .github/workflows/authorized-live-jev-use-demo.yml \+ --name ARTIFACT_NAME --cache PRIVATE_CACHE+python3 libs/cua-driver/tests/perception-demo/cache_evidence.py stage \+ --run-id RUN_ID --artifact-id ARTIFACT_ID --source-sha SOURCE_SHA \+ --workflow .github/workflows/authorized-live-jev-use-demo.yml \+ --name ARTIFACT_NAME --cache PRIVATE_CACHE --output PRIVATE_STAGE+```++Use the producer's actual workflow path for each platform. `fetch` checks the+completed GitHub run and artifact producer on every invocation and verifies+GitHub's SHA-256 artifact ZIP digest. A retry reuses verified encrypted bytes+without a second download. `stage` verifies the same identity and digest again,+then extracts only the two ciphertext envelopes into a new private directory.+An interrupted transfer is not cached; an interrupted metadata write can+recover a complete, digest-matching ZIP. Neither command decrypts or certifies+the evidence. Keep the private key outside GitHub, decrypt into a separate+private directory with `evidence_envelope.py`, and validate each plaintext+manifest, recording, provider SHA, and exact candidate SHA before editing or+rendering. If the test failed, the artifact expired, or the candidate changed+in a way that requires recertification, a cached download is not a substitute+for a new run. Do not attach the cache, staged envelopes, or plaintext to a PR.+Native macOS certification remains separate from the Windows/Linux live-providerworkflow. This proof runs directly in a logged-in, TCC-authorized Lume guest. A maintainerdispatches `.github/workflows/e2e-rust-macos.yml` in `lume` mode, whose exact-SHA gate runsdiff --git a/libs/cua-driver/tests/perception-demo/cache_evidence.py b/libs/cua-driver/tests/perception-demo/cache_evidence.pynew file mode 100644index 0000000000..d138fd5801--- /dev/null+++ b/libs/cua-driver/tests/perception-demo/cache_evidence.py@@ -0,0 +1,246 @@+#!/usr/bin/env python3+"""Cache exact-run encrypted evidence for retryable local validation and rendering.++This tool does not certify a run or decrypt evidence. It pins a GitHub artifact's+ZIP digest and admits only the two encrypted evidence envelopes.+"""++from __future__ import annotations++import argparse+import hashlib+import json+import os+from pathlib import Path+import re+import shutil+import stat+import subprocess+import sys+import tempfile+import zipfile++from evidence_envelope import _rename_directory_no_replace+++REPO = "trycua/cua"+MEMBERS = ("primary-desktop.cuae", "window.cuae")+SHA = re.compile(r"[0-9a-f]{40}\Z")+DIGEST = re.compile(r"sha256:[0-9a-f]{64}\Z")+WORKFLOW = re.compile(r"\.github/workflows/[A-Za-z0-9_.-]+\.yml\Z")+MAX_ARCHIVE = 220 * 1024 * 1024+MAX_ENVELOPE = 101 * 1024 * 1024+++def require(condition: bool, message: str) -> None:+ if not condition:+ raise ValueError(message)+++def private_directory(path: Path) -> None:+ if not path.exists() and not path.is_symlink():+ path.mkdir(mode=0o700)+ mode = path.lstat().st_mode+ require(stat.S_ISDIR(mode) and not path.is_symlink(), "cache must be a real directory")+ require(mode & 0o077 == 0, "cache directory must not be accessible to group or others")+++def private_file(path: Path, label: str) -> None:+ mode = path.lstat().st_mode+ require(stat.S_ISREG(mode) and not path.is_symlink(), f"{label} must be a regular file")+ require(mode & 0o077 == 0, f"{label} must not be accessible to group or others")+++def gh_json(endpoint: str) -> dict:+ result = subprocess.run(["gh", "api", endpoint], check=True, capture_output=True, text=True)+ value = json.loads(result.stdout)+ require(isinstance(value, dict), "GitHub returned invalid metadata")+ return value+++def identity(run_id: int, artifact_id: int, source_sha: str, workflow: str, name: str) -> dict:+ require(run_id > 0 and artifact_id > 0, "run and artifact IDs must be positive")+ require(SHA.fullmatch(source_sha) is not None, "source SHA must be 40 lowercase hex characters")+ require(WORKFLOW.fullmatch(workflow) is not None, "workflow must be a repository workflow path")+ require(bool(name) and len(name) <= 128 and re.fullmatch(r"[A-Za-z0-9._-]+", name), "invalid artifact name")+ run = gh_json(f"repos/{REPO}/actions/runs/{run_id}")+ require(run.get("id") == run_id and run.get("head_sha") == source_sha, "run source identity mismatch")+ require((run.get("repository") or {}).get("full_name") == REPO, "run repository mismatch")+ require(run.get("path") == workflow, "run workflow identity mismatch")+ require((run.get("status"), run.get("conclusion")) == ("completed", "success"), "run is not a completed success")+ artifact = gh_json(f"repos/{REPO}/actions/artifacts/{artifact_id}")+ producer = artifact.get("workflow_run") or {}+ require(artifact.get("id") == artifact_id and artifact.get("name") == name, "artifact identity mismatch")+ require(artifact.get("expired") is False, "artifact has expired")+ require(producer.get("id") == run_id and producer.get("head_sha") == source_sha, "artifact producer mismatch")+ require(producer.get("repository_id") == run["repository"].get("id"), "artifact repository mismatch")+ digest = artifact.get("digest")+ require(isinstance(digest, str) and DIGEST.fullmatch(digest) is not None, "artifact has no SHA-256 digest")+ return {+ "schema": "cua-encrypted-evidence-cache/v1",+ "repository": REPO,+ "run_id": run_id,+ "artifact_id": artifact_id,+ "source_sha": source_sha,+ "workflow": workflow,+ "name": name,+ "archive_digest": digest,+ }+++def archive_digest(path: Path) -> str:+ private_file(path, "cached archive")+ require(0 < path.stat().st_size <= MAX_ARCHIVE, "cached archive size is invalid")+ digest = hashlib.sha256()+ with path.open("rb") as handle:+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):+ digest.update(chunk)+ return "sha256:" + digest.hexdigest()+++def inspect_archive(path: Path) -> None:+ try:+ with zipfile.ZipFile(path) as archive:+ infos = archive.infolist()+ require(sorted(info.filename for info in infos) == list(MEMBERS), "archive must contain only encrypted evidence envelopes")+ for info in infos:+ require(not info.is_dir() and not info.flag_bits & 1, "archive has an unsupported member")+ require(0 < info.file_size <= MAX_ENVELOPE, "encrypted evidence size is invalid")+ require((info.external_attr >> 16) & 0o170000 != stat.S_IFLNK, "archive contains a link")+ with archive.open(info) as handle:+ require(handle.read(8) == b"CUAEVID\x00", "archive member is not an evidence envelope")+ while handle.read(1024 * 1024):+ pass # Check CRC before caching or staging.+ except (zipfile.BadZipFile, RuntimeError) as error:+ raise ValueError("archive is invalid") from error+++def paths(cache: Path, artifact_id: int) -> tuple[Path, Path]:+ return cache / f"artifact-{artifact_id}.zip", cache / f"artifact-{artifact_id}.json"+++def read_cached(cache: Path, expected: dict) -> Path:+ archive, metadata = paths(cache, expected["artifact_id"])+ private_file(metadata, "cache metadata")+ require(json.loads(metadata.read_text(encoding="utf-8")) == expected, "cached artifact identity changed")+ require(archive_digest(archive) == expected["archive_digest"], "cached archive digest mismatch")+ inspect_archive(archive)+ return archive+++def publish_metadata(cache: Path, metadata: Path, expected: dict) -> None:+ with tempfile.NamedTemporaryFile(dir=cache, prefix=".identity-", mode="w", encoding="utf-8", delete=False) as handle:+ temporary = Path(handle.name)+ try:+ os.chmod(temporary, 0o600)+ json.dump(expected, handle, sort_keys=True)+ handle.write("\n")+ handle.flush()+ os.fsync(handle.fileno())+ try:+ os.link(temporary, metadata)+ except FileExistsError:+ # Another invocation may have finished the same immutable artifact.+ private_file(metadata, "cache metadata")+ require(json.loads(metadata.read_text(encoding="utf-8")) == expected, "cached artifact identity changed")+ finally:+ temporary.unlink(missing_ok=True)+++def fetch(cache: Path, expected: dict) -> Path:+ private_directory(cache)+ archive, metadata = paths(cache, expected["artifact_id"])+ if metadata.exists() or metadata.is_symlink():+ return read_cached(cache, expected)+ if archive.exists() or archive.is_symlink():+ # Recover a fully published ZIP after an interruption before metadata.+ require(archive_digest(archive) == expected["archive_digest"], "cached archive digest mismatch")+ inspect_archive(archive)+ publish_metadata(cache, metadata, expected)+ return read_cached(cache, expected)+ temporary: Path | None = None+ try:+ with tempfile.NamedTemporaryFile(dir=cache, prefix=".evidence-", delete=False) as handle:+ temporary = Path(handle.name)+ os.chmod(temporary, 0o600)+ with subprocess.Popen(+ ["gh", "api", f"repos/{REPO}/actions/artifacts/{expected['artifact_id']}/zip"],+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,+ ) as process:+ assert process.stdout is not None+ try:+ for chunk in iter(lambda: process.stdout.read(1024 * 1024), b""):+ require(handle.tell() + len(chunk) <= MAX_ARCHIVE, "downloaded archive is too large")+ handle.write(chunk)+ except (OSError, ValueError):+ process.kill()+ raise+ require(process.wait() == 0, "artifact download failed")+ handle.flush()+ os.fsync(handle.fileno())+ require(archive_digest(temporary) == expected["archive_digest"], "downloaded archive digest mismatch")+ inspect_archive(temporary)+ try:+ os.link(temporary, archive) # Do not overwrite a concurrent or earlier download.+ except FileExistsError:+ require(archive_digest(archive) == expected["archive_digest"], "cached archive digest mismatch")+ inspect_archive(archive)+ publish_metadata(cache, metadata, expected)+ return read_cached(cache, expected)+ finally:+ if temporary is not None:+ temporary.unlink(missing_ok=True)+++def stage(archive: Path, destination: Path, expected_digest: str) -> None:+ require(not destination.exists() and not destination.is_symlink(), "output directory already exists")+ private_directory(destination.parent)+ require(archive_digest(archive) == expected_digest, "cached archive digest mismatch")+ inspect_archive(archive)+ temporary = Path(tempfile.mkdtemp(dir=destination.parent, prefix=".stage-"))+ try:+ with zipfile.ZipFile(archive) as source:+ for name in MEMBERS:+ target = temporary / name+ with source.open(name) as content, target.open("xb") as output:+ shutil.copyfileobj(content, output)+ os.chmod(target, 0o600)+ require(archive_digest(archive) == expected_digest, "cached archive changed during staging")+ # Directory rename must not replace an existing (possibly concurrent) stage.+ require(not destination.exists() and not destination.is_symlink(), "output directory already exists")+ _rename_directory_no_replace(temporary, destination)+ finally:+ if temporary.exists():+ for name in MEMBERS:+ (temporary / name).unlink(missing_ok=True)+ temporary.rmdir()+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("command", choices=("fetch", "stage"))+ parser.add_argument("--run-id", type=int, required=True)+ parser.add_argument("--artifact-id", type=int, required=True)+ parser.add_argument("--source-sha", required=True)+ parser.add_argument("--workflow", required=True)+ parser.add_argument("--name", required=True)+ parser.add_argument("--cache", type=Path, required=True)+ parser.add_argument("--output", type=Path, help="private directory for encrypted envelopes (stage only)")+ args = parser.parse_args()+ require((args.command == "stage") == (args.output is not None), "--output is required only for stage")+ expected = identity(args.run_id, args.artifact_id, args.source_sha, args.workflow, args.name)+ if args.command == "fetch":+ fetch(args.cache, expected)+ else:+ private_directory(args.cache)+ stage(read_cached(args.cache, expected), args.output, expected["archive_digest"])+ print(json.dumps({"status": args.command, "source_sha": args.source_sha, "run_id": args.run_id, "artifact_id": args.artifact_id}))+ return 0+++if __name__ == "__main__":+ try:+ raise SystemExit(main())+ except (OSError, ValueError, subprocess.CalledProcessError, json.JSONDecodeError) as error:+ print(f"evidence cache: {error}", file=sys.stderr)+ raise SystemExit(2)diff --git a/libs/cua-driver/tests/perception-demo/test_cache_evidence.py b/libs/cua-driver/tests/perception-demo/test_cache_evidence.pynew file mode 100644index 0000000000..59d4782bc4--- /dev/null+++ b/libs/cua-driver/tests/perception-demo/test_cache_evidence.py@@ -0,0 +1,222 @@+"""Offline exact-identity and private encrypted-cache regression tests."""++import hashlib+import importlib.util+from io import BytesIO+import json+from pathlib import Path+import sys+import tempfile+import unittest+from unittest import mock+import zipfile+++HERE = Path(__file__).parent+sys.path.insert(0, str(HERE))+SPEC = importlib.util.spec_from_file_location("cache_evidence", HERE / "cache_evidence.py")+cache = importlib.util.module_from_spec(SPEC)+assert SPEC.loader is not None+SPEC.loader.exec_module(cache)+++class EvidenceCacheTests(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.root = Path(self.temporary.name)+ self.cache = self.root / "cache"+ self.run_id = 42+ self.artifact_id = 91+ self.sha = "a" * 40+ self.workflow = ".github/workflows/authorized-live-jev-use-demo.yml"+ self.name = "encrypted-evidence"+ output = BytesIO()+ with zipfile.ZipFile(output, "w") as archive:+ for name in cache.MEMBERS:+ archive.writestr(name, b"CUAEVID\x00" + name.encode())+ self.data = output.getvalue()+ self.expected = {+ "schema": "cua-encrypted-evidence-cache/v1", "repository": cache.REPO,+ "run_id": self.run_id, "artifact_id": self.artifact_id,+ "source_sha": self.sha, "workflow": self.workflow, "name": self.name,+ "archive_digest": "sha256:" + hashlib.sha256(self.data).hexdigest(),+ }++ def remote(self, *, run=None, artifact=None):+ run = run or {+ "id": self.run_id, "head_sha": self.sha, "path": self.workflow,+ "repository": {"full_name": cache.REPO, "id": 8},+ "status": "completed", "conclusion": "success",+ }+ artifact = artifact or {+ "id": self.artifact_id, "name": self.name, "expired": False,+ "workflow_run": {"id": self.run_id, "head_sha": self.sha, "repository_id": 8},+ "digest": self.expected["archive_digest"],+ }+ return mock.patch.object(cache, "gh_json", side_effect=[run, artifact])++ def test_identity_checks_run_and_immutable_artifact(self):+ with self.remote():+ self.assertEqual(cache.identity(self.run_id, self.artifact_id, self.sha, self.workflow, self.name), self.expected)+ for change, label in (+ ({"head_sha": "b" * 40}, "source"),+ ({"status": "in_progress"}, "completed"),+ ({"path": ".github/workflows/other.yml"}, "workflow"),+ ({"repository": {"full_name": "someone/else", "id": 8}}, "repository"),+ ):+ with self.subTest(change=change), self.remote(run={+ "id": self.run_id, "head_sha": self.sha, "path": self.workflow,+ "repository": {"full_name": cache.REPO, "id": 8},+ "status": "completed", "conclusion": "success", **change,+ }):+ with self.assertRaisesRegex(ValueError, label):+ cache.identity(self.run_id, self.artifact_id, self.sha, self.workflow, self.name)+ for change, label in (+ ({"digest": None}, "digest"),+ ({"expired": True}, "expired"),+ ({"workflow_run": {"id": 43, "head_sha": self.sha, "repository_id": 8}}, "producer"),+ ):+ with self.subTest(change=change), self.remote(artifact={+ "id": self.artifact_id, "name": self.name, "expired": False,+ "workflow_run": {"id": self.run_id, "head_sha": self.sha, "repository_id": 8},+ "digest": self.expected["archive_digest"], **change,+ }):+ with self.assertRaisesRegex(ValueError, label):+ cache.identity(self.run_id, self.artifact_id, self.sha, self.workflow, self.name)++ def write_cached(self):+ self.cache.mkdir(mode=0o700)+ archive, metadata = cache.paths(self.cache, self.artifact_id)+ archive.write_bytes(self.data)+ metadata.write_text(json.dumps(self.expected), encoding="utf-8")+ archive.chmod(0o600)+ metadata.chmod(0o600)+ return archive, metadata++ def test_validated_cache_can_be_staged_without_retransfer_or_plaintext(self):+ archive, _ = self.write_cached()+ with mock.patch.object(cache, "subprocess") as process:+ self.assertEqual(cache.fetch(self.cache, self.expected), archive)+ process.assert_not_called()+ destination = self.root / "stage"+ cache.stage(cache.read_cached(self.cache, self.expected), destination, self.expected["archive_digest"])+ self.assertEqual(sorted(item.name for item in destination.iterdir()), list(cache.MEMBERS))+ self.assertEqual((destination / "window.cuae").read_bytes(), b"CUAEVID\x00window.cuae")+ with self.assertRaisesRegex(ValueError, "already exists"):+ cache.stage(archive, destination, self.expected["archive_digest"])++ def test_recovers_complete_archive_after_interrupted_metadata_write(self):+ archive, metadata = self.write_cached()+ metadata.unlink()+ with mock.patch.object(cache, "subprocess") as process:+ self.assertEqual(cache.fetch(self.cache, self.expected), archive)+ process.assert_not_called()+ self.assertEqual(json.loads(metadata.read_text(encoding="utf-8")), self.expected)++ def test_fetch_streams_verified_archive_once_then_reuses_it(self):+ self.cache.mkdir(mode=0o700)++ class Download:+ def __init__(self, payload):+ self.stdout = BytesIO(payload)++ def __enter__(self):+ return self++ def __exit__(self, *_):+ return False++ def wait(self):+ return 0++ def kill(self):+ raise AssertionError("valid download must not be terminated")++ with mock.patch.object(cache.subprocess, "Popen", return_value=Download(self.data)) as download:+ archive = cache.fetch(self.cache, self.expected)+ self.assertEqual(archive.read_bytes(), self.data)+ self.assertEqual(cache.fetch(self.cache, self.expected), archive)+ download.assert_called_once()+ self.assertEqual(json.loads(cache.paths(self.cache, self.artifact_id)[1].read_text()), self.expected)++ def test_failed_download_never_publishes_an_archive(self):+ self.cache.mkdir(mode=0o700)++ class Download:+ stdout = BytesIO(b"partial")++ def __enter__(self):+ return self++ def __exit__(self, *_):+ return False++ def wait(self):+ return 1++ def kill(self):+ raise AssertionError("completed failed download is not killed")++ with mock.patch.object(cache.subprocess, "Popen", return_value=Download()):+ with self.assertRaisesRegex(ValueError, "download failed"):+ cache.fetch(self.cache, self.expected)+ self.assertFalse(any(self.cache.iterdir()))++ def test_interrupted_archive_with_wrong_digest_cannot_be_recovered(self):+ archive, metadata = self.write_cached()+ metadata.unlink()+ archive.write_bytes(b"incomplete")+ with self.assertRaisesRegex(ValueError, "digest mismatch"):+ cache.fetch(self.cache, self.expected)+ self.assertFalse(metadata.exists())++ def test_tampering_and_foreign_identity_cannot_be_reused(self):+ archive, metadata = self.write_cached()+ with self.assertRaisesRegex(ValueError, "identity changed"):+ cache.read_cached(self.cache, {**self.expected, "source_sha": "b" * 40})+ archive.write_bytes(self.data + b"altered")+ with self.assertRaisesRegex(ValueError, "digest mismatch"):+ cache.read_cached(self.cache, self.expected)+ archive.write_bytes(self.data)+ archive.chmod(0o644)+ with self.assertRaisesRegex(ValueError, "group or others"):+ cache.read_cached(self.cache, self.expected)+ archive.chmod(0o600)+ metadata.unlink()+ metadata.symlink_to(archive)+ with self.assertRaisesRegex(ValueError, "regular file"):+ cache.read_cached(self.cache, self.expected)++ def test_archive_refuses_unencrypted_extra_and_traversal_entries(self):+ archive = self.root / "evidence.zip"+ for names in (+ ("window.cuae", "primary-desktop.cuae", "manifest.json"),+ ("window.cuae", "../primary-desktop.cuae"),+ ):+ with self.subTest(names=names):+ with zipfile.ZipFile(archive, "w") as output:+ for name in names:+ output.writestr(name, b"CUAEVID\x00sample")+ archive.chmod(0o600)+ with self.assertRaisesRegex(ValueError, "only encrypted"):+ cache.inspect_archive(archive)+ with zipfile.ZipFile(archive, "w") as output:+ for name in cache.MEMBERS:+ output.writestr(name, b"not an envelope")+ with self.assertRaisesRegex(ValueError, "not an evidence envelope"):+ cache.inspect_archive(archive)++ def test_private_directory_must_not_be_a_link_or_group_accessible(self):+ self.cache.mkdir(mode=0o755)+ with self.assertRaisesRegex(ValueError, "group or others"):+ cache.private_directory(self.cache)+ self.cache.chmod(0o700)+ link = self.root / "alias"+ link.symlink_to(self.cache, target_is_directory=True)+ with self.assertRaisesRegex(ValueError, "real directory"):+ cache.private_directory(link)+++if __name__ == "__main__":+ unittest.main()