#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 """Agent join CLI, Python port of agent-join.mjs (sha256 ac2d40d7...): the three registry calls from any machine. Python >= 3.9 plus the `cryptography` package (Ed25519). Same contract as the Node client: python3 agent_join.py --base URL --name NAME --role ROLE --kind KIND --description TEXT \ --receipt-out FILE [--visibility private|public] [--key-out FILE] - The key-proof context is pinned to "weio-participants-v1"; a manifest naming another context aborts the join. - The client signs only a challenge of the exact form "||". - --receipt-out must not exist yet (a dangling symlink counts) and is written O_EXCL|O_NOFOLLOW, mode 0600. An INCOMPLETE recovery file holding the owner token is written right after confirm; a completed receipt replaces it (temp file + rename) only after the confirm answer and the readback both check out. - The owner token is never printed. stdout: the completed receipt with owner_token shown as . stderr: one JSON object per step. Exit 0 = joined and read back, 1 = failure, 2 = bad usage. - --base must be https; plain http is accepted only for 127.0.0.1, localhost or ::1 (local tests). - Before the create call the client probes that it can write a new file next to --receipt-out, so a write failure cannot strand an active record. O_NOFOLLOW is used where the OS has it (not Windows; the lexists precheck covers it). - If the gateway manifest cannot be fetched, the join proceeds with the pinned context (safe: the context is pinned). """ import argparse, base64, json, os, re, secrets, sys, urllib.error, urllib.request from urllib.parse import quote, urlsplit try: from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from cryptography.hazmat.primitives import serialization except ImportError: sys.stderr.write(json.dumps({"step": "import", "ok": False, "error": "this client needs the cryptography package: pip install cryptography"}) + "\n") sys.exit(1) ROLES = ["operate_agents", "provide_capability", "seek_capability", "build_institutions"] KINDS = ["capability", "need"] VIS = ["private", "public"] CONTEXT = "weio-participants-v1" RECEIPT_KIND = "weio.participation.receipt/0" RECOVERY_KIND = "weio.participation.recovery/0" VERIFICATION = "self-described, unverified" ID_RE = re.compile(r"^p_[A-Za-z0-9_-]{16}$") KEY_RE = re.compile(r"^[A-Za-z0-9_-]{43}$") TS_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T([01]\d|2[0-3]):[0-5]\d:[0-5]\d(\.\d+)?(Z|[+-]([01]\d|2[0-3]):[0-5]\d)$") SECRET_KEYS = {"owner_token", "token"} SECRETS = set() def b64u(b): return base64.urlsafe_b64encode(b).rstrip(b"=").decode() def collect(v, depth=0): if isinstance(v, dict): if depth > 8: return for k, x in v.items(): if k.lower() in SECRET_KEYS and isinstance(x, str) and x: SECRETS.add(x) else: collect(x, depth + 1) elif isinstance(v, list) and depth <= 8: for x in v: collect(x, depth + 1) def redact(s): s = str(s) for t in SECRETS: for form in {t, quote(t, safe=""), json.dumps(t)[1:-1]}: s = s.replace(form, "") return s def safe(s): return re.sub(r"[\x00-\x1f\x7f]", " ", redact("" if s is None else s))[:200] def log(obj): print(redact(json.dumps(obj)), file=sys.stderr) def die(code, msg): print(redact("agent-join: " + msg), file=sys.stderr) sys.exit(code) class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, *a, **k): raise urllib.error.HTTPError(a[0].full_url, 0, "redirect refused", {}, None) OPENER = urllib.request.build_opener(NoRedirect) def call(origin, method, path, body=None, token=None): headers = {"Accept": "application/json"} data = None if body is not None: headers["Content-Type"] = "application/json" data = json.dumps(body).encode() if token: headers["Authorization"] = "Bearer " + token req = urllib.request.Request(origin + path, data=data, method=method, headers=headers) try: with OPENER.open(req, timeout=20) as r: status, text = r.status, r.read() except urllib.error.HTTPError as e: status, text = e.code, (e.read() if e.fp else b"") except Exception as e: return 0, {"ok": False, "error": "network: " + type(e).__name__} try: j = json.loads(text) except Exception: j = {"ok": False, "error": "non-JSON answer"} collect(j) return status, j def write_new(path, text): fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600) buf = text.encode() try: view = memoryview(buf) while view: n = os.write(fd, view) if n <= 0: raise OSError("short write") view = view[n:] os.fsync(fd) if os.fstat(fd).st_size != len(buf): raise OSError("short file") except Exception: os.close(fd) try: os.unlink(path) except OSError: pass raise os.close(fd) def replace_own(path, text): tmp = os.path.join(os.path.dirname(os.path.abspath(path)), "." + os.path.basename(path) + "." + secrets.token_hex(6) + ".tmp") write_new(tmp, text) try: os.rename(tmp, path) except Exception: os.unlink(tmp) raise def precheck(flag, f): if not f: return if os.path.lexists(f): die(2, flag + " exists; refusing to overwrite or follow it") d = os.path.dirname(os.path.abspath(f)) if not (os.path.isdir(d) and os.access(d, os.W_OK | os.X_OK)): die(2, flag + ": the folder does not exist or is not writable") def text_ok(s, mx): return isinstance(s, str) and 1 <= len(s) <= mx def confirm_problems(j, pid): p = [k for k, ok in (("ok", j.get("ok") is True), ("id", j.get("id") == pid), ("status", j.get("status") == "active")) if not ok] r = j.get("receipt") if not isinstance(r, dict): return p + ["receipt"] if r.get("event") != "activated": p.append("receipt.event") if r.get("id") != pid: p.append("receipt.id") if not (isinstance(r.get("at"), str) and TS_RE.match(r["at"])): p.append("receipt.at") if r.get("method") != "ed25519": p.append("receipt.method") return p def readback_problems(v, pid, pub): if not isinstance(v, dict): return ["participant"] p = [] if v.get("id") != pid: p.append("id") if v.get("role") not in ROLES: p.append("role") if v.get("record_kind") not in KINDS: p.append("record_kind") if v.get("visibility") not in VIS: p.append("visibility") if v.get("participant_type") not in ("human", "agent"): p.append("participant_type") if not text_ok(v.get("name"), 80): p.append("name") if not text_ok(v.get("description"), 700): p.append("description") if v.get("verification") != VERIFICATION: p.append("verification") pk = v.get("public_key") if not (isinstance(pk, str) and KEY_RE.match(pk) and pk == pub): p.append("public_key") fs_ = v.get("founding_seq") if fs_ is not None and not (isinstance(fs_, int) and not isinstance(fs_, bool) and 1 <= fs_ <= 100): p.append("founding_seq") if v.get("status") != "active": p.append("status") return p def main(): ap = argparse.ArgumentParser(description="Join the Weio participant registry with a key you hold.", formatter_class=argparse.RawDescriptionHelpFormatter, epilog="example:\n python3 agent_join.py --base https://weio.ai --name my-agent --role provide_capability \\\n --kind capability --description \"What my agent does\" --receipt-out receipt.json --key-out key.pem") ap.add_argument("--base", required=True) ap.add_argument("--name", required=True) ap.add_argument("--role", required=True, choices=ROLES) ap.add_argument("--kind", required=True, choices=KINDS) ap.add_argument("--description", required=True) ap.add_argument("--visibility", default="private", choices=VIS) ap.add_argument("--key-out") ap.add_argument("--receipt-out", required=True) o = ap.parse_args() u = urlsplit(o.base) if u.scheme not in ("http", "https") or not u.netloc: die(2, "bad --base") if u.scheme == "http" and u.hostname not in ("127.0.0.1", "localhost", "::1"): die(2, "--base must use https (http only for localhost)") origin = u.scheme + "://" + u.netloc if o.key_out and os.path.abspath(o.key_out) == os.path.abspath(o.receipt_out): die(2, "invalid --key-out / --receipt-out") precheck("--key-out", o.key_out) precheck("--receipt-out", o.receipt_out) probe = os.path.join(os.path.dirname(os.path.abspath(o.receipt_out)), ".agent-join-probe-" + secrets.token_hex(6)) try: write_new(probe, "probe\n") os.unlink(probe) except Exception as e: die(2, f"cannot write next to --receipt-out ({type(e).__name__}); nothing was sent") st, mf = call(origin, "GET", "/.well-known/weio-gateway.json") if st == 200 and isinstance(mf, dict) and mf.get("schema") in ("weio.gateway/0", "weio.gateway/1"): mctx = (mf.get("join") or {}).get("context") if isinstance(mf.get("join"), dict) else None if mctx is not None and mctx != CONTEXT: log({"step": "manifest", "error": "manifest join context differs from the pinned context; refusing to join"}) sys.exit(1) log({"step": "manifest", "status": st}) key = Ed25519PrivateKey.generate() pub_raw = key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw) pub = b64u(pub_raw) if o.key_out: d = key.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption()) write_new(o.key_out, json.dumps({"kty": "OKP", "crv": "Ed25519", "x": pub, "d": b64u(d)}, indent=2) + "\n") record = {"participant_type": "agent", "role": o.role, "name": o.name, "record_kind": o.kind, "description": o.description, "visibility": o.visibility} st, c1 = call(origin, "POST", "/api/participants", {**record, "public_key": pub}) if st != 202: log({"step": "create", "status": st, "error": safe(c1.get("error"))}); sys.exit(1) pid, nonce, sign = c1.get("id"), c1.get("nonce"), c1.get("sign") if not (isinstance(pid, str) and isinstance(nonce, str) and sign == f"{CONTEXT}|{pid}|{nonce}"): log({"step": "challenge", "error": "the message to sign is not " + CONTEXT + "||; refusing to sign"}); sys.exit(1) sig = b64u(key.sign(sign.encode("utf-8"))) st, c2 = call(origin, "POST", "/api/participants/confirm-key", {"id": pid, "nonce": nonce, "signature": sig}) if st != 200: log({"step": "confirm-key", "status": st, "error": safe(c2.get("error"))}); sys.exit(1) token = c2.get("owner_token") if not (isinstance(token, str) and token): log({"step": "confirm-key", "status": 200, "error": "no owner token in the answer"}); sys.exit(1) SECRETS.add(token) reg = c2.get("receipt") if isinstance(c2.get("receipt"), dict) else {} recovery = {"receipt_kind": RECOVERY_KIND, "complete": False, "incomplete_note": "INCOMPLETE: not a completed receipt. The readback has not succeeded; record_as_sent is what was sent.", "registry": origin, "gateway": "agent_join.py", "id": pid, "status": c2.get("status"), "method": reg.get("method"), "activated_at": reg.get("at"), "public_key": pub, "record_as_sent": record, "owner_token": token} try: write_new(o.receipt_out, json.dumps(recovery, indent=2) + "\n") except Exception as e: alt = os.path.join(os.getcwd(), "agent-join-recovery-" + secrets.token_hex(6) + ".json") try: write_new(alt, json.dumps(recovery, indent=2) + "\n") die(1, f"record {safe(pid)} may be active; {o.receipt_out} not writable ({type(e).__name__}); recovery file saved in {alt} (mode 0600)") except SystemExit: raise except Exception: die(1, "the record may be active, but no recovery file could be saved; the token is not shown") log({"step": "receipt", "note": "incomplete recovery file with the owner token saved (mode 0600)", "file": o.receipt_out}) cp = confirm_problems(c2, pid) if ID_RE.match(pid) else ["id"] if cp: log({"step": "confirm-key", "error": "confirm answer is not a complete active activation", "fields": cp}); sys.exit(1) st, rb = call(origin, "GET", "/api/participants/" + quote(pid, safe=""), token=token) view = rb.get("participant") if st == 200 and isinstance(rb, dict) else None rp = readback_problems(view, pid, pub) if rp: log({"step": "readback", "status": st, "fields": rp, "file": o.receipt_out}); sys.exit(1) keys = ["participant_type", "role", "name", "record_kind", "description", "visibility"] receipt = {"receipt_kind": RECEIPT_KIND, "registry": origin, "gateway": "agent_join.py", "id": view["id"], "status": c2["status"], "method": reg["method"], "activated_at": reg["at"], "founding_seq": view.get("founding_seq"), "verification": view["verification"], "public_key": view["public_key"], "record": {k: view[k] for k in keys}, "readback": {"public": "/api/participants/" + view["id"], "profile": "/participants/" + view["id"]}} try: replace_own(o.receipt_out, json.dumps({**receipt, "owner_token": token}, indent=2) + "\n") except Exception as e: log({"step": "receipt", "error": f"could not write the completed receipt ({type(e).__name__}); the recovery file remains"}); sys.exit(1) print(redact(json.dumps({**receipt, "owner_token": f""}, indent=2))) if __name__ == "__main__": main()