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>
281 lines
12 KiB
Python
281 lines
12 KiB
Python
"""
|
|
The worker link, worker side — a worker that dials out instead of listening.
|
|
|
|
A tailnet worker binds its Tailscale address and the hub calls it. A guest's
|
|
computer is on no network the hub can reach, so this sidecar listens on
|
|
loopback only and this thread carries the hub's calls to it: it long-polls
|
|
the hub (``POST <hub>/worker-link/poll``, Bearer the link token), makes each
|
|
request it gets against the local sidecar, and posts the answer back
|
|
(``POST <hub>/worker-link/reply/<id>``). The hub's half is
|
|
``backend/workers/link.py``; the requests are the ones it would have sent
|
|
over the tailnet — the pairing included.
|
|
|
|
``link.json`` in the worker's state dir (0600) holds ``{hub, workerId,
|
|
linkToken[, owner]}``, written by ``python link.py enroll <hub> <code>`` (the
|
|
installer, with the one-time code from the guest's portal — or from the
|
|
owner's *Pair a worker* → *It dials out*, which makes ``owner`` true) and rewritten by
|
|
``POST /link/token`` when the hub rotates the token. No file: the thread
|
|
idles. A refused token (401 — the computer was removed) idles it too, until
|
|
the file changes.
|
|
|
|
Standard library only: one keep-alive HTTPS connection for the poll, one per
|
|
reply thread.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import http.client
|
|
import json
|
|
import os
|
|
import platform
|
|
import socket
|
|
import sys
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
from fastapi import APIRouter, Header, HTTPException
|
|
from pydantic import BaseModel
|
|
|
|
import pairing
|
|
|
|
POLL_TIMEOUT_S = 60
|
|
# `enroll`'s exit status when the hub doesn't know the code (worker/install.sh).
|
|
CODE_REFUSED = 3
|
|
LOCAL_TIMEOUT_S = 300
|
|
# Never relayed back: hop-by-hop, and what the HTTP stack sets itself.
|
|
_HOP = {"connection", "keep-alive", "transfer-encoding", "te", "trailer", "upgrade",
|
|
"content-length", "content-encoding", "date", "server"}
|
|
|
|
_lock = threading.Lock()
|
|
_state: dict = {"connected": False, "lastPollAt": None, "error": None}
|
|
|
|
|
|
def _path():
|
|
return pairing.state_dir() / "link.json"
|
|
|
|
|
|
def config() -> dict:
|
|
try:
|
|
cfg = json.loads(_path().read_text())
|
|
except (OSError, ValueError):
|
|
return {}
|
|
return cfg if isinstance(cfg, dict) and cfg.get("hub") and cfg.get("linkToken") else {}
|
|
|
|
|
|
def _save(cfg: dict) -> None:
|
|
pairing._write_private(_path(), json.dumps(cfg))
|
|
|
|
|
|
def forget() -> None:
|
|
"""Unpaired: stop dialling the hub."""
|
|
_path().unlink(missing_ok=True)
|
|
|
|
|
|
def status() -> dict | None:
|
|
"""``/health``'s ``link`` (None when this worker doesn't dial out)."""
|
|
cfg = config()
|
|
if not cfg:
|
|
return None
|
|
with _lock:
|
|
return {"hub": cfg["hub"], **_state}
|
|
|
|
|
|
# ── HTTP ─────────────────────────────────────────────────────────────────────
|
|
def _conn(hub: str, timeout: float) -> http.client.HTTPConnection:
|
|
u = urllib.parse.urlsplit(hub)
|
|
cls = http.client.HTTPSConnection if u.scheme == "https" else http.client.HTTPConnection
|
|
return cls(u.hostname, u.port, timeout=timeout)
|
|
|
|
|
|
def _send(conn, method: str, path: str, token: str, body: bytes = b"",
|
|
headers: dict | None = None) -> tuple[int, bytes]:
|
|
h = {"Authorization": f"Bearer {token}", "User-Agent": "ai-agent-worker-link",
|
|
**(headers or {})}
|
|
if body or method == "POST":
|
|
h.setdefault("Content-Type", "application/json")
|
|
conn.request(method, path, body=body or None, headers=h)
|
|
r = conn.getresponse()
|
|
return r.status, r.read()
|
|
|
|
|
|
# ── one request from the hub ─────────────────────────────────────────────────
|
|
def _local(base: str, req: dict, body: bytes) -> tuple[int, dict, bytes]:
|
|
headers = {k: v for k, v in (req.get("headers") or {}).items()
|
|
if k.lower() not in _HOP and k.lower() != "host"}
|
|
r = urllib.request.Request(base + req["path"], data=body if body else None,
|
|
method=req.get("method") or "GET", headers=headers)
|
|
try:
|
|
with urllib.request.urlopen(r, timeout=LOCAL_TIMEOUT_S) as resp:
|
|
return resp.status, dict(resp.headers.items()), resp.read()
|
|
except urllib.error.HTTPError as e:
|
|
return e.code, dict(e.headers.items()), e.read()
|
|
except (urllib.error.URLError, OSError) as e:
|
|
return 502, {"Content-Type": "application/json"}, json.dumps({"detail": {
|
|
"message": f"the worker's sidecar didn't answer: {e}", "kind": "sidecar"}}).encode()
|
|
|
|
|
|
def _handle(cfg: dict, base: str, req: dict) -> None:
|
|
hub = cfg["hub"].rstrip("/")
|
|
tok = cfg["linkToken"]
|
|
try:
|
|
if req.get("bodyUrl"):
|
|
c = _conn(hub, LOCAL_TIMEOUT_S)
|
|
st, body = _send(c, "GET", urllib.parse.urlsplit(hub).path + req["bodyUrl"], tok)
|
|
c.close()
|
|
if st != 200:
|
|
raise RuntimeError(f"body fetch: HTTP {st}")
|
|
else:
|
|
body = base64.b64decode(req.get("body") or "")
|
|
status_, headers, data = _local(base, req, body)
|
|
except Exception as e:
|
|
status_, headers, data = 502, {"Content-Type": "application/json"}, json.dumps(
|
|
{"detail": {"message": f"link: {e}", "kind": "sidecar"}}).encode()
|
|
keep = {k: v for k, v in headers.items() if k.lower() not in _HOP}
|
|
try:
|
|
c = _conn(hub, LOCAL_TIMEOUT_S)
|
|
_send(c, "POST", urllib.parse.urlsplit(hub).path + f"/worker-link/reply/{req['id']}",
|
|
tok, data, {"Content-Type": "application/octet-stream",
|
|
"x-link-status": str(status_),
|
|
"x-link-headers": json.dumps(keep)})
|
|
c.close()
|
|
except Exception as e:
|
|
print(f"[link] reply {req.get('id')} failed: {e}", flush=True)
|
|
|
|
|
|
# ── the loop ─────────────────────────────────────────────────────────────────
|
|
def _set(**kw) -> None:
|
|
with _lock:
|
|
_state.update(kw)
|
|
|
|
|
|
def run(base: str) -> None:
|
|
"""Poll forever (a daemon thread). ``base`` is the local sidecar's URL."""
|
|
conn, conn_hub, backoff = None, None, 2.0
|
|
while True:
|
|
cfg = config()
|
|
if not cfg:
|
|
_set(connected=False)
|
|
time.sleep(5)
|
|
continue
|
|
hub = cfg["hub"].rstrip("/")
|
|
try:
|
|
if conn is None or conn_hub != hub:
|
|
if conn is not None:
|
|
conn.close()
|
|
conn, conn_hub = _conn(hub, POLL_TIMEOUT_S), hub
|
|
st, raw = _send(conn, "POST", urllib.parse.urlsplit(hub).path
|
|
+ "/worker-link/poll", cfg["linkToken"], b"{}")
|
|
except Exception as e:
|
|
if conn is not None:
|
|
conn.close()
|
|
conn = None
|
|
_set(connected=False, error=str(e)[:200])
|
|
time.sleep(backoff)
|
|
backoff = min(60.0, backoff * 2)
|
|
continue
|
|
if st in (401, 403):
|
|
# Removed (or its guest paused): wait for a new link.json.
|
|
_set(connected=False, error=f"refused by the hub (HTTP {st})")
|
|
mtime = _path().stat().st_mtime if _path().exists() else 0
|
|
while (_path().stat().st_mtime if _path().exists() else 0) == mtime:
|
|
time.sleep(30)
|
|
continue
|
|
if st != 200:
|
|
_set(connected=False, error=f"HTTP {st}")
|
|
time.sleep(300 if st == 429 else backoff)
|
|
backoff = min(60.0, backoff * 2)
|
|
continue
|
|
backoff = 2.0
|
|
_set(connected=True, error=None,
|
|
lastPollAt=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
|
|
try:
|
|
reqs = json.loads(raw).get("requests") or []
|
|
except ValueError:
|
|
reqs = []
|
|
for req in reqs:
|
|
threading.Thread(target=_handle, args=(cfg, base, req), daemon=True).start()
|
|
|
|
|
|
def start() -> None:
|
|
"""The sidecar's startup hook: dial out (idle while there is no link.json)."""
|
|
bind = os.environ.get("SIDECAR_BIND", "127.0.0.1")
|
|
port = os.environ.get("SIDECAR_PORT", "8790")
|
|
threading.Thread(target=run, args=(f"http://{bind}:{port}",), daemon=True,
|
|
name="worker-link").start()
|
|
|
|
|
|
# ── the hub hands over a new token ───────────────────────────────────────────
|
|
class TokenBody(BaseModel):
|
|
token: str
|
|
|
|
|
|
def make_router(auth) -> APIRouter:
|
|
r = APIRouter()
|
|
|
|
@r.post("/link/token")
|
|
def link_token(body: TokenBody, authorization: str | None = Header(default=None)):
|
|
"""The hub rotated this computer's link token."""
|
|
auth(authorization)
|
|
cfg = config()
|
|
if not cfg:
|
|
raise HTTPException(409, {"message": "this worker doesn't dial out",
|
|
"kind": "no_link"})
|
|
tok = (body.token or "").strip()
|
|
if len(tok) < 32:
|
|
raise HTTPException(400, "a link token is 32+ characters")
|
|
_save({**cfg, "linkToken": tok})
|
|
return {"ok": True}
|
|
|
|
return r
|
|
|
|
|
|
# ── enroll (the installer) ───────────────────────────────────────────────────
|
|
def enroll(hub: str, code: str) -> dict:
|
|
"""Trade the portal's one-time code for a link token and save it; the hub
|
|
pairs with this sidecar through the link on its first poll."""
|
|
hub = hub.rstrip("/")
|
|
ident = pairing.identity()
|
|
payload = {"code": code.strip(), "pairCode": pairing.new_code(),
|
|
"hostname": ident["hostname"], "platform": sys.platform,
|
|
"machine": platform.machine(), "name": socket.gethostname().split(".")[0]}
|
|
req = urllib.request.Request(f"{hub}/worker-link/enroll", method="POST",
|
|
data=json.dumps(payload).encode(),
|
|
headers={"Content-Type": "application/json",
|
|
"User-Agent": "ai-agent-worker-link"})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=30) as r:
|
|
out = json.loads(r.read())
|
|
except urllib.error.HTTPError as e:
|
|
try:
|
|
detail = json.loads(e.read()).get("detail")
|
|
except Exception:
|
|
detail = None
|
|
detail = detail if isinstance(detail, dict) else {}
|
|
if detail.get("kind") == "enroll_code":
|
|
# Unknown, used or expired: the installer says what to do next.
|
|
raise SystemExit(CODE_REFUSED)
|
|
raise SystemExit(f"enroll refused (HTTP {e.code}): {detail.get('message') or e.reason}")
|
|
except (urllib.error.URLError, OSError) as e:
|
|
raise SystemExit(f"couldn't reach {hub}: {getattr(e, 'reason', e)}")
|
|
# ``owner``: one of the hub owner's workers (Pair a worker → It dials
|
|
# out), not a guest's computer — the installer's `update` reads it back.
|
|
_save({"hub": hub, "workerId": out["workerId"], "linkToken": out["linkToken"],
|
|
**({"owner": True} if out.get("owner") else {})})
|
|
return out
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# `python link.py enroll <hub> <code>` (the installer) · `python link.py status`
|
|
cmd = sys.argv[1] if len(sys.argv) > 1 else "status"
|
|
if cmd == "enroll" and len(sys.argv) == 4:
|
|
out = enroll(sys.argv[2], sys.argv[3])
|
|
print(json.dumps({"workerId": out["workerId"], "name": out.get("name")}))
|
|
else:
|
|
cfg = config()
|
|
print(json.dumps({"hub": cfg.get("hub"), "workerId": cfg.get("workerId"),
|
|
"linked": bool(cfg), "owner": bool(cfg.get("owner"))}))
|