Files
leleka/desktop/tests/remote_install.py
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

150 lines
8.6 KiB
Python

"""Real isolated SSH install/activate transactions. Never starts an inference worker.
Uses a unique private installation slot and removes only that slot on completion.
"""
import asyncio
import getpass
import hashlib
import json
import os
from pathlib import Path
import platform
import secrets
import shlex
import shutil
import socket
import tempfile
async def main():
root = Path(__file__).resolve().parents[2]
binary = root / "desktop-core/target/debug/strata-desktop"
ssh = shutil.which("ssh")
sshd = shutil.which("sshd") or "/usr/sbin/sshd"
assert os.name != "nt" and ssh and Path(sshd).is_file()
slot = "install-test-" + secrets.token_hex(12)
installed = Path.home() / ".strata-next/installations" / slot
assert not installed.exists()
processes = []
with tempfile.TemporaryDirectory(prefix="strata-install-test-") as folder:
p = Path(folder)
env = os.environ.copy()
async def run(*args, timeout=60, **kwargs):
proc = await asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE, **kwargs)
processes.append(proc)
out, err = await asyncio.wait_for(proc.communicate(), timeout)
return proc.returncode, out, err
try:
for key in ("host", "client"):
rc, _, _ = await run("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(p / key))
assert rc == 0
(p / "authorized").write_text((p / "client.pub").read_text())
with socket.socket() as listener:
listener.bind(("127.0.0.1", 0))
port = listener.getsockname()[1]
(p / "sshd.conf").write_text(
f"Port {port}\nListenAddress 127.0.0.1\nHostKey {p}/host\nPidFile {p}/pid\n"
f"UsePAM no\nPasswordAuthentication no\nKbdInteractiveAuthentication no\n"
f"AuthorizedKeysFile {p}/authorized\nAllowUsers {getpass.getuser()}\nLogLevel ERROR\n")
daemon = await asyncio.create_subprocess_exec(sshd, "-D", "-e", "-f", str(p / "sshd.conf"),
stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE)
processes.append(daemon)
await asyncio.sleep(.2)
assert daemon.returncode is None, "isolated sshd failed"
public = " ".join((p / "host.pub").read_text().split()[:2])
(p / "known_hosts").write_text(f"[127.0.0.1]:{port} {public}\n")
(p / "ssh.conf").write_text(f'UserKnownHostsFile "{p}/known_hosts"\nIdentitiesOnly yes\n')
(p / "bin").mkdir()
wrapper = p / "bin/ssh"
ssh_exec = shlex.quote(ssh) + " -F " + shlex.quote(str(p / "ssh.conf")) + ' "$@"\n'
wrapper.write_text("#!/bin/sh\nexec " + ssh_exec)
wrapper.chmod(0o700)
env["PATH"] = str(p / "bin") + os.pathsep + env["PATH"]
worker = p / "worker"
worker.write_text("#!/bin/sh\nprintf unexpected > " + shlex.quote(str(p / "worker-started")) + "\n")
worker.chmod(0o700)
profile = {"schema_version": 1, "id": "synthetic", "model": "fixture", "executable": str(worker),
"args": ["private-fixture-marker"], "endpoint": "127.0.0.1:19999", "startup_timeout_ms": 1000}
(p / "worker.json").write_text(json.dumps(profile))
target = {"ssh": {"schema_version": 1, "id": "fixture", "host": "127.0.0.1", "user": getpass.getuser(),
"port": port, "identity_file": str(p / "client")}, "slot": slot,
"os": "macos" if platform.system() == "Darwin" else "linux",
"arch": "aarch64" if platform.machine() in ("arm64", "aarch64") else "x86_64"}
config = {"schema_version": 1, "target": target, "runtime": str(binary),
"runtime_sha256": hashlib.file_digest(binary.open("rb"), "sha256").hexdigest(),
"worker_profile": str(p / "worker.json")}
async def command(name, value, success=True):
(p / "command.json").write_text(json.dumps(value))
rc, out, err = await run(str(binary), name, str(p / "command.json"), env=env)
assert (rc == 0) == success, (rc, out, err)
assert b"private-fixture-marker" not in out + err
return json.loads(out) if success else None
first = await command("remote-install", config)
assert first["outcome"] == "installed" and not first["serving_changed"]
current = lambda: (installed / "current").read_text().strip()
assert current() == first["release"]
assert (installed.stat().st_mode & 0o777) == 0o700
assert hashlib.file_digest((installed / "releases" / current() / "strata-desktop").open("rb"), "sha256").hexdigest() == config["runtime_sha256"]
repeated = await command("remote-install", config)
assert repeated["release"] == first["release"] and repeated["outcome"] == "reused"
# A new profile creates a separate immutable bundle.
profile["model"] = "fixture-next"
(p / "worker.json").write_text(json.dumps(profile))
second = await command("remote-install", config)
assert second["release"] != first["release"] and current() == second["release"]
rollback = {"schema_version": 1, "target": target, "runtime_sha256": first["runtime_sha256"],
"profile_sha256": first["profile_sha256"]}
assert (await command("remote-activate", rollback))["outcome"] == "activated"
assert current() == first["release"]
# Target-side profile failure cannot replace a working selection.
profile["executable"] = "/nonexistent-strata-test-worker"
(p / "worker.json").write_text(json.dumps(profile))
await command("remote-install", config, False)
assert current() == first["release"]
await command("remote-install", {**config, "runtime_sha256": "0" * 64}, False)
await command("remote-activate", {**rollback, "target": {**target, "os": "linux" if target["os"] == "macos" else "macos"}}, False)
assert current() == first["release"]
# A concurrent/stale lock is fail-closed and is not removed by another invocation.
(installed / ".lock").mkdir()
await command("remote-activate", rollback, False)
assert (installed / ".lock").is_dir()
(installed / ".lock").rmdir()
# A stale marker belongs to the earlier operation and is not deleted.
(installed / ".current-next").write_text("retain-for-inspection")
await command("remote-activate", rollback, False)
assert (installed / ".current-next").read_text() == "retain-for-inspection"
(installed / ".current-next").unlink()
# Truncated transfer cleans its staging and preserves selection.
wrapper.write_text("#!/bin/sh\nhead -c 100 | " + ssh_exec)
await command("remote-install", config, False)
wrapper.write_text("#!/bin/sh\nexec " + ssh_exec)
assert current() == first["release"]
assert not list(installed.glob(".stage.*")) and not (installed / ".lock").exists()
# Neither a bad retained release nor unsafe marker is activated.
retained = installed / "releases" / second["release"] / "worker.json"
retained.write_text("{}")
await command("remote-activate", {**rollback, "profile_sha256": second["profile_sha256"]}, False)
assert current() == first["release"]
(installed / "current").unlink()
(p / "untouched").write_text("sentinel")
(installed / "current").symlink_to(p / "untouched")
await command("remote-activate", rollback, False)
assert (p / "untouched").read_text() == "sentinel"
assert not (p / "worker-started").exists(), "installer must not start backend"
print("PASS: real SSH install, repeat, changed profile, rollback, private permissions, wrong digest/OS/profile, slot lock, truncated upload cleanup, corrupt release and symlink rejection; no worker launched.")
finally:
for proc in reversed(processes):
if proc.returncode is None:
proc.kill()
await proc.wait()
if installed.exists():
shutil.rmtree(installed)
if __name__ == "__main__":
asyncio.run(main())