Files
NODEDC_MISSION_CORE/scripts/install_compute_connection_links.py

219 lines
8.5 KiB
Python

#!/usr/bin/env python3
"""Adopt already installed SSH links into identity-bound connection routing.
Default is a read-only plan. This does not install VPNs, grant credentials,
change the board network, or provision model runtimes. Rollback retains the
exact previous launchd files. Only enumerated existing labels may be replaced.
"""
from __future__ import annotations
import argparse
import json
import os
import plistlib
import re
import shlex
import subprocess
import time
from pathlib import Path
from k1link.compute_connections.service import ConnectionService
from k1link.compute_connections.store import ConnectionStore, WorkerBinding
from k1link.compute_connections.transport import (
SshTransport,
TransportBinding,
bounded_run,
tailscale_profile,
tailscale_status,
)
def atomic(path: Path, data: bytes):
temporary = path.with_suffix(".install.tmp")
with temporary.open("xb") as stream:
stream.write(data)
stream.flush()
os.fsync(stream.fileno())
temporary.chmod(0o600)
os.replace(temporary, path)
def bootstrap(domain: str, path: Path):
# bootout is asynchronous: wait for launchd to finish retiring the old job.
deadline = time.monotonic() + 15
while True:
result = subprocess.run(
["/bin/launchctl", "bootstrap", domain, str(path)], capture_output=True, check=False
)
if result.returncode == 0:
return
if time.monotonic() >= deadline:
raise RuntimeError("launchd did not accept the service after retirement")
time.sleep(0.5)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--plan", type=Path, required=True)
parser.add_argument("--apply", action="store_true")
parser.add_argument("--rollback", action="store_true")
args = parser.parse_args()
root = Path(__file__).resolve().parents[1]
system = root / ".runtime/system"
plan = json.loads(args.plan.read_bytes())
labels = plan.pop("launchd_labels")
contour = plan["contour_id"]
alias = plan["ssh_alias"]
if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]{0,100}", alias):
raise ValueError("Invalid installed SSH alias")
config = bounded_run(["/usr/bin/ssh", "-G", alias]).decode().splitlines()
values = dict(line.split(" ", 1) for line in config if " " in line)
known_alias = values.get("hostkeyalias") or values["hostname"]
if known_alias == "none":
known_alias = values["hostname"]
known_files = shlex.split(values.get("userknownhostsfile", ""))
if len(known_files) != 1:
raise ValueError("One explicit installed known-hosts file is required")
known = Path(known_files[0]).expanduser()
keys = (
bounded_run(["/usr/bin/ssh-keygen", "-F", known_alias, "-f", str(known)])
.decode()
.splitlines()
)
keys = [
" ".join(line.split()[1:3])
for line in keys
if not line.startswith("#") and " ssh-ed25519 " in line
]
if len(set(keys)) != 1:
raise ValueError("Exactly one already trusted Ed25519 host key is required")
binding = TransportBinding(**plan, host_key=keys[0])
if set(labels) != {x.id for x in binding.channels}:
raise ValueError("Every installed channel needs exactly one existing launchd label")
status = tailscale_status()
profile = tailscale_profile(status)
peer = next(
x
for x in status["Peer"].values()
if str(x.get("DNSName", "")).rstrip(".") == values["hostname"]
)
service = ConnectionService(system, wireguard=lambda: [], tailscale=lambda: status)
_, connection = service.candidate(profile.id, peer["ID"])
worker = WorkerBinding(
contour_id=contour,
transport_id=binding.id,
host_key_sha256=binding.fingerprint,
connections=(connection,),
active_connection_id=connection.id,
)
plists = []
for channel in binding.channels:
label = labels[channel.id]
if not re.fullmatch(r"com\.nodedc\.[A-Za-z0-9.-]+", label):
raise ValueError("Only owned NODE.DC labels can be migrated")
path = Path.home() / "Library/LaunchAgents" / (label + ".plist")
if path.is_symlink():
raise ValueError("Symlink service definition refused")
original = path.read_bytes()
document = plistlib.loads(original)
argv = document["ProgramArguments"]
if document["Label"] != label or "k1link.rotating_process" not in argv or "--" not in argv:
raise ValueError("Only existing managed SSH links can be adopted")
child = argv[argv.index("--") + 1 :]
already = "k1link.compute_connections.link" in child
if not already and (
child[0] != "/usr/bin/ssh" or child[-1] != alias or channel.arguments[1] not in child
):
raise ValueError("Installed forward differs from the reviewed plan")
document["ProgramArguments"] = argv[: argv.index("--") + 1] + [
str(root / ".venv/bin/python"),
"-m",
"k1link.compute_connections.link",
"--root",
str(system),
"--contour",
contour,
"--channel",
channel.id,
]
plists.append((path, original, plistlib.dumps(document), label))
print(
json.dumps(
dict(
contour=contour,
network=profile.name,
identity=binding.fingerprint,
channels=len(plists),
action="rollback" if args.rollback else "apply" if args.apply else "plan",
)
)
)
if not (args.apply or args.rollback):
return
backup = system / "connection-migrations" / binding.id
backup.mkdir(parents=True, exist_ok=True, mode=0o700)
transport_root = system / "worker-bindings"
transport_root.mkdir(parents=True, exist_ok=True, mode=0o700)
if not args.rollback:
target = transport_root / (binding.id + ".json")
if target.exists() and target.read_bytes() != binding.model_dump_json(indent=2).encode():
raise ValueError("A different installed binding exists; refusing overwrite")
if not target.exists():
atomic(target, binding.model_dump_json(indent=2).encode())
trust = transport_root / (binding.id + ".known_hosts")
content = (binding.id + " " + binding.host_key + "\n").encode()
if trust.exists() and trust.read_bytes() != content:
raise ValueError("Installed trust changed")
if not trust.exists():
atomic(trust, content)
SshTransport(transport_root).probe(worker, connection)
store = ConnectionStore(system)
current = store.read()
existing = next((x for x in current.workers if x.contour_id == contour), None)
if existing is None:
store.enroll(profile, worker, expected_revision=current.revision)
elif existing.host_key_sha256 != worker.host_key_sha256:
raise ValueError("Existing device identity differs")
domain = f"gui/{os.getuid()}"
changed = []
try:
for path, original, replacement, label in plists:
saved = backup / path.name
if not saved.exists():
atomic(saved, original)
desired = saved.read_bytes() if args.rollback else replacement
if path.read_bytes() != original:
raise ValueError("Service changed concurrently")
subprocess.run(
["/bin/launchctl", "bootout", domain + "/" + label],
check=False,
capture_output=True,
)
atomic(path, desired)
changed.append((path, original, label))
bootstrap(domain, path)
if not args.rollback:
deadline = time.monotonic() + 35
while time.monotonic() < deadline:
states = service.link_states(service.store.read().worker(contour))
if states and all(x["connected"] for x in states):
print(json.dumps(dict(state="connected", channels=states)))
return
time.sleep(1)
raise RuntimeError("Link acceptance failed")
except BaseException:
for path, original, label in reversed(changed):
subprocess.run(
["/bin/launchctl", "bootout", domain + "/" + label],
check=False,
capture_output=True,
)
atomic(path, original)
bootstrap(domain, path)
raise
if __name__ == "__main__":
main()