Files
ai-agent/sidecar/test_link.py
gabrielvidalandClaude Opus 5.5 ad308d22e8 feat(workers): owner workers that dial out — for a machine off the tailnet
A worker on a network the hub can't call (an Orus devbox, only on the
company's tailnet) now pairs over the guests' worker link as one of the
owner's workers:

- POST /api/workers/enroll mints an owner code (link.OWNER) with the
  dialog's answers and the install line (WORKER_HUB/ENROLL/ACCOUNT/CWD).
- /worker-link/enroll/check says owner: true; /worker-link/enroll makes an
  ordinary owner record (no owner field, id w…, claudeMode own, account),
  and on_paired puts it in the picked profile (default runner if asked).
- Own login only: PATCH refuses the proxy for a linked owner worker
  (the proxy is on the tailnet host; the public host takes no owner token).
- Its login is watched like any own-mode worker's, its link token rotates
  weekly, and the security log records worker_linked.
- sidecar/link.py keeps owner in link.json; install.sh sets such a machine
  up as the owner's (notify shims, no launcher, own-login warning), and
  points systemctl --user at /run/user/<uid> when a shell lacks it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:45:02 +01:00

142 lines
6.1 KiB
Python

"""link.py — the worker that dials out: it polls a hub, makes each request
against its own sidecar, posts the answer back; enroll saves the token; a
refused token idles it. ``python -m pytest test_link.py`` from ``sidecar/``."""
import base64
import json
import os
import tempfile
import threading
import time
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
os.environ["WORKER_STATE_DIR"] = tempfile.mkdtemp()
import link # noqa: E402
def _server(handler):
srv = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv, f"http://127.0.0.1:{srv.server_address[1]}"
class LinkTest(unittest.TestCase):
def setUp(self):
link.forget()
self.replies, self.queue, self.polls, self.local_seen = [], [], [], []
test = self
class Hub(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_POST(self):
n = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(n)
auth = self.headers.get("Authorization")
if self.path.endswith("/worker-link/poll"):
test.polls.append(auth)
if auth != "Bearer " + "T" * 40:
self.send_response(401)
self.end_headers()
return
out = {"requests": test.queue[:]}
test.queue.clear()
data = json.dumps(out).encode()
self.send_response(200)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
elif "/worker-link/reply/" in self.path:
test.replies.append((self.path.rsplit("/", 1)[1],
int(self.headers["x-link-status"]),
json.loads(self.headers["x-link-headers"]), body))
self.send_response(200)
self.send_header("Content-Length", "2")
self.end_headers()
self.wfile.write(b"{}")
elif self.path.endswith("/worker-link/enroll"):
d = json.loads(body)
test.enrolled = d
ok = d["code"] != "DEAD"
mine = {"owner": True} if d["code"] == "OWNERS12" else {}
data = json.dumps({"workerId": "gabc", "linkToken": "T" * 40, **mine} if ok else {
"detail": {"message": "unknown", "kind": "enroll_code"}}).encode()
self.send_response(200 if ok else 403)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
class Local(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def _answer(self):
n = int(self.headers.get("Content-Length") or 0)
test.local_seen.append((self.command, self.path,
self.headers.get("Authorization"),
self.rfile.read(n)))
code = 404 if self.path == "/missing" else 200
data = b'{"ok":true}'
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("X-Feed-Size", "11")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
do_GET = do_POST = do_PUT = _answer
self.hub, self.hub_url = _server(Hub)
self.local, self.local_url = _server(Local)
self.addCleanup(self.hub.shutdown)
self.addCleanup(self.local.shutdown)
def test_enroll_saves_the_link(self):
out = link.enroll(self.hub_url + "/", "CODE1234")
self.assertEqual(out["workerId"], "gabc")
self.assertEqual(link.config()["linkToken"], "T" * 40)
self.assertEqual(link.config()["hub"], self.hub_url)
self.assertTrue(self.enrolled["pairCode"])
self.assertEqual(self.enrolled["code"], "CODE1234")
def test_an_owners_code_marks_the_link_as_the_owners(self):
# Pair a worker → It dials out: the installer reads `owner` back on update.
self.assertNotIn("owner", (link.enroll(self.hub_url, "CODE1234"), link.config())[1])
link.enroll(self.hub_url, "OWNERS12")
self.assertIs(link.config()["owner"], True)
self.assertRegex(link._path().read_text(), r'"owner": *true')
def test_a_dead_code_exits_for_the_installer(self):
with self.assertRaises(SystemExit) as cm:
link.enroll(self.hub_url, "DEAD")
self.assertEqual(cm.exception.code, link.CODE_REFUSED)
self.assertEqual(link.config(), {})
def test_relays_requests_to_the_local_sidecar(self):
link._save({"hub": self.hub_url, "workerId": "gabc", "linkToken": "T" * 40})
self.queue += [
{"id": "r1", "method": "POST", "path": "/spawn?x=1",
"headers": {"authorization": "Bearer hub", "content-type": "application/json"},
"body": base64.b64encode(b'{"a":1}').decode()},
{"id": "r2", "method": "GET", "path": "/missing", "headers": {}}]
threading.Thread(target=link.run, args=(self.local_url,), daemon=True).start()
for _ in range(100):
if len(self.replies) == 2:
break
time.sleep(0.05)
by = {r[0]: r for r in self.replies}
self.assertEqual(by["r1"][1], 200)
self.assertEqual(by["r1"][2].get("X-Feed-Size"), "11")
self.assertEqual(by["r1"][3], b'{"ok":true}')
self.assertEqual(by["r2"][1], 404)
seen = {p: (m, a, b) for m, p, a, b in self.local_seen}
self.assertEqual(seen["/spawn?x=1"], ("POST", "Bearer hub", b'{"a":1}'))
self.assertTrue(link.status()["connected"])
if __name__ == "__main__":
unittest.main()