"""Offline checks for the private-repository update safety boundary.""" from __future__ import annotations import json import os import stat import subprocess import tempfile import time import unittest from pathlib import Path from virsh_panel.updater import BRANCH, REPOSITORY_URL, UpdateError, Updater class MemoryStore: def __init__(self): self.secrets: dict[str, str] = {} self.values: dict[str, str] = {} self.deployment_states: list[str] = [] def get_secret(self, name): return self.secrets.get(name) def set_secret(self, name, value): self.secrets[name] = value def delete_secret(self, name): self.secrets.pop(name, None) def get_value(self, name): return self.values.get(name) def set_value(self, name, value): self.values[name] = value if name.startswith("update.job."): payload = json.loads(value) state = payload.get("deployment_state") if state and (not self.deployment_states or self.deployment_states[-1] != state): self.deployment_states.append(state) def git(path: Path, *args: str) -> str: result = subprocess.run( ["git", *args], cwd=path, capture_output=True, text=True, check=True, ) return result.stdout.strip() def make_repo(tmp_path: Path) -> Path: source = tmp_path / "source" source.mkdir() git(source, "init", "-b", BRANCH) git(source, "config", "user.name", "Updater Test") git(source, "config", "user.email", "updater@example.test") (source / "README.md").write_text("old\n", encoding="utf-8") (source / "engine").mkdir() (source / "engine" / "requirements.txt").write_text("example-package==1.0\n", encoding="utf-8") (source / ".gitignore").write_text( "engine/.venv/\nruntime/\nweb/vendor/\nweb/storage/ticket-attachments/\n", encoding="utf-8", ) git(source, "add", "README.md", "engine/requirements.txt", ".gitignore") git(source, "commit", "-m", "initial") checkout = tmp_path / "panel" subprocess.run( ["git", "clone", "--branch", BRANCH, str(source), str(checkout)], capture_output=True, text=True, check=True, ) git(checkout, "remote", "set-url", "origin", REPOSITORY_URL) return checkout def advance_source(source: Path, *, filename: str = "README.md") -> str: (source / filename).parent.mkdir(parents=True, exist_ok=True) (source / filename).write_text("new\n", encoding="utf-8") # Protected runtime paths are normally ignored; forcing them lets the # updater test prove that a malicious target commit is still rejected. git(source, "add", "-f", filename) git(source, "commit", "-m", "next") return git(source, "rev-parse", "HEAD") def local_fetch(updater: Updater, source: Path): def fetch() -> str: git(updater.repo_dir, "fetch", "--no-tags", str(source), f"refs/heads/{BRANCH}") return git(updater.repo_dir, "rev-parse", "FETCH_HEAD") updater._fetch_remote = fetch class UpdaterTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory(prefix="virsh-panel-updater-test-") self.addCleanup(self.temp.cleanup) self.tmp_path = Path(self.temp.name) def test_settings_and_token_never_reveal_secret(self): checkout = make_repo(self.tmp_path) store = MemoryStore() updater = Updater(checkout, store) updater.set_token("a-test-access-token-123") settings = updater.settings() self.assertEqual(settings["repository"], REPOSITORY_URL) self.assertTrue(settings["token_configured"]) self.assertTrue(settings["checkout_ready"]) self.assertIsNone(settings["active_job_id"]) self.assertIsNone(settings["last_job_id"]) self.assertNotIn("a-test-access-token-123", repr(settings)) with updater._git_auth() as env: self.assertEqual(env["VIRT_CLOUD_GIT_TOKEN"], "a-test-access-token-123") self.assertNotIn("a-test-access-token-123", Path(env["GIT_ASKPASS"]).read_text()) updater.clear_token() self.assertFalse(updater.settings()["token_configured"]) def test_check_is_read_only_and_reports_new_version(self): checkout = make_repo(self.tmp_path) updater = Updater(checkout, MemoryStore()) current = git(checkout, "rev-parse", "HEAD") updater._remote_head = lambda: current self.assertEqual(updater.check()["status"], "current") updater._remote_head = lambda: "a" * 40 self.assertEqual(updater.check()["status"], "update_available") self.assertEqual(git(checkout, "rev-parse", "HEAD"), current) def test_zip_or_dirty_checkout_is_rejected(self): plain = self.tmp_path / "plain" plain.mkdir() with self.assertRaisesRegex(UpdateError, "Git"): Updater(plain, MemoryStore()).check() checkout = make_repo(self.tmp_path) (checkout / "README.md").write_text("user changes\n", encoding="utf-8") updater = Updater(checkout, MemoryStore()) with self.assertRaisesRegex(UpdateError, "未提交"): updater.create_job() with self.assertRaisesRegex(UpdateError, "未提交"): updater.apply() def test_project_ignores_ticket_attachment_runtime_data(self): project_root = Path(__file__).resolve().parents[2] self.assertIn( "/web/storage/ticket-attachments/", (project_root / ".gitignore").read_text(encoding="utf-8"), ) self.assertIn( "storage/ticket-attachments/", (project_root / "web" / ".gitignore").read_text(encoding="utf-8"), ) def test_ignored_ticket_attachments_do_not_make_checkout_dirty(self): checkout = make_repo(self.tmp_path) attachment = checkout / "web" / "storage" / "ticket-attachments" / "ticket-image.png" attachment.parent.mkdir(parents=True) attachment.write_bytes(b"private runtime image") updater = Updater(checkout, MemoryStore()) updater._remote_head = lambda: git(checkout, "rev-parse", "HEAD") self.assertTrue(updater.settings()["checkout_ready"]) self.assertEqual(updater.check()["status"], "current") self.assertEqual(git(checkout, "status", "--porcelain=v1", "--untracked-files=all"), "") source = self.tmp_path / "source" target = advance_source(source) local_fetch(updater, source) applied = updater.apply() self.assertEqual(applied["new_commit"], target) self.assertEqual(attachment.read_bytes(), b"private runtime image") def test_target_commit_cannot_vendor_ticket_attachments(self): checkout = make_repo(self.tmp_path) source = self.tmp_path / "source" target = source / "web" / "storage" / "ticket-attachments" / "bundled.png" target.parent.mkdir(parents=True) target.write_bytes(b"must remain runtime-only") git(source, "add", "-f", str(target.relative_to(source))) git(source, "commit", "-m", "attempt to vendor ticket image") updater = Updater(checkout, MemoryStore()) local_fetch(updater, source) with self.assertRaisesRegex(UpdateError, "运行数据"): updater.apply() def test_fast_forward_job_is_persisted_and_calls_restart(self): checkout = make_repo(self.tmp_path) source = self.tmp_path / "source" old = git(checkout, "rev-parse", "HEAD") target = advance_source(source) store = MemoryStore() updater = Updater(checkout, store) updater.set_token("a-test-access-token-123") local_fetch(updater, source) queued = updater.create_job() self.assertEqual(updater.settings()["active_job_id"], queued["job_id"]) restarted = [] def restart(mark_schema_ready): restarted.append(True) mark_schema_ready() result = updater.run_pending_job( before_switch=lambda: None, restart=restart, ) self.assertEqual(result["status"], "succeeded") self.assertEqual(result["old_commit"], old) self.assertEqual(result["new_commit"], target) self.assertTrue(result["rollback_ref"].startswith("refs/virt-cloud/rollback/")) self.assertEqual(updater.get_job(queued["job_id"]), result) self.assertEqual(updater.settings()["last_job_id"], queued["job_id"]) self.assertIsNone(updater.settings()["active_job_id"]) self.assertEqual(restarted, [True]) self.assertEqual(store.deployment_states, [ "preparing", "quiescing", "services_stopped", "code_switched", "schema_migrating", "schema_ready", "services_ready", ]) self.assertEqual(result["deployment_state"], "services_ready") self.assertEqual(git(checkout, "rev-parse", "HEAD"), target) self.assertEqual(git(checkout, "rev-parse", result["rollback_ref"]), old) def test_apply_restores_tracked_modes_without_exposing_ignored_secrets(self): checkout = make_repo(self.tmp_path) source = self.tmp_path / "source" nested = source / "web" / "app" / "NewFeature.php" nested.parent.mkdir(parents=True) nested.write_text("