# ruff: noqa: E402, E501 — generated: the embedded sources come first """aid.discover@v1: AID discovery end to end — what a careful AID client would conclude. Give `domain`. The agent reads _agent. through two DNS-over-HTTPS resolvers and applies the record rules (the aid-record agent), then, when the record has a key, asks the endpoint for a fresh proof bound to the domain and applies every verifier rule (the aid-proof agent) to the answer it got. The challenge is the hearth's CALL_NONCE for this call: 32 random bytes the endpoint could not have seen before. The endpoint is reached only because the caller named it: `domain` (or, when the record points to another host, `endpoint`) is one of this agent's egress input fields, so the hearth lets this one call fetch that one host, over https, from public addresses only, without redirects. Verdicts: proven_bound, proven_unbound, proof_failed, found_unproven, endpoint_host_not_named, no_valid_record, lookup_failed (no resolver answered: retry). GENERATED by hestia-agents/scripts/build_aid_discover.py from the two agents' sources, embedded below verbatim; edit those, not this file. """ RECORD_SOURCE = '"""AID record lookup and validation: what an AID v2.1.1 client finds for a domain.\n\nGive `domain`. The agent asks two public DNS-over-HTTPS resolvers (Cloudflare and Google) for\nthe TXT records at _agent., that exact host and no parent, and applies the client\nalgorithm of the specification (sections 2.1 to 2.3): parse each answer, validate it by its\nversion, prefer aid2, refuse two valid records of one version as ambiguous.\n\nOr give `txt`, the TXT strings you are about to publish, to validate them with no lookup.\n\nThe sandbox has no sockets: fetch() asks the hearth, which talks only to the two resolvers\nthis agent\'s deploy names. The answer says what each resolver returned and whether it\nvalidated DNSSEC (the AD flag). It is an observation of public DNS at the resolvers\' Date,\nsigned by this agent, and no more than that. Not done here: the endpoint proof for `k` (send\nthe exchange to aid.proof.verify), the .well-known fallback, and _agent._ names.\n"""\n\nimport hashlib\nimport json\n\nSPEC = "AID v2.1.1, sections 2.1-2.3"\nRESOLVERS = (("cloudflare", "https://cloudflare-dns.com/dns-query"),\n ("google", "https://dns.google/resolve"))\nPROTOCOLS = ("a2a", "graphql", "grpc", "local", "mcp", "openapi", "ucp", "websocket", "zeroconf")\nAUTHS = ("apikey", "basic", "custom", "mtls", "none", "oauth2_code", "oauth2_device", "pat")\nLOCAL_SCHEMES = ("docker", "npx", "pip")\nALIASES = (("uri", "u"), ("proto", "p"), ("auth", "a"), ("desc", "s"), ("docs", "d"),\n ("dep", "e"), ("pka", "k"), ("kid", "i"))\nERRORS = {1000: "ERR_NO_RECORD", 1001: "ERR_INVALID_TXT", 1002: "ERR_UNSUPPORTED_PROTO",\n 1004: "ERR_DNS_LOOKUP_FAILED"}\nDNS_STATUS = {0: "NOERROR", 1: "FORMERR", 2: "SERVFAIL", 3: "NXDOMAIN", 4: "NOTIMP", 5: "REFUSED"}\nMONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")\n_URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"\n_HOST = "abcdefghijklmnopqrstuvwxyz0123456789-"\n\n\nclass _Invalid(ValueError):\n """A record that fails validation: the specification\'s ERR_INVALID_TXT (1001)."""\n\n\nclass _Unsupported(_Invalid):\n """A record whose protocol token is not in the registry: ERR_UNSUPPORTED_PROTO (1002)."""\n\n\n# ------------------------------------------------------------------ the key\n\n\ndef _key_bytes(k):\n if "=" in k or not k or any(char not in _URL for char in k):\n raise _Invalid("k must be unpadded base64url")\n if len(k) % 4 == 1:\n raise _Invalid("k is not valid base64url")\n bits, count, size = 0, 0, 0\n for char in k:\n bits = (bits << 6) | _URL.find(char)\n count += 6\n if count >= 8:\n count -= 8\n size += 1\n bits &= (1 << count) - 1\n if size != 32:\n raise _Invalid("k must decode to exactly 32 bytes, it decodes to " + str(size))\n return bits == 0\n\n\ndef keyid(k):\n """RFC 7638 thumbprint of the JWK {crv, kty, x}: the keyid an endpoint proof must name."""\n jwk = \'{"crv":"Ed25519","kty":"OKP","x":"\' + k + \'"}\'\n digest = hashlib.sha256(jwk.encode("utf-8")).digest()\n out, bits, count = "", 0, 0\n for byte in digest:\n bits = (bits << 8) | byte\n count += 8\n while count >= 6:\n count -= 6\n out += _URL[(bits >> count) & 63]\n bits &= (1 << count) - 1\n if count:\n out += _URL[(bits << (6 - count)) & 63]\n return out\n\n\n# ------------------------------------------------------------------ one record\n\n\ndef _absolute(uri, scheme):\n rest = uri[len(scheme):]\n host = rest.split("/", 1)[0].split("?", 1)[0].split("#", 1)[0]\n return uri.startswith(scheme) and bool(host) and " " not in uri\n\n\ndef _timestamp(text):\n """True for YYYY-MM-DDTHH:MM:SSZ with plausible fields."""\n if len(text) != 20 or text[4] + text[7] + text[10] + text[13] + text[16] + text[19] != "--T::Z":\n return False\n digits = text[0:4] + text[5:7] + text[8:10] + text[11:13] + text[14:16] + text[17:19]\n if not (digits.isdigit() and digits.isascii()):\n return False\n return (1 <= int(text[5:7]) <= 12 and 1 <= int(text[8:10]) <= 31 and int(text[11:13]) <= 23\n and int(text[14:16]) <= 59 and int(text[17:19]) <= 60)\n\n\ndef parse(txt):\n """(record, warnings) for one TXT string, or raises _Invalid. Canonical field names."""\n raw = {}\n for pair in txt.split(";"):\n pair = pair.strip()\n if not pair:\n continue\n name, eq, value = pair.partition("=")\n name, value = name.strip().lower(), value.strip()\n if not eq:\n raise _Invalid("not a key=value pair: " + pair[:40])\n if not name or not value:\n raise _Invalid("empty key or value in: " + pair[:40])\n if name in raw:\n raise _Invalid("key given twice: " + name)\n raw[name] = value\n version = raw.get("v") or raw.get("version")\n if "v" in raw and "version" in raw:\n raise _Invalid("both version and its alias v are given")\n if version is None:\n raise _Invalid("no v: not an AID record")\n if version not in ("aid1", "aid2"):\n raise _Invalid("version " + version + " is not aid1 or aid2")\n fields, long_keys = {"v": version}, ["version"] if "version" in raw else []\n for full, alias in ALIASES:\n if full in raw and alias in raw:\n raise _Invalid("both " + full + " and its alias " + alias + " are given")\n if full in raw:\n long_keys.append(full)\n value = raw.get(full) or raw.get(alias)\n if value is not None:\n fields[full] = value\n if "uri" not in fields:\n raise _Invalid("no u (uri): required")\n if "proto" not in fields:\n raise _Invalid("no p (proto): required")\n proto, uri = fields["proto"], fields["uri"]\n if proto not in PROTOCOLS:\n raise _Unsupported("protocol " + proto + " is not in the registry ("\n + ", ".join(PROTOCOLS) + ")")\n if "auth" in fields and fields["auth"] not in AUTHS:\n raise _Invalid("auth " + fields["auth"] + " is not in the registry ("\n + ", ".join(AUTHS) + ")")\n if len(fields.get("desc", "").encode("utf-8")) > 60:\n raise _Invalid("s (desc) is " + str(len(fields["desc"].encode("utf-8")))\n + " UTF-8 bytes; the limit is 60")\n if "docs" in fields and not _absolute(fields["docs"], "https://"):\n raise _Invalid("d (docs) must be an absolute https:// URL")\n if "dep" in fields and not _timestamp(fields["dep"]):\n raise _Invalid("e (dep) must be an ISO 8601 UTC time such as 2027-01-01T00:00:00Z")\n canonical_key = True\n if version == "aid2":\n if "kid" in fields:\n raise _Invalid("kid / i is not allowed in an aid2 record")\n if "pka" in fields:\n canonical_key = _key_bytes(fields["pka"])\n elif "pka" in fields and "kid" not in fields:\n raise _Invalid("an aid1 record with k needs i (kid)")\n if proto == "local":\n scheme = uri.split(":", 1)[0] if ":" in uri else ""\n if scheme not in LOCAL_SCHEMES:\n raise _Invalid("a local agent\'s u must start with one of "\n + ", ".join(LOCAL_SCHEMES) + ":")\n elif proto == "zeroconf":\n if not uri.startswith("zeroconf:"):\n raise _Invalid("a zeroconf agent\'s u must start with zeroconf:")\n elif proto == "websocket":\n if not _absolute(uri, "wss://"):\n raise _Invalid("a websocket agent\'s u must be an absolute wss:// URL")\n elif not _absolute(uri, "https://"):\n raise _Invalid("a remote agent\'s u must be an absolute https:// URL")\n warnings = []\n if len(txt.encode("utf-8")) > 255:\n warnings.append("the record is " + str(len(txt.encode("utf-8"))) + " bytes; above 255 it "\n "is split into several strings, which some DNS panels handle badly")\n if long_keys:\n warnings.append("uses the long key " + ", ".join(long_keys) + "; providers should "\n "publish the one-letter aliases")\n if "auth" not in fields:\n warnings.append("no a (auth): recommended, so a client knows how to authenticate")\n if version == "aid1":\n warnings.append("an aid1 record: the legacy format, read only when no valid aid2 "\n "record exists")\n elif "pka" not in fields:\n warnings.append("no k: a client cannot check that the endpoint belongs to this record")\n elif not canonical_key:\n warnings.append("k has non-zero spare bits in its last character: it decodes, but two "\n "spellings of one key give two different keyids")\n return fields, warnings\n\n\ndef select(strings, at):\n """The specification\'s section 2.3 over the TXT strings found at one name."""\n seen, valid = [], {"aid1": [], "aid2": []}\n for txt in strings:\n entry = {"txt": txt}\n try:\n record, warnings = parse(txt)\n except _Invalid as exc:\n entry.update(valid=False, problem=str(exc),\n code=1002 if isinstance(exc, _Unsupported) else 1001)\n else:\n entry.update(valid=True, version=record["v"])\n valid[record["v"]].append((txt, record, warnings))\n seen.append(entry)\n out = {"found": bool(strings), "valid": False}\n chosen = valid["aid2"] or valid["aid1"]\n if not strings:\n out.update(code=1000, detail="no TXT record at this name")\n elif not chosen:\n codes = [entry["code"] for entry in seen]\n out.update(code=1002 if codes and all(code == 1002 for code in codes) else 1001,\n detail="no TXT record at this name is a valid AID record")\n elif len(chosen) > 1:\n out.update(code=1001, detail=str(len(chosen)) + " valid " + chosen[0][1]["v"]\n + " records: ambiguous, a client must not pick one by answer order")\n else:\n txt, record, warnings = chosen[0]\n out.update(valid=True, code=0, txt=txt, record=record, warnings=list(warnings))\n if "pka" in record and record["v"] == "aid2":\n out["pka"] = {"k": record["pka"], "keyid": keyid(record["pka"]),\n "next": "a client MUST verify the endpoint proof (Appendix B) before "\n "using this endpoint; aid.proof.verify checks an exchange"}\n if "dep" in record and at:\n if record["dep"] <= at:\n out["deprecated"] = True\n out["warnings"].append("deprecated since " + record["dep"]\n + ": a client should stop using this endpoint")\n else:\n out["warnings"].append("will be deprecated at " + record["dep"])\n if out["code"]:\n out["error"] = ERRORS[out["code"]]\n others = [entry for entry in seen if not (out["valid"] and entry["txt"] == out["txt"])]\n if others:\n out["other_records"] = others\n return out\n\n\n# ------------------------------------------------------------------ DNS over HTTPS\n\n\ndef host(value):\n """The exact host to look up: lower-case ASCII (A-label for an IDN), no dot at the end."""\n text = value.strip().lower()\n if text.endswith("."):\n text = text[:-1]\n if text.startswith("_agent."):\n text = text[len("_agent."):]\n if not text.isascii():\n raise ValueError("give the domain in its A-label form (xn--...), not in Unicode")\n labels = text.split(".")\n if len(text) > 245 or len(labels) < 2:\n raise ValueError("domain must be a host name such as example.com")\n for label in labels:\n if not 1 <= len(label) <= 63 or any(char not in _HOST for char in label) \\\n or label.startswith("-") or label.endswith("-"):\n raise ValueError("domain must be a host name with no scheme, port or path")\n return text\n\n\ndef character_strings(data):\n """One TXT answer as a resolver\'s JSON gives it. Quoted character-strings (Cloudflare) are\n unescaped and joined in order, as the specification requires for a split record; an\n unquoted value (Google) is taken as it is."""\n text = data.strip()\n if not text.startswith(\'"\'):\n return text\n out, index, size = bytearray(), 0, len(text)\n while index < size:\n if text[index] in " \\t":\n index += 1\n continue\n if text[index] != \'"\':\n return text\n index += 1\n while index < size and text[index] != \'"\':\n if text[index] == "\\\\" and index + 1 < size:\n number = text[index + 1:index + 4]\n if len(number) == 3 and number.isdigit() and number.isascii() and int(number) < 256:\n out.append(int(number))\n index += 4\n else:\n out += text[index + 1].encode("utf-8")\n index += 2\n else:\n out += text[index].encode("utf-8")\n index += 1\n index += 1\n return bytes(out).decode("utf-8", "replace")\n\n\ndef http_date(text):\n """An HTTP Date header as YYYY-MM-DDTHH:MM:SSZ, or None."""\n parts = (text or "").replace(",", " ").split()\n if len(parts) != 6 or parts[5] != "GMT" or parts[2] not in MONTHS:\n return None\n clock = parts[4].split(":")\n if not (parts[1].isdigit() and parts[3].isdigit() and len(parts[3]) == 4 and len(clock) == 3\n and all(len(item) == 2 and item.isdigit() for item in clock)):\n return None\n stamp = (parts[3] + "-" + str(MONTHS.index(parts[2]) + 1).zfill(2) + "-" + parts[1].zfill(2)\n + "T" + ":".join(clock) + "Z")\n return stamp if _timestamp(stamp) else None\n\n\ndef resolve(name):\n """Ask each resolver for TXT at `name`. One fetch round per resolver."""\n answers = []\n for label, base in RESOLVERS:\n seen = {"resolver": label, "ok": False}\n answers.append(seen)\n try:\n reply = fetch(base + "?name=" + name + "&type=TXT&do=1", # noqa: F821 — the sandbox provides fetch()\n headers={"accept": "application/dns-json"})\n except Exception as exc: # the hearth refused the request (budget); never the fetch signal\n seen["problem"] = str(exc)[:160]\n continue\n if not reply.ok:\n seen["problem"] = reply.error or ("the resolver answered HTTP " + str(reply.status))\n continue\n try:\n body = json.loads(reply.text)\n status = int(body["Status"])\n except (ValueError, KeyError, TypeError):\n seen["problem"] = "the resolver\'s answer is not DNS JSON"\n continue\n seen["dns_status"] = DNS_STATUS.get(status, "RCODE " + str(status))\n seen["date"] = http_date(reply.headers.get("date"))\n if status not in (0, 3):\n seen["problem"] = "the resolver could not answer (" + seen["dns_status"] + ")"\n continue\n rows = [row for row in body.get("Answer") or [] if isinstance(row, dict)]\n texts = [row for row in rows if row.get("type") == 16 and isinstance(row.get("data"), str)]\n seen["ok"] = True\n seen["dnssec_validated"] = body.get("AD") is True\n seen["txt"] = [character_strings(row["data"]) for row in texts]\n ttls = [row["TTL"] for row in texts if isinstance(row.get("TTL"), int)]\n if ttls:\n seen["ttl"] = min(ttls)\n cnames = [str(row.get("data")).rstrip(".") for row in rows if row.get("type") == 5]\n if cnames:\n seen["cname"] = cnames\n return answers\n\n\n# ------------------------------------------------------------------ the handler\n\n\ndef handle(payload):\n if not isinstance(payload, dict):\n raise ValueError("send an object with domain, or with txt")\n at = payload.get("at")\n if at is not None and not (isinstance(at, str) and _timestamp(at)):\n raise ValueError("at must be an ISO 8601 UTC time such as 2026-11-19T20:00:00Z")\n txt = payload.get("txt")\n if txt is not None:\n strings = [txt] if isinstance(txt, str) else txt\n if not isinstance(strings, list) or not strings or len(strings) > 16 \\\n or not all(isinstance(item, str) and len(item) <= 4096 for item in strings):\n raise ValueError("txt must be one TXT string or a list of up to 16")\n out = select([item.strip() for item in strings], at)\n out.update(mode="validate", spec=SPEC)\n return out\n if not isinstance(payload.get("domain"), str):\n raise ValueError("give domain (a host name) or txt (the TXT strings to validate)")\n domain = host(payload["domain"])\n name = "_agent." + domain\n answers = resolve(name)\n usable = [seen for seen in answers if seen["ok"]]\n dns = {"resolvers": answers}\n if not usable:\n out = {"found": False, "valid": False, "code": 1004, "error": ERRORS[1004],\n "detail": "neither resolver gave a usable answer"}\n else:\n first = usable[0]\n observed = at or first.get("date")\n out = select(first["txt"], observed)\n if observed and not at:\n out["observed_at"] = observed\n dns["dnssec_validated"] = all(seen["dnssec_validated"] for seen in usable)\n if len(usable) > 1:\n dns["resolvers_agree"] = all(sorted(seen["txt"]) == sorted(first["txt"])\n for seen in usable)\n if not dns["resolvers_agree"]:\n out.setdefault("warnings", []).append(\n "the two resolvers returned different records: one of them may still hold "\n "the previous version in its cache (see ttl); the verdict uses "\n + first["resolver"])\n if out["valid"] and not dns["dnssec_validated"]:\n out["warnings"].append("the answer is not DNSSEC-validated (AD flag not set): the "\n "record can be forged on the way from the zone to a client")\n if out["code"] == 1000:\n out["detail"] += "; the .well-known fallback of Appendix C is not checked here"\n out.update(mode="lookup", domain=domain, query=name, dns=dns, spec=SPEC)\n return out\n' PROOF_SOURCE = '"""AID endpoint proof (PKA), checked for an exchange you made. AID v2.1.1, Appendix B.\n\nA domain\'s `_agent` TXT record may carry `k`, an Ed25519 key. A client then asks the endpoint\nto sign the response (RFC 9421, `Accept-Signature: aid-pka=...`), and accepts the endpoint only\nif every rule of Appendix B.6 holds, plus B.7 when the proof is bound to a domain. This agent\napplies those rules to what you send:\n\n k the key from the record (or `record`: the whole TXT string)\n request {uri, nonce, method (GET), aid_domain (the AID-Domain header, if you sent one)}\n response {status, headers: {signature-input, signature, cache-control}}\n now unix seconds when the response arrived: the proof is valid for at most 300 s\n\nThe sandbox makes no request itself, so it judges the exchange you describe: it cannot know\nthat you really sent that nonce or reached that URI. `signature_base` in the answer is the\nexact text the signature must cover, which is what a signer\'s author needs when a proof fails.\n\nPure Python Ed25519 (RFC 8032), cofactorless like OpenSSL, refusing non-canonical points,\nS >= L and small-order keys.\n"""\n\nimport hashlib\n\nSPEC = "AID v2.1.1, Appendix B (PKA handshake, B.7 domain binding)"\nTAG = "aid-pka-v2"\nBASE = [\'"@method";req\', \'"@target-uri";req\', \'"@authority";req\', \'"@status"\']\nBOUND = BASE[:3] + [\'"aid-domain";req\', \'"@status"\']\nPARAMS = ("created", "expires", "keyid", "alg", "nonce", "tag")\nMAX_WINDOW = 300\nDEFAULT_SKEW = 30\n\n# ------------------------------------------------------------------ Ed25519\n\n_Q = 2 ** 255 - 19\n_L = 2 ** 252 + 27742317777372353535851937790883648493\n_D = -121665 * pow(121666, _Q - 2, _Q) % _Q\n_I = pow(2, (_Q - 1) // 4, _Q)\n_IDENTITY = (0, 1, 1, 0)\n\n\ndef _recover_x(y, sign):\n if y >= _Q:\n return None\n x2 = (y * y - 1) * pow(_D * y * y + 1, _Q - 2, _Q) % _Q\n if x2 == 0:\n return None if sign else 0\n x = pow(x2, (_Q + 3) // 8, _Q)\n if (x * x - x2) % _Q:\n x = x * _I % _Q\n if (x * x - x2) % _Q:\n return None\n if x & 1 != sign:\n x = _Q - x\n return x\n\n\ndef _decode(raw):\n y = int.from_bytes(raw, "little")\n sign = y >> 255\n y &= (1 << 255) - 1\n x = _recover_x(y, sign)\n return None if x is None else (x, y, 1, x * y % _Q)\n\n\n_BY = 4 * pow(5, _Q - 2, _Q) % _Q\n_B = (_recover_x(_BY, 0), _BY, 1, _recover_x(_BY, 0) * _BY % _Q)\n\n\ndef _add(p, q):\n a = (p[1] - p[0]) * (q[1] - q[0]) % _Q\n b = (p[1] + p[0]) * (q[1] + q[0]) % _Q\n c = 2 * p[3] * q[3] * _D % _Q\n d = 2 * p[2] * q[2] % _Q\n e, f, g, h = b - a, d - c, d + c, b + a\n return (e * f % _Q, g * h % _Q, f * g % _Q, e * h % _Q)\n\n\ndef _double(p):\n a = p[0] * p[0] % _Q\n b = p[1] * p[1] % _Q\n c = 2 * p[2] * p[2] % _Q\n h = a + b\n e = h - (p[0] + p[1]) * (p[0] + p[1])\n g = a - b\n f = c + g\n return (e * f % _Q, g * h % _Q, f * g % _Q, e * h % _Q)\n\n\ndef _same(p, q):\n return (p[0] * q[2] - q[0] * p[2]) % _Q == 0 and (p[1] * q[2] - q[1] * p[2]) % _Q == 0\n\n\ndef _two_mul(k1, p1, k2, p2):\n both = _add(p1, p2)\n acc = _IDENTITY\n for i in range(max(k1.bit_length(), k2.bit_length()) - 1, -1, -1):\n acc = _double(acc)\n b1, b2 = (k1 >> i) & 1, (k2 >> i) & 1\n if b1 and b2:\n acc = _add(acc, both)\n elif b1:\n acc = _add(acc, p1)\n elif b2:\n acc = _add(acc, p2)\n return acc\n\n\ndef ed25519_verify(public, message, signature):\n """(ok, reason) per RFC 8032 5.1.7, cofactorless; small-order keys refused."""\n if len(signature) != 64:\n return False, "the signature is " + str(len(signature)) + " bytes, Ed25519 needs 64"\n a = _decode(public)\n if a is None:\n return False, "k is not a valid curve point"\n small = a\n for _ in range(3):\n small = _double(small)\n if _same(small, _IDENTITY):\n return False, "k has small order: it verifies forged signatures"\n r = _decode(signature[:32])\n if r is None:\n return False, "signature R is not a valid curve point"\n s = int.from_bytes(signature[32:], "little")\n if s >= _L:\n return False, "signature S is not reduced (S >= L)"\n k = int.from_bytes(hashlib.sha512(signature[:32] + public + message).digest(), "little") % _L\n neg_a = ((-a[0]) % _Q, a[1], a[2], (-a[3]) % _Q)\n if _same(_two_mul(s, _B, k, neg_a), r):\n return True, "Ed25519 verifies over the signature base"\n return False, "Ed25519 does not verify for this key over the signature base"\n\n\n# ------------------------------------------------------------------ encodings\n\n_STD = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"\n_URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"\n\n\ndef _unbase64(text, alphabet):\n if not text or len(text) % 4 == 1:\n raise ValueError("wrong length")\n out, bits, count = bytearray(), 0, 0\n for char in text:\n value = alphabet.find(char)\n if value < 0:\n raise ValueError("a character outside the alphabet")\n bits = (bits << 6) | value\n count += 6\n if count >= 8:\n count -= 8\n out.append((bits >> count) & 0xFF)\n bits &= (1 << count) - 1\n return bytes(out)\n\n\ndef _base64url(raw):\n out, bits, count = "", 0, 0\n for byte in raw:\n bits = (bits << 8) | byte\n count += 8\n while count >= 6:\n count -= 6\n out += _URL[(bits >> count) & 63]\n bits &= (1 << count) - 1\n if count:\n out += _URL[(bits << (6 - count)) & 63]\n return out\n\n\ndef keyid(k):\n """RFC 7638 thumbprint of the JWK {crv, kty, x}, as Appendix B.2 spells it."""\n jwk = \'{"crv":"Ed25519","kty":"OKP","x":"\' + k + \'"}\'\n return _base64url(hashlib.sha256(jwk.encode("utf-8")).digest())\n\n\n# ------------------------------------------------------------------ structured fields\n\n\nclass _Bad(ValueError):\n pass\n\n\ndef _header(headers, name):\n for key, value in headers.items():\n if str(key).strip().lower() == name:\n if isinstance(value, list):\n value = ", ".join(str(item) for item in value)\n if not isinstance(value, str):\n raise ValueError("response.headers." + name + " must be a string")\n return value.strip()\n return None\n\n\ndef _member(value, label, header):\n """The raw value of one member of a Structured Field dictionary. Commas inside quoted\n strings and inner lists do not split members."""\n parts, start, depth, quoted, escaped = [], 0, 0, False, False\n for index, char in enumerate(value):\n if quoted:\n if escaped:\n escaped = False\n elif char == "\\\\":\n escaped = True\n elif char == \'"\':\n quoted = False\n elif char == \'"\':\n quoted = True\n elif char == "(":\n depth += 1\n elif char == ")":\n depth -= 1\n elif char == "," and depth == 0:\n parts.append(value[start:index])\n start = index + 1\n parts.append(value[start:])\n found = []\n for part in parts:\n name, eq, raw = part.strip().partition("=")\n if eq and name.strip() == label:\n found.append(raw.strip())\n if not found:\n raise _Bad(header + " has no " + label + " member")\n if len(found) > 1:\n raise _Bad(header + " has " + str(len(found)) + " " + label\n + " members; which one counts is ambiguous")\n return found[0]\n\n\ndef _items(inner):\n out, start, quoted = [], 0, False\n for index, char in enumerate(inner):\n if char == \'"\':\n quoted = not quoted\n elif char == " " and not quoted:\n if index > start:\n out.append(inner[start:index])\n start = index + 1\n if len(inner) > start:\n out.append(inner[start:])\n return out\n\n\ndef _params(text):\n """Parameters after the covered list: {name: (kind, value)}, kind \'string\' or \'bare\'."""\n out, index, size = {}, 0, len(text)\n while index < size:\n if text[index] != ";":\n raise _Bad("unexpected text after the covered list: " + text[index:index + 20])\n index += 1\n end = index\n while end < size and text[end] not in "=;":\n end += 1\n name = text[index:end]\n if not name or name in out:\n raise _Bad("parameter \'" + name + "\' is empty or given twice")\n if end >= size or text[end] == ";":\n raise _Bad("parameter " + name + " has no value")\n end += 1\n if end < size and text[end] == \'"\':\n end += 1\n chars = []\n while True:\n if end >= size:\n raise _Bad("parameter " + name + ": the string is not closed")\n char = text[end]\n if char == "\\\\":\n if end + 1 >= size or text[end + 1] not in \'"\\\\\':\n raise _Bad("parameter " + name + ": bad escape")\n chars.append(text[end + 1])\n end += 2\n elif char == \'"\':\n break\n else:\n chars.append(char)\n end += 1\n out[name] = ("string", "".join(chars))\n index = end + 1\n else:\n stop = end\n while stop < size and text[stop] != ";":\n stop += 1\n out[name] = ("bare", text[end:stop])\n index = stop\n return out\n\n\ndef _signature_input(raw):\n """(covered items, parameters) of an aid-pka Signature-Input member."""\n if not raw.startswith("("):\n raise _Bad("Signature-Input aid-pka is not an inner list")\n close = raw.find(")")\n if close < 0:\n raise _Bad("Signature-Input aid-pka: the covered list is not closed")\n params = _params(raw[close + 1:])\n for name in params:\n if name not in PARAMS:\n raise _Bad("Signature-Input has a parameter the profile does not define: " + name)\n for name in PARAMS:\n if name not in params:\n raise _Bad("Signature-Input has no " + name)\n for name in ("created", "expires"):\n kind, value = params[name]\n if kind != "bare" or not value.isdigit() or not value.isascii():\n raise _Bad(name + " must be a bare integer")\n for name in ("keyid", "alg", "nonce", "tag"):\n if params[name][0] != "string":\n raise _Bad(name + " must be a quoted string")\n return _items(raw[1:close].strip()), {name: params[name][1] for name in PARAMS}\n\n\ndef _signature(raw):\n """(bytes, note) of an aid-pka Signature member, a Structured Field byte sequence."""\n if len(raw) < 2 or not raw.startswith(":") or not raw.endswith(":"):\n raise _Bad("Signature aid-pka is not a byte sequence (:base64:)")\n body = raw[1:-1].strip()\n stripped = body.rstrip("=")\n padding = len(body) - len(stripped)\n try:\n value = _unbase64(stripped, _STD)\n except ValueError as exc:\n raise _Bad("Signature aid-pka is not standard base64: " + str(exc)) from None\n note = None\n if padding != (-len(stripped)) % 4:\n note = ("the Signature value has wrong or missing base64 padding; RFC 8941 lets a parser "\n "accept it, the AID reference client refuses it")\n return value, note\n\n\n# ------------------------------------------------------------------ the request context\n\n\ndef target(uri):\n """(@target-uri, @authority) for a request URI, per Appendix B.5: no fragment, lower-case\n host, default port dropped, path and query kept as sent."""\n text = uri.strip()\n cut = text.find("#")\n if cut >= 0:\n text = text[:cut]\n scheme, sep, rest = text.partition("://")\n if not sep or scheme.lower() != "https":\n raise ValueError("request.uri must be an https:// URL (the proof is an HTTPS exchange)")\n end = len(rest)\n for mark in "/?":\n at = rest.find(mark)\n if 0 <= at < end:\n end = at\n netloc, tail = rest[:end], rest[end:]\n if "@" in netloc or " " in rest:\n raise ValueError("request.uri must not carry credentials or spaces")\n host, port = netloc, ""\n if netloc.startswith("["):\n close = netloc.find("]")\n if close < 0 or (netloc[close + 1:] and not netloc[close + 1:].startswith(":")):\n raise ValueError("request.uri has a malformed IPv6 host")\n host, port = netloc[:close + 1], netloc[close + 2:]\n elif ":" in netloc:\n host, _, port = netloc.rpartition(":")\n if not host:\n raise ValueError("request.uri has no host")\n if port and not (port.isdigit() and port.isascii() and int(port) <= 65535):\n raise ValueError("request.uri has a malformed port")\n authority = host.lower() + (":" + str(int(port)) if port and int(port) != 443 else "")\n return "https://" + authority + tail, authority\n\n\ndef aid_domain(value):\n """The AID-Domain value as both sides must use it: lower-case, no trailing dot."""\n text = value.strip().lower()\n if text.endswith("."):\n text = text[:-1]\n if not text or any(char not in "abcdefghijklmnopqrstuvwxyz0123456789.:[]_-" for char in text):\n raise ValueError("request.aid_domain is not a host name")\n return text\n\n\n# ------------------------------------------------------------------ the handler\n\n\ndef _key_from(payload):\n k = payload.get("k")\n if k is None and isinstance(payload.get("record"), str):\n for pair in payload["record"].split(";"):\n name, eq, value = pair.partition("=")\n if eq and name.strip().lower() in ("k", "pka"):\n k = value.strip()\n if not isinstance(k, str) or not k:\n raise ValueError("give k (the key from the _agent record) or record (the TXT string "\n "with k)")\n return k\n\n\ndef _uint(value, where, upper):\n if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= upper:\n raise ValueError(where + " must be an integer from 0 to " + str(upper))\n return value\n\n\ndef handle(payload):\n if not isinstance(payload, dict):\n raise ValueError("send an object: k, request, response, now")\n k = _key_from(payload)\n request, response = payload.get("request"), payload.get("response")\n if not isinstance(request, dict) or not isinstance(response, dict):\n raise ValueError("request and response must be objects")\n uri, nonce = request.get("uri"), request.get("nonce")\n if not isinstance(uri, str) or not isinstance(nonce, str) or not nonce:\n raise ValueError("request.uri and request.nonce (the challenge you sent) are required")\n method = str(request.get("method") or "GET").upper()\n if not method.isalpha() or not method.isascii():\n raise ValueError("request.method must be an HTTP method name")\n target_uri, authority = target(uri)\n sent_domain = request.get("aid_domain")\n if sent_domain is not None:\n if not isinstance(sent_domain, str):\n raise ValueError("request.aid_domain must be a string")\n sent_domain = aid_domain(sent_domain)\n status = _uint(response.get("status"), "response.status", 599)\n headers = response.get("headers")\n if not isinstance(headers, dict):\n raise ValueError("response.headers must be an object")\n now = _uint(payload.get("now"), "now (unix seconds when the response arrived)", 2 ** 40)\n skew = _uint(payload.get("skew", DEFAULT_SKEW), "skew", MAX_WINDOW)\n require_bound = payload.get("require_domain_binding") is True\n\n checks, warnings = [], []\n out = {"verified": False, "domain_bound": False, "spec": SPEC}\n\n def check(name, ok, detail):\n checks.append({"check": name, "ok": bool(ok), "detail": detail})\n return bool(ok)\n\n def done():\n failed = [item["check"] for item in checks if not item["ok"]]\n out["verified"] = not failed\n out["domain_bound"] = bool(out["verified"] and out.get("covers_aid_domain"))\n out["code"] = 0 if out["verified"] else 1003\n if failed:\n out["error"] = "ERR_SECURITY"\n out["failed"] = failed\n out["checks"] = checks\n if warnings:\n out["warnings"] = warnings\n out.pop("covers_aid_domain", None)\n return out\n\n # B.1, B.2: the key and the keyid it implies.\n public = None\n try:\n if "=" in k:\n raise ValueError("it is padded")\n public = _unbase64(k, _URL)\n if len(public) != 32:\n raise ValueError("it decodes to " + str(len(public)) + " bytes, not 32")\n except ValueError as exc:\n check("key", False, "k must be unpadded base64url of a 32-byte Ed25519 key: " + str(exc))\n return done()\n expected_keyid = keyid(k)\n out["keyid"] = expected_keyid\n check("key", True, "k is a 32-byte key; its RFC 7638 thumbprint is the expected keyid")\n\n check("no_redirect", not 300 <= status < 400,\n "status " + str(status) + (": a redirect is never a proof (B.5)" if 300 <= status < 400\n else " (any status may be signed; PKA does not need 200)"))\n\n cache = _header(headers, "cache-control") or ""\n no_store = any(part.strip().split(";", 1)[0].strip().lower() == "no-store"\n for part in cache.split(","))\n check("cache_control", no_store,\n "Cache-Control has no-store" if no_store\n else "the response must carry Cache-Control: no-store, got " + (cache or "nothing"))\n\n # B.3: the two signature headers.\n sig_input, sig = _header(headers, "signature-input"), _header(headers, "signature")\n if not sig_input or not sig:\n refusal = ""\n if status == 403 and sent_domain:\n refusal = (" A 403 without a signature is how an endpoint refuses a domain it does "\n "not serve (B.7).")\n check("signature_headers", False,\n "the response has no Signature-Input and Signature: no proof was given." + refusal)\n return done()\n try:\n raw_params = _member(sig_input, "aid-pka", "Signature-Input")\n covered, params = _signature_input(raw_params)\n signature, note = _signature(_member(sig, "aid-pka", "Signature"))\n except _Bad as exc:\n check("signature_headers", False, str(exc))\n return done()\n if note:\n warnings.append(note)\n check("signature_headers", True, "Signature-Input and Signature carry an aid-pka member")\n created, expires = int(params["created"]), int(params["expires"])\n out["covered"] = covered\n out["created"], out["expires"] = created, expires\n\n # B.4, B.6, B.7: exactly the base set, or the base set with aid-domain before @status.\n bound = covered == BOUND\n out["covers_aid_domain"] = bound\n shape_ok = bound or covered == BASE\n if bound:\n shape = \'the base set plus "aid-domain";req: a domain-bound proof\'\n elif shape_ok:\n shape = "the four base components: an unbound proof"\n else:\n shape = ("the covered set must be " + " ".join(BASE) + \', or the same with \'\n \'"aid-domain";req before "@status"; got \' + " ".join(covered))\n check("covered_components", shape_ok, shape)\n check("tag", params["tag"] == TAG, "tag is " + params["tag"] + ", the profile\'s is " + TAG)\n check("alg", params["alg"].lower() == "ed25519", "alg is " + params["alg"])\n if params["alg"] != "ed25519" and params["alg"].lower() == "ed25519":\n warnings.append("alg is not lower-case; signers MUST emit ed25519 (verifiers accept "\n "any case)")\n check("keyid", params["keyid"] == expected_keyid,\n "keyid is the thumbprint of k" if params["keyid"] == expected_keyid\n else "keyid " + params["keyid"] + " is not the thumbprint of k (" + expected_keyid\n + "): another key signed, or the keyid hashes the raw key bytes")\n check("nonce", params["nonce"] == nonce,\n "the nonce is the challenge you sent" if params["nonce"] == nonce\n else "the nonce is not the challenge you sent: a replayed or unrelated response")\n if len(nonce) < 43:\n warnings.append("your challenge is shorter than 32 bytes in base64url; the spec asks for "\n "at least 32 bytes of entropy")\n window_ok = expires > created and expires - created <= MAX_WINDOW\n check("window", window_ok,\n "created " + str(created) + ", expires " + str(expires) + ": "\n + (str(expires - created) + " s, within the 300 s limit" if window_ok\n else "expires must be later than created by at most 300 s"))\n fresh = created - now <= skew and now - expires <= skew\n if fresh:\n when = "now " + str(now) + " is inside the window (skew " + str(skew) + " s)"\n else:\n side = "before created" if created - now > skew else "after expires"\n when = "now " + str(now) + " is " + side + " by more than " + str(skew) + " s"\n check("freshness", fresh, when)\n\n # B.7: a proof that covers aid-domain only means something for the domain the client named.\n domain_line = None\n if bound:\n if sent_domain is None:\n check("domain_binding", False,\n "the response covers aid-domain but you sent no AID-Domain: refused "\n "(fail closed)")\n else:\n domain_line = \'"aid-domain";req: \' + sent_domain\n check("domain_binding", True, "bound to " + sent_domain + " if the signature verifies")\n elif require_bound:\n check("domain_binding", False,\n "you require domain binding and the proof is unbound: an endpoint that ignores "\n "AID-Domain proves control of the key, not that it serves this domain")\n elif sent_domain is not None:\n warnings.append("you sent AID-Domain and the endpoint answered with an unbound proof: it "\n "controls the key, but did not state that it serves " + sent_domain)\n\n if covered == BASE or (bound and domain_line):\n lines = [\'"@method";req: \' + method, \'"@target-uri";req: \' + target_uri,\n \'"@authority";req: \' + authority]\n if domain_line:\n lines.append(domain_line)\n lines += [\'"@status": \' + str(status), \'"@signature-params": \' + raw_params]\n base = "\\n".join(lines)\n out["signature_base"] = base\n ok, reason = ed25519_verify(public, base.encode("utf-8"), signature)\n check("signature", ok, reason)\n else:\n check("signature", False, "not checked: the covered set does not allow a signature base")\n return done()\n' # ------------------------------------------------------------------ the two checks, as embedded import base64 as _base64 import time as _time _RECORD = {"__name__": "aid_record", "fetch": fetch} # noqa: F821 — the sandbox provides fetch() exec(compile(RECORD_SOURCE, "aid-record/handler.py", "exec"), _RECORD) _PROOF = {"__name__": "aid_proof"} exec(compile(PROOF_SOURCE, "aid-proof/handler.py", "exec"), _PROOF) SPEC = "AID v2.1.1: sections 2.1-2.3 (record) and Appendix B (endpoint proof, B.7 domain binding)" def _host_of(uri): rest = uri.split("://", 1)[1] if "://" in uri else "" return rest.split("/", 1)[0].split("?", 1)[0].split("#", 1)[0].rsplit("@", 1)[-1].split(":", 1)[0].lower() def _named(payload, name): value = payload.get(name) if not isinstance(value, str) or not value.strip(): return None text = value.strip() return (_host_of(text) if "://" in text else text.lower().rstrip(".")) def handle(payload): if not isinstance(payload, dict) or not isinstance(payload.get("domain"), str): raise ValueError("send domain: the host whose agent you want to find, e.g. example.com") domain = _RECORD["host"](payload["domain"]) if payload["domain"].strip().lower().rstrip(".") != domain: # The hearth lets this call reach the host the domain field names, exactly that one. raise ValueError("send domain as the bare host, e.g. " + domain) seed = globals().get("CALL_NONCE") or "" if len(seed) != 64: raise ValueError("this hearth gives handlers no call nonce, so no fresh proof can be asked for") found = _RECORD["handle"]({"domain": domain}) out = {"domain": domain, "spec": SPEC, "record": found} if not found.get("valid"): # 1004: neither resolver answered (or the hearth's egress budget refused them). That says # nothing about the record, so it is not reported as a missing one. verdict = "lookup_failed" if found.get("code") == 1004 else "no_valid_record" out.update(verdict=verdict, code=found.get("code"), error=found.get("error")) return out record = found["record"] uri, proto = record["uri"], record["proto"] out["endpoint"] = {"uri": uri, "proto": proto, "auth": record.get("auth")} if record["v"] != "aid2" or "pka" not in record: out.update(verdict="found_unproven", detail="the record has no aid2 key (k): the endpoint cannot prove it belongs to " "this domain; trust it as far as you trust DNS for " + domain) return out if not uri.startswith("https://"): out.update(verdict="found_unproven", detail="the endpoint is not https (" + proto + "): the proof of Appendix B is an " "HTTPS exchange") return out target = _host_of(uri) if target not in (domain, _named(payload, "endpoint")): out.update(verdict="endpoint_host_not_named", endpoint_host=target, detail="the endpoint is on " + target + ", another host than " + domain + ". This " "agent reaches only hosts the caller names: call again with endpoint=" + target) return out k = record["pka"] nonce = _base64.urlsafe_b64encode(bytes.fromhex(seed)).decode().rstrip("=") kid = _PROOF["keyid"](k) covered = '"@method";req "@target-uri";req "@authority";req "aid-domain";req "@status"' ask = ("aid-pka=(" + covered + ');created;expires;keyid="' + kid + '";alg="ed25519";nonce="' + nonce + '";tag="aid-pka-v2"') reply = fetch(uri, headers={"Accept-Signature": ask, "AID-Domain": domain, # noqa: F821 "Cache-Control": "no-store"}) exchange = {"k": k, "request": {"uri": uri, "nonce": nonce, "method": "GET", "aid_domain": domain}, "response": {"status": reply.status, "headers": dict(reply.headers)}, "now": int(_time.time()), "require_domain_binding": payload.get("require_domain_binding") is True} proof = _PROOF["handle"](exchange) if reply.error: proof["fetch_error"] = str(reply.error)[:200] out["proof"] = proof out["exchange"] = {"status": reply.status, "nonce": nonce, "aid_domain": domain, "observed_at": _time.strftime("%Y-%m-%dT%H:%M:%SZ", _time.gmtime(exchange["now"]))} if proof["verified"]: out["verdict"] = "proven_bound" if proof["domain_bound"] else "proven_unbound" else: out["verdict"] = "proof_failed" out["code"] = 1003 out["error"] = "ERR_SECURITY" return out