# SPDX-License-Identifier: Apache-2.0 """A Core client written against the text of the specification, in one file, to show that the text is enough. The client below uses nothing from the reference package: the `cryptography` library for Ed25519, the standard library for everything else, and JCS (RFC 8785), base58btc and ULIDs written out here. Every step names the section of the specification it was written from. The only thing it takes from the package is the Gateway it talks to. python review/spec_client.py [id] against a Gateway that is already running (its base URL, without /v1); `id` is the Actor ID of the publisher of the Gateway list, to be given when the Gateway does not publish the list itself (§9.4) python review/spec_client.py starts the reference Gateway in this process first, and ends with one exchange with the reference client and one across two Gateways; without the jcs, base58 and pyhpke packages: python review/run_independent.py probe review/spec_client.py python review/spec_client.py vectors checks the Core values of vectors/ with the functions below, no Gateway Two agents register, find each other by handle, exchange one plaintext message (L0), acknowledge it, and the sender verifies the Gateway's `delivered`. A third revokes its own key and is refused from then on. Exit status 0 when every check passes. What this file leaves out: it verifies a Card whose primary key is still the inception key and sends to no other (a Card that has rotated or recovered is verified through its key events, §11.5 and Appendix F); it refuses a peer whose key a revocation names without weighing when the revocation takes effect; and it knows no Owners or delegations, so it relies on no device key (§11.1). Two files build on this one: `review/spec_client_sealed.py` adds `sealed.v1`, and `review/spec_client_owner.py` the registration of an Owner (`owner.v1`). """ import base64 import hashlib import json import os import sys import time import urllib.error import urllib.parse import urllib.request from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat FAILS = 0 PUBLISHER = "" # the pinned Actor ID of the Gateway-list publisher; empty: the Gateway an agent joined (§9.4) def check(name: str, ok: bool, detail: str = "") -> None: global FAILS print(("ok " if ok else "FAIL ") + name + (f" ({detail})" if detail and not ok else "")) FAILS += 0 if ok else 1 def attempt(fn): """The value of fn(), or the exception it raised, so that a step that fails is a FAIL line and not a traceback.""" try: return fn() except Exception as e: # noqa: BLE001 (a check reports it) return e def raw(public_key) -> bytes: return public_key.public_bytes(Encoding.Raw, PublicFormat.Raw) # ---- building blocks ----------------------------------------------------------------------------------------------- def jcs(obj) -> bytes: """RFC 8785 for what the protocol puts on the wire: objects, arrays, strings, integers, booleans (§5, §6.2: no floating point, no null). Keys sort by UTF-16 code unit, which json.dumps does for the Basic Multilingual Plane.""" return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8") def b64u(data: bytes) -> str: """§6.2: binary values are base64url without padding.""" return base64.urlsafe_b64encode(data).rstrip(b"=").decode() def b64u_decode(text: str) -> bytes: """§6.2: a binary value has one text, the canonical one of its bytes. Whoever decodes refuses any other: a character outside the alphabet, padding, or a last character whose bits that encode no byte are not zero.""" if not isinstance(text, str) or any(c not in B64U for c in text) or len(text) % 4 == 1: raise ValueError("base64url without padding expected (§6.2)") data = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)) if b64u(data) != text: raise ValueError("not the canonical base64url text of its bytes (§6.2)") return data B64U = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" def base58btc(data: bytes) -> str: n = int.from_bytes(data, "big") out = "" while n: n, r = divmod(n, 58) out = B58[r] + out return "1" * (len(data) - len(data.lstrip(b"\0"))) + out def base58btc_decode(text: str) -> bytes: n = 0 for ch in text: n = n * 58 + B58.index(ch) body = n.to_bytes((n.bit_length() + 7) // 8, "big") return b"\0" * (len(text) - len(text.lstrip("1"))) + body CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" def ulid() -> str: """§4.3: a ULID in its canonical text form, 26 characters of Crockford base32, upper case.""" n = (int(time.time() * 1000) << 80) | int.from_bytes(os.urandom(10), "big") return "".join(CROCKFORD[(n >> (5 * i)) & 31] for i in range(25, -1, -1)) def ts(offset: int = 0) -> str: """§6.2: protocol timestamps are RFC 3339 UTC in whole seconds with the Z suffix.""" return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + offset)) def http(method: str, url: str, body=None): data = json.dumps(body).encode() if body is not None else None # The User-Agent is no rule of the specification: the sample operator's edge answers 403 to urllib's default. req = urllib.request.Request(url, data=data, method=method, headers={"User-Agent": "aep-spec-client/1", **({"Content-Type": "application/json"} if data else {})}) try: with urllib.request.urlopen(req, timeout=40) as r: return r.status, json.loads(r.read() or b"{}") except urllib.error.HTTPError as e: return e.code, json.loads(e.read() or b"{}") # ---- identity (§4.1, §20.1) ---------------------------------------------------------------------------------------- def actor_id(pub: bytes, prefix: str = "agent") -> str: """§4.1, §20.1 step 2: `agent:` + multibase base58btc (`z`) of varint(0xed) ‖ public key, the bytes ed 01 ‖ key.""" return f"{prefix}:z" + base58btc(b"\xed\x01" + pub) def key_of(actor: str) -> bytes: """The inception public key an Actor ID carries (§4.1): the ID is self-certifying.""" raw = base58btc_decode(actor.split(":", 1)[1][1:]) assert raw[:2] == b"\xed\x01" and len(raw) == 34, "not an Ed25519 Actor ID" return raw[2:] def content_digest(rec: dict) -> str: """§7: the content digest of a Card version, SHA-256 of the JCS of the Record without `sigs`.""" return b64u(hashlib.sha256(jcs({k: v for k, v in rec.items() if k != "sigs"})).digest()) # ---- signatures (§11.3) -------------------------------------------------------------------------------------------- def sign_record(rec: dict, actor: str, kid: str, key: Ed25519PrivateKey) -> dict: """§6.2, §11.3: Sign(utf8("aep/1/record") ‖ 0x00 ‖ JCS(Record without sigs) ‖ 0x00 ‖ utf8(signed_at)).""" signed_at = ts() unsigned = {k: v for k, v in rec.items() if k != "sigs"} val = key.sign(b"aep/1/record\x00" + jcs(unsigned) + b"\x00" + signed_at.encode()) rec["sigs"] = [{"actor": actor, "kid": kid, "signed_at": signed_at, "alg": "ed25519", "val": b64u(val)}] return rec def verify_record(rec: dict, pub_of) -> bool: """Every entry of sigs[] against the key its actor and kid name; the issuer must be among the signers (§6).""" unsigned = {k: v for k, v in rec.items() if k != "sigs"} for s in rec["sigs"]: pub = pub_of(s["actor"], s["kid"]) Ed25519PublicKey.from_public_bytes(pub).verify( b64u_decode(s["val"]), b"aep/1/record\x00" + jcs(unsigned) + b"\x00" + s["signed_at"].encode()) return rec["sigs"][0]["actor"] == rec["issuer"] def sign_envelope(env: dict, kid: str, key: Ed25519PrivateKey) -> dict: """§11.3: Sign(utf8("aep/1/envelope") ‖ 0x00 ‖ JCS(Envelope without sig)).""" unsigned = {k: v for k, v in env.items() if k != "sig"} env["sig"] = {"actor": env["from"], "kid": kid, "alg": "ed25519", "val": b64u(key.sign(b"aep/1/envelope\x00" + jcs(unsigned)))} return env def verify_envelope(env: dict, pub_of) -> None: unsigned = {k: v for k, v in env.items() if k != "sig"} assert env["sig"]["actor"] == env["from"] Ed25519PublicKey.from_public_bytes(pub_of(env["from"], env["sig"]["kid"])).verify( b64u_decode(env["sig"]["val"]), b"aep/1/envelope\x00" + jcs(unsigned)) def signed_request(fields: dict, actor: str, kid: str, key: Ed25519PrivateKey, route: str, gateway: str) -> dict: """§10.4: utf8("aep/1/request") ‖ 0x00 ‖ JCS(object without sig) ‖ 0x00 ‖ utf8(route) ‖ 0x00 ‖ utf8(gateway); rid, iat within 300 s, exp at most 5 minutes after iat; sig = { actor, kid, alg, val }.""" obj = {"actor": actor, "kid": kid, **fields, "rid": ulid(), "iat": ts(), "exp": ts(240)} val = key.sign(b"aep/1/request\x00" + jcs(obj) + b"\x00" + route.encode() + b"\x00" + gateway.encode()) obj["sig"] = {"actor": actor, "kid": kid, "alg": "ed25519", "val": b64u(val)} return obj # ---- an agent ------------------------------------------------------------------------------------------------------ class Agent: def __init__(self, base: str, name: str): self.base = base self.key = Ed25519PrivateKey.generate() self.pub = raw(self.key.public_key()) self.id = actor_id(self.pub) self.cards = {} # Actor ID -> the Card this agent verified # §10.4: the Gateway's description, at the root of the origin; the Card in it names the Gateway's ID and URL u = urllib.parse.urlsplit(base) status, info = http("GET", f"{u.scheme}://{u.netloc}/.well-known/aep/gateway") assert status == 200, info self.gw_card = self.verify_card(info["card"]) self.gw = self.gw_card["issuer"] own = [e for e in self.gw_card["body"]["endpoints"] if e["kind"] == "relay" and e["gateway"] == self.gw] assert own and own[0]["url"].rstrip("/") == base + "/v1", "the description does not name this URL (§10.4)" # §4.2, §9.4: a handle is a name under a scope the Gateway issues, which its description lists self.handle = f"{name}.{(info.get('scopes') or ['agent'])[0]}" def verify_card(self, card: dict) -> dict: """§4.1, §20.1 step 5: the Card has not expired, its primary signing key derives the ID, and the Card is signed with it. That is the whole check for a first version and for the ordinary versions after it, which keep the key. A Card that has rotated fails here: this file does not follow key events, and what it cannot verify it does not use.""" assert card["type"] == "agent_card" and card.get("exp", "9999") > ts() primary = [k for k in card["body"]["keys"] if k["purpose"] == "sig" and "delegation" not in k] assert len(primary) == 1 assert actor_id(b64u_decode(primary[0]["pub"]), card["issuer"].split(":")[0]) == card["issuer"] keys = {k["kid"]: b64u_decode(k["pub"]) for k in card["body"]["keys"]} assert verify_record(card, lambda actor, kid: keys[kid] if actor == card["issuer"] else None) self.cards[card["issuer"]] = card return card def pub_of(self, actor: str, kid: str) -> bytes: """§11.1: a device key is relied on only by a verifier that takes delegations[] with the chain. This file takes none, so it verifies under a peer's primary key and under no device key.""" if actor == self.id: return self.pub return next(b64u_decode(k["pub"]) for k in self.cards[actor]["body"]["keys"] if k["kid"] == kid and "delegation" not in k) def envelope(self, to: str, record: dict, ttl: int = 3600) -> dict: """§5: v, id, from, to, iat, exp, body, sig; no enc, so body is the plaintext Record.""" return sign_envelope({"v": 1, "id": ulid(), "from": self.id, "to": to, "iat": ts(), "exp": ts(ttl), "body": record}, "sig-1", self.key) def register(self) -> dict: """§20.1 steps 3 and 4, §9.1: Card v1 in a plaintext Envelope addressed to the Gateway's own Actor ID.""" card = {"id": ulid(), "type": "agent_card", "v": 1, "issuer": self.id, "iat": ts(), "exp": ts(30 * 86400), "body": {"actor_type": "agent", "handles": [self.handle], "keys": [{"kid": "sig-1", "purpose": "sig", "alg": "ed25519", "pub": b64u(self.pub)}], "endpoints": [{"kind": "relay", "gateway": self.gw, "url": self.base + "/v1"}], "supported": {"v": [1], "suites": ["ed25519"], "content_types": ["application/aep.message+json"]}, "policy": {"visibility": "direct", "contact": "open"}}} self.card = sign_record(card, self.id, "sig-1", self.key) status, res = http("POST", f"{self.base}/v1/send", self.envelope(self.gw, self.card)) return {"status": status, **res} def resolve(self, path: str, v1: str = "") -> dict: """§10.4: GET /v1/actors/{id} or /v1/handles/{handle} -> { card, key_events[], delegations[], revocations[] }, at this agent's own Gateway unless another `/v1` base is given. §20.1 step 5: the Card is checked before it is used. This file refuses a peer when a revocation in the answer names any key its Card lists, as `#` (§11.5): that is more than step 5 asks, and it spares the file from weighing `effective_at` against every signature it verifies later.""" status, res = http("GET", f"{(v1 or self.base + '/v1').rstrip('/')}/{path}") assert status == 200, res named = {r.get("subject") for r in res.get("revocations", [])} assert not any(f"{res['card']['issuer']}#{k['kid']}" in named for k in res["card"]["body"]["keys"]), "key_revoked" return self.verify_card(res["card"]) def resolve_handle(self, handle: str) -> dict: """§4.2, §9.4: a handle resolves at the Gateway that holds its scope, and the signed Gateway list says which Gateway that is. The list is believed as far as its publisher, whose Actor ID is pinned: PUBLISHER, or the Gateway this agent joined. The Card that comes back must list the handle (the bidirectional check).""" u = urllib.parse.urlsplit(self.base) status, listed = http("GET", f"{u.scheme}://{u.netloc}/.well-known/aep/gateways") publisher = PUBLISHER or self.gw if publisher == self.gw: self.cards[self.gw] = self.gw_card else: self.resolve(f"actors/{publisher}") assert status == 200 and listed["issuer"] == publisher and verify_record(listed, self.pub_of), listed assert listed["body"]["content_type"] == "application/aep.gateways+json" scope = handle.split(".", 1)[1] holder = next(g for g in listed["body"]["data"]["gateways"] if scope in g["scopes"]) card = self.resolve(f"handles/{handle}", holder["url"]) assert handle in card["body"].get("handles", []) return card def text_record(self, text: str) -> dict: """§7: a payload Record in the Core message format.""" return sign_record({"id": ulid(), "type": "payload", "v": 1, "issuer": self.id, "iat": ts(), "exp": ts(86400), "body": {"content_type": "application/aep.message+json", "data": {"text": text}}}, self.id, "sig-1", self.key) def post(self, env: dict) -> dict: """§20.1 step 5, §10.4: POST /v1/send at this agent's own Gateway, which accepts the Envelope for a recipient it is home to and forwards it for any other. (Posting straight to another Home Gateway is allowed too, with the sender's Card beside the Envelope in `cards[]`.)""" status, res = http("POST", f"{self.base}/v1/send", env) return {"status": status, "envelope": env, **res} def send_text(self, to: str, text: str) -> dict: """§20.1 step 5: sign a payload Record, wrap it in an Envelope, sign the Envelope, send.""" return self.post(self.envelope(to, self.text_record(text))) def sync(self, cursor: str = "0", wait: int = 2) -> dict: """§10.1, §10.4: POST /v1/mailbox/sync with a signed request.""" req = signed_request({"cursor": cursor, "limit": 20, "wait": wait}, self.id, "sig-1", self.key, "POST /v1/mailbox/sync", self.gw) status, res = http("POST", f"{self.base}/v1/mailbox/sync", req) assert status == 200, res return res def ack(self, cursor: str) -> dict: req = signed_request({"cursor": cursor}, self.id, "sig-1", self.key, "POST /v1/mailbox/ack", self.gw) status, res = http("POST", f"{self.base}/v1/mailbox/ack", req) return {"status": status, **res} def check_delivered(sender: Agent, env: dict) -> None: """§7, §10.1: after the recipient's ack, its Home Gateway puts a signed `delivered` into the sender's mailbox. The sender counts it only from the Gateway that the recipient's Card names as its relay.""" home = next(e["gateway"] for e in sender.cards[env["to"]]["body"]["endpoints"] if e["kind"] == "relay") receipts = sender.sync(wait=3)["envelopes"] att = next((e["envelope"] for e in receipts if isinstance(e["envelope"]["body"], dict) and e["envelope"]["body"].get("type") == "attestation" and e["envelope"]["body"].get("subject") == f"env:{sender.id}/{env['id']}"), None) check("the sender's mailbox holds an Envelope from the recipient's Home Gateway (§10.1)", att is not None and att["from"] == home) if att: if home == sender.gw: sender.cards[home] = sender.gw_card else: sender.resolve(f"actors/{home}") # another Gateway's Card, by ID, at the sender's own Gateway verify_envelope(att, sender.pub_of) body = att["body"] verify_record(body, sender.pub_of) digest = b64u(hashlib.sha256(jcs(env)).digest()) check("it is a delivered attestation by that Gateway (§7, §10.1)", body["body"]["kind"] == "delivered" and body["issuer"] == home and body["subject"] == f"env:{sender.id}/{env['id']}") check("it names the Envelope by id and by the SHA-256 of its JCS, sig included (§7)", {"id": env["id"], "digest": digest} in body["body"]["claims"]["envelopes"], json.dumps(body["body"]["claims"])[:300]) def run(base: str) -> None: tag = ulid()[-6:].lower() alice, bob = Agent(base, f"sc-alice-{tag}"), Agent(base, f"sc-bob-{tag}") check("the Gateway's description names its ID and this URL (§10.4)", alice.gw.startswith("agent:z6Mk")) for who in (alice, bob): res = who.register() check(f"registration is accepted (§9.1): {who.handle}", len(res.get("accepted", [])) == 1 and not res.get("rejected"), json.dumps(res)[:300]) status, back = http("GET", f"{base}/v1/actors/{who.id}") check("the Card comes back by ID, byte for byte in JCS (§9.1)", status == 200 and jcs(back["card"]) == jcs(who.card)) card = attempt(lambda: alice.resolve_handle(bob.handle)) check("a handle resolves, at the Gateway the signed list names for its scope, to a Card that lists it (§4.2, §9.4)", isinstance(card, dict) and card["issuer"] == bob.id, repr(card)[:300]) sent = alice.send_text(bob.id, "Dinner next week?") env = sent["envelope"] check("send is answered accepted (§10.4)", sent.get("accepted") == [env["id"]], json.dumps({k: v for k, v in sent.items() if k != "envelope"})[:300]) got = bob.sync() entries = got["envelopes"] check("sync returns the Envelope with its cursor and accepted_at (§10.1)", len(entries) == 1 and {"envelope", "cursor", "accepted_at"} <= set(entries[0])) inbound = entries[0]["envelope"] bob.resolve(f"actors/{inbound['from']}") verify_envelope(inbound, bob.pub_of) rec = inbound["body"] check("the Record verifies and its sender signed it (§11.3)", verify_record(rec, bob.pub_of) and inbound["from"] in [s["actor"] for s in rec["sigs"]]) check("the text arrived", rec["body"]["data"]["text"] == "Dinner next week?") check("ack is answered ok (§10.1)", bob.ack(entries[0]["cursor"]).get("ok") is True) check_delivered(alice, env) again = alice.send_text(bob.id, "Dinner next week?") # a new Envelope id: a new delivery status, rep = http("POST", f"{base}/v1/send", env) # the same Envelope again: its first answer check("a repeated Envelope gets its first answer and is not delivered twice (§10.4, §12.2)", rep.get("accepted") == [env["id"]] and len(bob.sync(cursor=entries[0]["cursor"])["envelopes"]) == 1 and again.get("accepted") == [again["envelope"]["id"]]) tampered = dict(env, id=ulid()) # another id under the old signature status, rep = http("POST", f"{base}/v1/send", tampered) code = (rep.get("rejected") or [{}])[0].get("error", {}).get("code") check("an Envelope whose signature does not cover it is rejected as unauthorized (§8)", code == "unauthorized", json.dumps(rep)[:200]) zoe = Agent(base, f"sc-zoe-{tag}") zoe.register() zoe.resolve(f"actors/{bob.id}") revocation = sign_record({"id": ulid(), "type": "revocation", "v": 1, "issuer": zoe.id, "iat": ts(), "subject": f"{zoe.id}#sig-1", "body": {"reason": "compromise", "effective_at": ts(-3600)}}, # an hour back zoe.id, "sig-1", zoe.key) published = zoe.envelope(zoe.gw, revocation) status, rep = http("POST", f"{base}/v1/send", published) check("an Actor revokes its own key with a revocation that key signs, effective before it was signed, and " "publishes it like a Card (§9.1, §11.5)", rep.get("accepted") == [published["id"]], json.dumps(rep)[:300]) check("a peer whose key a revocation names is not written to (§20.1, §11.5)", isinstance(attempt(lambda: alice.resolve(f"actors/{zoe.id}")), AssertionError)) late = zoe.send_text(bob.id, "Signed after the revocation") code = (late.get("rejected") or [{}])[0].get("error", {}).get("code") check("and the Gateway refuses what that key signs afterwards, with key_revoked (§11.5)", code == "key_revoked", json.dumps({k: v for k, v in late.items() if k != "envelope"})[:300]) def run_vectors(vdir: str) -> None: """The reference vectors, recomputed with the functions of this file: identifiers, JCS, the three signature inputs, content digests and the Envelope digest a `delivered` names. Sealing (HPKE) is not in this file.""" load = lambda name: json.load(open(os.path.join(vdir, name), encoding="utf-8")) sha = lambda data: b64u(hashlib.sha256(data).digest()) unsigned = lambda rec: {k: v for k, v in rec.items() if k != "sigs"} record_input = lambda rec, s: b"aep/1/record\x00" + jcs(unsigned(rec)) + b"\x00" + s["signed_at"].encode() for a in load("keys.json")["actors"]: pub = b64u_decode(a["sig_pub"]) seed_pub = Ed25519PrivateKey.from_private_bytes(bytes.fromhex(a["sig_seed"])).public_key().public_bytes( Encoding.Raw, PublicFormat.Raw) prefix = "owner" if a["actor_type"] in ("person", "organization") else "agent" check(f"keys: {a['name']}'s Actor ID derives from its key (§4.1)", seed_pub == pub and actor_id(pub, prefix) == a["id"]) if "next_key_hash" in a: nxt = Ed25519PrivateKey.from_private_bytes(bytes.fromhex(a["next_sig_seed"])).public_key().public_bytes( Encoding.Raw, PublicFormat.Raw) check(f"keys: {a['name']}'s next_key_hash is SHA-256 of the raw next key (§6.2)", sha(nxt) == a["next_key_hash"]) for v in load("jcs.json")["valid"]: check(f"jcs: {v['name']}", jcs(v["object"]).decode("utf-8") == v["canonical"]) cards = load("cards.json") chain = cards["alice_chain"] pubs = {} # (actor, kid) -> key, from every Card version seen for card in chain + [cards["gateway_card"], cards["bob_card"]]: for k in card["body"]["keys"]: pubs[(card["issuer"], k["kid"])] = b64u_decode(k["pub"]) def verifies(rec: dict) -> bool: try: for s in rec["sigs"]: Ed25519PublicKey.from_public_bytes(pubs[(s["actor"], s["kid"])]).verify(b64u_decode(s["val"]), record_input(rec, s)) return True except Exception: return False for i, card in enumerate(chain): check(f"cards: content digest of alice v{card['v']} (§7)", sha(jcs(unsigned(card))) == cards["alice_content_digests"][i]) check(f"cards: signature input of alice v{card['v']} (§11.3)", record_input(card, card["sigs"][0]).hex() == cards["alice_sig_inputs_hex"][i] and verifies(card)) if i: check(f"cards: alice v{card['v']} names v{chain[i - 1]['v']} by its content digest (§7)", card["body"]["prev"] == cards["alice_content_digests"][i - 1]) first = next(k for k in chain[0]["body"]["keys"] if k["purpose"] == "sig" and "delegation" not in k) last = next(k for k in chain[-1]["body"]["keys"] if k["purpose"] == "sig" and "delegation" not in k) check("cards: alice's ID derives from the primary key of v1 (§4.1)", actor_id(b64u_decode(first["pub"])) == chain[0]["issuer"]) check("cards: the rotation introduces the key v1 committed to (§4.1)", last["kid"] != first["kid"] and sha(b64u_decode(last["pub"])) == first["next_key_hash"]) check("cards: the Gateway's Card names its own ID and URL as its relay endpoint (§10.4)", any(e["kind"] == "relay" and e["gateway"] == cards["gateway_card"]["issuer"] for e in cards["gateway_card"]["body"]["endpoints"]) and verifies(cards["gateway_card"])) re_ = load("records_envelopes.json") rec = re_["record"] check("records: signature input and signature of a Record (§6.2, §11.3)", record_input(rec, rec["sigs"][0]).hex() == re_["record_sig_input_hex"] and verifies(rec)) for name in ("envelope_l0", "envelope_l1"): env = re_[name] body = b"aep/1/envelope\x00" + jcs({k: v for k, v in env.items() if k != "sig"}) ok = body.hex() == re_[name + "_sig_input_hex"] try: Ed25519PublicKey.from_public_bytes(pubs[(env["from"], env["sig"]["kid"])]).verify(b64u_decode(env["sig"]["val"]), body) except Exception: ok = False check(f"envelopes: signature input and signature of {name} (§11.3)", ok) ra = load("requests_attestations.json") req = ra["sync_request"] gw = cards["gateway_card"]["issuer"] body = (b"aep/1/request\x00" + jcs({k: v for k, v in req.items() if k != "sig"}) + b"\x00" + b"POST /v1/mailbox/sync" + b"\x00" + gw.encode()) ok = body.hex() == ra["sync_request_sig_input_hex"] try: Ed25519PublicKey.from_public_bytes(pubs[(req["actor"], req["kid"])]).verify(b64u_decode(req["sig"]["val"]), body) except Exception: ok = False check("requests: signature input and signature of a sync request (§10.4)", ok) att = ra["delivered_attestation"] digest = sha(jcs(re_["envelope_l1"])) check("attestations: delivered names the Envelope by the SHA-256 of its JCS, sig included (§7)", digest == ra["envelope_l1_digest"] and {"id": re_["envelope_l1"]["id"], "digest": digest} in att["body"]["claims"]["envelopes"]) check("attestations: delivered is signed by the Gateway and names the first Envelope it covers (§10.1)", verifies(att) and att["issuer"] == gw and att["subject"] == f"env:{re_['envelope_l1']['from']}/{re_['envelope_l1']['id']}") def run_with_reference(base: str) -> None: """Run only when this file started the Gateway itself, so that the reference package is at hand: the reference client is the other end, and each of the two reads what the other wrote. The client above uses none of it.""" from aep.client import Agent as Reference tag = ulid()[-6:].lower() mine, theirs = Agent(base, f"sc-frank-{tag}"), Reference(base, handle=f"ref-grace-{tag}.agent") mine.register() theirs.register() theirs.resolve(mine.id) theirs.send_text(mine.id, "From the reference client", encrypt=False) # this Card lists no `enc` key (§11.4) entries = mine.sync()["envelopes"] inbound = entries[0]["envelope"] if entries else {} def read() -> str: mine.resolve(f"actors/{theirs.id}") verify_envelope(inbound, mine.pub_of) assert verify_record(inbound["body"], mine.pub_of) and inbound["from"] in [s["actor"] for s in inbound["body"]["sigs"]] return inbound["body"]["body"]["data"]["text"] check("a message from the reference client verifies here (§11.3)", attempt(read) == "From the reference client", repr(attempt(read))[:200]) sent = attempt(lambda: mine.send_text(theirs.id, "From the client written against the text")) texts = attempt(lambda: [rec["body"]["data"]["text"] for _, rec in theirs.sync(wait=2) if rec["type"] == "payload"]) check("and the reference client verifies what this file sent", texts == ["From the client written against the text"], repr(texts)[:200] + " " + repr(sent)[:200]) def run_two_gateways(base: str) -> None: """Run only when this file starts the Gateways itself: two more reference Gateways that list each other, and one agent at each. What the sender's own Gateway answers, how the Envelope travels, and whose `delivered` returns.""" from aep.gateway import Gateway ports = (18581, 18582) urls = [f"http://127.0.0.1:{port}" for port in ports] for i in (0, 1): Gateway(urls[i], ("one.agent", "two.agent")[i], peers=[urls[1 - i]], local_endpoints=True).serve("127.0.0.1", ports[i]) tag = ulid()[-6:].lower() alice, bob = Agent(urls[0], f"sc-alice-{tag}"), Agent(urls[1], f"sc-bob-{tag}") alice.register() bob.register() card = attempt(lambda: alice.resolve_handle(bob.handle)) check("a handle under another Gateway's scope resolves at that Gateway, which the sender's signed list names " "(§4.2, §9.4)", isinstance(card, dict) and card["issuer"] == bob.id, repr(card)[:300]) sent = alice.send_text(bob.id, "Across two Gateways") env = sent["envelope"] check("the sender's own Gateway answers queued and forwards the Envelope (§10.4)", sent.get("queued") == [env["id"]], json.dumps({k: v for k, v in sent.items() if k != "envelope"})[:300]) entries = bob.sync(wait=5)["envelopes"] inbound = entries[0]["envelope"] if entries else {} check("it arrives at the recipient's Home Gateway with its values unchanged (§5, §10.4)", jcs(inbound) == jcs(env)) def read() -> str: bob.resolve(f"actors/{alice.id}") # at bob's own Gateway, which asks the Gateways on its list verify_envelope(inbound, bob.pub_of) assert verify_record(inbound["body"], bob.pub_of) and inbound["from"] in [s["actor"] for s in inbound["body"]["sigs"]] return inbound["body"]["body"]["data"]["text"] check("the recipient resolves the sender by ID at its own Gateway and verifies the message (§10.4, §11.3)", attempt(read) == "Across two Gateways", repr(attempt(read))[:200]) check("ack is answered ok (§10.1)", bool(entries) and bob.ack(entries[0]["cursor"]).get("ok") is True) check_delivered(alice, env) def main(run, run_vectors=None, more=None) -> None: """The three ways to start this file, and the two files beside it that build on it. `more` runs only when the file started the Gateway itself, which is when the reference package is at hand.""" global PUBLISHER here = os.path.dirname(os.path.abspath(__file__)) if len(sys.argv) > 2 and sys.argv[1] != "vectors": PUBLISHER = sys.argv[2] if len(sys.argv) > 1 and sys.argv[1] == "vectors": if run_vectors is None: sys.exit("this file has no vector mode") run_vectors(sys.argv[2] if len(sys.argv) > 2 else os.path.join(here, "..", "vectors")) elif len(sys.argv) > 1: run(sys.argv[1].rstrip("/")) else: import threading sys.path.append(os.path.join(here, "..", "ref")) from aep import gateway # the other end of the test; the client above does not use it port = 18580 threading.Thread(target=gateway.main, args=(["--port", str(port), "--scope", "agent"],), daemon=True).start() for _ in range(50): try: urllib.request.urlopen(f"http://127.0.0.1:{port}/.well-known/aep/gateway", timeout=1).read() break except OSError: time.sleep(0.2) run(f"http://127.0.0.1:{port}") if more: more(f"http://127.0.0.1:{port}") print(f"{FAILS} failure(s)") sys.exit(1 if FAILS else 0) if __name__ == "__main__": main(run, run_vectors, lambda base: (run_with_reference(base), run_two_gateways(base)))