# SPDX-License-Identifier: Apache-2.0 """The registration of an Owner (`owner.v1`) on top of review/spec_client.py, written against the text of the specification like that file (§9.1, §13, §4.1, §11.5). An Owner is an Actor with a root key and a Card of its own. This file publishes what makes an Agent the Owner's, in the order §9.1 gives: the Owner's Card, the Owner's delegation, and a version of the Agent's Card that names the Owner. Then it shows what the relationship is for: the Agent's own key cannot drop the Owner, also not by telling the claim step again or by numbering a version ahead of it, and the Owner can revoke the Agent's key. It uses nothing from the reference package. python review/spec_client_owner.py against a Gateway that is already running (its base URL, without /v1) python review/spec_client_owner.py starts the reference Gateway in this process first; without the jcs, base58 and pyhpke packages: python review/run_independent.py probe review/spec_client_owner.py What this file leaves out: delegation chains and their evaluation for a command (§13, `exchange.v1`), and device keys (§11.1). Exit status 0 when every check passes. """ import itertools import json import os import sys from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import spec_client as core # noqa: E402 from spec_client import (Agent, actor_id, b64u, b64u_decode, check, content_digest, http, raw, # noqa: E402 sign_envelope, sign_record, ts, ulid) class Owner: """§9.1 step 1: an `owner:` ID derived from a root key pair, and a Card like any other Actor's (§4.1: a person or an organization uses the `owner:` prefix). This Owner takes no messages, so its Card lists no endpoint.""" def __init__(self, base: str, gateway_id: str): self.base, self.gw = base, gateway_id self.key = Ed25519PrivateKey.generate() self.pub = raw(self.key.public_key()) self.id = actor_id(self.pub, "owner") def publish(self, record: dict) -> dict: """§9.1: publication is a plaintext Envelope addressed to the Gateway's own Actor ID, and `from` signed the Record it carries.""" env = sign_envelope({"v": 1, "id": ulid(), "from": self.id, "to": self.gw, "iat": ts(), "exp": ts(3600), "body": record}, "sig-1", self.key) status, res = http("POST", f"{self.base}/v1/send", env) return {"status": status, "id": env["id"], **res} def card(self) -> dict: return sign_record({"id": ulid(), "type": "agent_card", "v": 1, "issuer": self.id, "iat": ts(), "exp": ts(30 * 86400), "body": {"actor_type": "person", "endpoints": [], "keys": [{"kid": "sig-1", "purpose": "sig", "alg": "ed25519", "pub": b64u(self.pub)}], "supported": {"v": [1], "suites": ["ed25519"], "content_types": []}}}, self.id, "sig-1", self.key) def delegation(self, agent: str, scope: str) -> dict: """§9.1 step 2, §13: a `delegation` from the Owner to the Agent. The scope `represent:` is the relationship: the subject speaks for this Owner.""" return sign_record({"id": ulid(), "type": "delegation", "v": 1, "issuer": self.id, "subject": agent, "iat": ts(), "exp": ts(90 * 86400), "body": {"scope": [scope]}}, self.id, "sig-1", self.key) def revocation(issuer, actor: str, kid: str) -> dict: """§11.5: a key is named `#`; a revocation has no `exp`.""" return sign_record({"id": ulid(), "type": "revocation", "v": 1, "issuer": issuer.id, "iat": ts(), "subject": f"{actor}#{kid}", "body": {"reason": "compromise", "effective_at": ts()}}, issuer.id, "sig-1", issuer.key) def next_version(agent: Agent, change) -> dict: """§4.1, §6.2: an ordinary version keeps the Record's id and the primary key, counts `v` up and names the version before it by content digest in `prev`. `change` edits the body.""" body = dict(agent.card["body"], prev=content_digest(agent.card)) change(body) return sign_record({"id": agent.card["id"], "type": "agent_card", "v": agent.card["v"] + 1, "issuer": agent.id, "iat": ts(), "exp": ts(30 * 86400), "body": body}, agent.id, "sig-1", agent.key) def version_over(agent: Agent, base: dict, v: int, lifetime: int = 30 * 86400) -> dict: """§4.1, §11.5: a version built on `base` and not on the Agent's current version, with `base`'s body. With `v` = `base`'s `v` + 1 it tells again the step that the version after `base` made; with a higher `v` it is a version numbered ahead, which a chain may hold directly after a key event.""" body = dict(base["body"], prev=content_digest(base)) return sign_record({"id": base["id"], "type": "agent_card", "v": v, "issuer": agent.id, "iat": ts(), "exp": ts(lifetime), "body": body}, agent.id, "sig-1", agent.key) def publish(agent: Agent, record: dict) -> dict: env = agent.envelope(agent.gw, record) status, res = http("POST", f"{agent.base}/v1/send", env) return {"status": status, "id": env["id"], **res} def accepted(res: dict) -> bool: return res.get("accepted") == [res["id"]] def refused(res: dict) -> str: return (res.get("rejected") or [{}])[0].get("error", {}).get("code", "") def run(base: str) -> None: tag = ulid()[-6:].lower() nova, bob, mallory = (Agent(base, f"sc-{name}-{tag}") for name in ("nova", "bob", "mallory")) for who in (nova, bob, mallory): who.register() owner = Owner(base, nova.gw) name_owner = lambda body: body.update(owner=owner.id) check("a solo start: the Agent registered without an Owner (§9.1)", "owner" not in nova.card["body"]) check("the Owner's Card registers; it lists no endpoint, since this Owner takes no messages (§7, §9.1)", accepted(owner.publish(owner.card()))) res = publish(nova, next_version(nova, name_owner)) check("a Card that names an Owner is refused as unauthorized while the Gateway holds no delegation from that " "Owner (§9.1)", refused(res) == "unauthorized", json.dumps(res)[:300]) owner.publish(owner.delegation(nova.id, "disclose:cv")) res = publish(nova, next_version(nova, name_owner)) check("a delegation with another scope is not the relationship: the Card is still refused (§9.1)", refused(res) == "unauthorized", json.dumps(res)[:300]) res = owner.publish(owner.delegation(nova.id, f"represent:{owner.id}")) check("the Owner publishes its delegation, scope `represent:` (§9.1, §13)", accepted(res), json.dumps(res)[:300]) first = nova.card # the version before the claim: it names no Owner claimed = next_version(nova, name_owner) res = publish(nova, claimed) check("now the Agent's next version names the Owner and is accepted: a claim (§4.1, §9.1)", accepted(res), json.dumps(res)[:300]) if accepted(res): nova.card = claimed status, answer = http("GET", f"{base}/v1/actors/{nova.id}") grants = [d for d in answer.get("delegations", []) if d["issuer"] == owner.id and d["subject"] == nova.id and f"represent:{owner.id}" in d["body"]["scope"]] check("`resolve` serves the Card with its Owner and the Owner's grant beside it (§9.1, §10.4)", answer["card"]["body"].get("owner") == owner.id and len(grants) == 1) res = publish(nova, next_version(nova, lambda body: body.pop("owner"))) check("the Agent's own key cannot drop the Owner: an ordinary version without `owner` is refused (§4.1)", bool(refused(res)) and not res.get("accepted"), json.dumps(res)[:300]) other = Owner(base, nova.gw) other.publish(other.card()) other.publish(other.delegation(nova.id, f"represent:{other.id}")) res = publish(nova, next_version(nova, lambda body: body.update(owner=other.id))) check("nor replace it with another Owner, even one that has delegated to it (§4.1)", bool(refused(res)) and not res.get("accepted"), json.dumps(res)[:300]) # §4.1, Appendix F.5: a Directory holds a version to this against the latest version it holds as well. The claim # was made by an ordinary version, so a version built on the one before it verifies as a chain and names no Owner. # Of one step told twice a Directory keeps the copy with the smaller content digest (compared as raw bytes), so # the copy that is tried is one with the smaller digest. Copies that differ in their `exp` are made until one has # it: half of them do on average, and fewer when the claim's own digest is small again = next(c for c in (version_over(nova, first, claimed["v"], 30 * 86400 - n) for n in itertools.count(1)) if b64u_decode(content_digest(c)) < b64u_decode(content_digest(claimed))) # as many copies as it takes res = publish(nova, again) check("nor tell the claim step again at the same `v` without the Owner, in the copy a Directory would keep: " "unauthorized (§4.1, Appendix F.5)", refused(res) == "unauthorized", json.dumps(res)[:300]) res = publish(nova, version_over(nova, first, claimed["v"] + 5)) check("nor number a version ahead of the claim, built on the version before it: unauthorized (§4.1)", refused(res) == "unauthorized", json.dumps(res)[:300]) status, answer = http("GET", f"{base}/v1/actors/{nova.id}") check("`resolve` still serves the version that named the Owner", content_digest(answer["card"]) == content_digest(claimed)) res = publish(mallory, revocation(mallory, nova.id, "sig-1")) check("a stranger's revocation of the Agent's key is refused as unauthorized (§11.5)", refused(res) == "unauthorized", json.dumps(res)[:300]) nova.resolve(f"actors/{bob.id}") before = nova.send_text(bob.id, "Before the revocation") check("until then the Agent sends as before", before.get("accepted") == [before["envelope"]["id"]]) res = owner.publish(revocation(owner, nova.id, "sig-1")) check("the Owner revokes the Agent's key, named `#` (§11.5)", accepted(res), json.dumps(res)[:300]) late = nova.send_text(bob.id, "After the revocation") check("and the Gateway refuses what that key signs afterwards, with key_revoked (§11.5)", refused(late) == "key_revoked", json.dumps({k: v for k, v in late.items() if k != "envelope"})[:300]) if __name__ == "__main__": core.main(run)