aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / om / agora / test / limits.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Independent HTTP oracle for native Omega services; not a production dependency.""" |
| 3 | import argparse |
| 4 | import contextlib |
| 5 | import datetime |
| 6 | import http.client |
| 7 | import json |
| 8 | import pathlib |
| 9 | import subprocess |
| 10 | import tempfile |
| 11 | import time |
| 12 | |
| 13 | parser = argparse.ArgumentParser() |
| 14 | parser.add_argument("core") |
| 15 | parser.add_argument("edge") |
| 16 | parser.add_argument("--only", choices=("capacity", "quota")) |
| 17 | parser.add_argument("--expiry", action="store_true", help="also wait through an actual 600-second expiry") |
| 18 | args = parser.parse_args() |
| 19 | |
| 20 | |
| 21 | @contextlib.contextmanager |
| 22 | def service(binary, *argv): |
| 23 | proc = subprocess.Popen([binary, *map(str, argv)], stdout=subprocess.PIPE, text=True) |
| 24 | try: |
| 25 | line = proc.stdout.readline().split() |
| 26 | assert len(line) == 2 and line[0] in ("listening", "PORT"), line |
| 27 | yield int(line[1]) |
| 28 | finally: |
| 29 | proc.terminate() |
| 30 | proc.wait(timeout=10) |
| 31 | |
| 32 | |
| 33 | def request(port, path, data=None, headers=(), conn=None): |
| 34 | own = conn is None |
| 35 | conn = conn or http.client.HTTPConnection("127.0.0.1", port, timeout=10) |
| 36 | try: |
| 37 | conn.putrequest("POST" if data is not None else "GET", path) |
| 38 | for key, value in headers: |
| 39 | conn.putheader(key, value) |
| 40 | if data is not None: |
| 41 | conn.putheader("Content-Length", str(len(data))) |
| 42 | conn.endheaders(data) |
| 43 | response = conn.getresponse() |
| 44 | return response.status, response.read() |
| 45 | finally: |
| 46 | if own: |
| 47 | conn.close() |
| 48 | |
| 49 | |
| 50 | def challenge(port): |
| 51 | code, body = request(port, "/agora/api/challenge") |
| 52 | assert code == 200, (code, body) |
| 53 | fields = body.split(b"challenge\t")[1].strip().split(b"\t") |
| 54 | assert fields[1] == b"0", fields |
| 55 | return fields[0], fields[2] |
| 56 | |
| 57 | |
| 58 | def hello(port, token): |
| 59 | return request(port, "/agora/api/hello", b"challenge\t" + token + b"\nnonce\t0\nname\tCapacity\nkind\thuman\n") |
| 60 | |
| 61 | |
| 62 | def capacity(root): |
| 63 | root.mkdir() |
| 64 | with service(args.core, "serve", "--state", root, "--port", 0, "--bits", 0) as port: |
| 65 | tokens = [challenge(port) for _ in range(1024)] |
| 66 | for _ in range(3): |
| 67 | actual = request(port, "/agora/api/challenge") |
| 68 | assert actual == (429, b"agora 1\nerr slow challenge capacity reached\n"), ("capacity refusal", actual) |
| 69 | assert datetime.datetime.now(datetime.timezone.utc) < datetime.datetime.fromisoformat(tokens[0][1].decode().replace("Z", "+00:00")) |
| 70 | assert hello(port, tokens[0][0])[0] == 200, "live oldest challenge was evicted" |
| 71 | assert hello(port, tokens[0][0])[0] == 403, "used challenge accepted twice" |
| 72 | replacement, _ = challenge(port) |
| 73 | assert replacement not in [token for token, _ in tokens] |
| 74 | assert hello(port, tokens[-1][0])[0] == 200, "live last challenge was evicted" |
| 75 | assert hello(port, replacement)[0] == 200 |
| 76 | print("limits: PASS full 1024-slot table refuses issuance; oldest/latest live tokens survive; used slots recycle; single use", flush=True) |
| 77 | if args.expiry: |
| 78 | # Seal both used slots with fresh, unconsumed tokens. A later successful issuance must |
| 79 | # reclaim expired unused capacity, not accidentally recycle an already-used slot. |
| 80 | challenge(port) |
| 81 | challenge(port) |
| 82 | assert request(port, "/agora/api/challenge") == (429, b"agora 1\nerr slow challenge capacity reached\n") |
| 83 | print("limits: waiting 601 seconds for actual expiry (no clock injection)", flush=True) |
| 84 | time.sleep(601) |
| 85 | assert hello(port, tokens[1][0]) == (403, b"agora 1\nerr work challenge unknown expired or used\n") |
| 86 | fresh, _ = challenge(port) |
| 87 | assert hello(port, fresh)[0] == 200 |
| 88 | print("limits: PASS actual expiry rejects retained token and reclaims expired full-table slots", flush=True) |
| 89 | |
| 90 | |
| 91 | def rpc(port, protocol, fields, headers, conn=None): |
| 92 | if protocol == "mcp": |
| 93 | value = {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "agora_hello", "arguments": fields}} |
| 94 | else: |
| 95 | value = {"jsonrpc": "2.0", "id": 1, "method": "message/send", "params": {"message": {"role": "user", "messageId": "quota", "parts": [], "metadata": {"skill": "agora_hello", **fields}}}} |
| 96 | code, body = request(port, "/agora/" + protocol, json.dumps(value).encode(), headers, conn) |
| 97 | assert code == 200, (code, body) |
| 98 | result = json.loads(body)["result"] |
| 99 | text = result["content" if protocol == "mcp" else "parts"][0]["text"] |
| 100 | return text |
| 101 | |
| 102 | |
| 103 | def edgehello(core, edge, protocol, headers=(), conn=None): |
| 104 | # A real bits=0 core isolates quota behavior; the full gate separately tests nonzero PoW. |
| 105 | token, _ = challenge(core) |
| 106 | return rpc(edge, protocol, {"kind": "human", "name": "Quota", "challenge": token.decode(), "nonce": 0}, headers, conn) |
| 107 | |
| 108 | |
| 109 | def quota(root): |
| 110 | (root / "node").mkdir() |
| 111 | with service(args.core, "serve", "--state", root / "node", "--port", 0, "--bits", 0) as core: |
| 112 | # Existing core ingress trusts the operator proxy. These are oracle-supplied proxy identities, |
| 113 | # not evidence that untrusted direct-core access is safe. |
| 114 | for ip in ("192.0.2.1", "2001:db8::2"): |
| 115 | for _ in range(20): |
| 116 | token, _ = challenge(core) |
| 117 | data = b"challenge\t" + token + b"\nnonce\t0\nname\tCoreQuota\nkind\thuman\n" |
| 118 | assert request(core, "/agora/api/hello", data, (("X-Real-IP", ip),))[0] == 200 |
| 119 | token, _ = challenge(core) |
| 120 | data = b"challenge\t" + token + b"\nnonce\t0\nname\tCoreQuota\nkind\thuman\n" |
| 121 | actual = request(core, "/agora/api/hello", data, (("X-Real-IP", ip),)) |
| 122 | assert actual == (429, b"agora 1\nerr slow ip rate limit reached\n"), ("IP quota refusal", actual) |
| 123 | print("limits: PASS core independent proxy-client IP quotas at 20/21 (existing restricted ingress contract)", flush=True) |
| 124 | with service(args.edge, "--api", core, "--port", 0) as edge: |
| 125 | for _ in range(20): |
| 126 | assert edgehello(core, edge, "mcp").startswith("agora 1\nok\n") |
| 127 | # The unresolved edge pooling must stay fail-closed: changing forwarding claims must not |
| 128 | # buy another quota. Exercise both protocols, duplicate headers and keep-alive requests. |
| 129 | claims = [(), (("X-Real-IP", "192.0.2.9"),), (("X-Forwarded-For", "192.0.2.9"),), (("X-Real-IP", "2001:db8::9"), ("X-Forwarded-For", "192.0.2.8")), (("X-Real-IP", "192.0.2.9"), ("x-real-ip", "192.0.2.8"))] |
| 130 | conn = http.client.HTTPConnection("127.0.0.1", edge, timeout=10) |
| 131 | try: |
| 132 | for headers in claims: |
| 133 | for protocol in ("mcp", "a2a"): |
| 134 | text = edgehello(core, edge, protocol, headers, conn) |
| 135 | assert "err slow ip rate limit reached" in text, text |
| 136 | finally: |
| 137 | conn.close() |
| 138 | print("limits: PASS MCP/A2A shared local quota retained; spoofed forwarded headers cannot bypass exhausted quota", flush=True) |
| 139 | print("limits: NOT_IMPLEMENTED independent edge client quotas (AG-2 accepted-peer interface prerequisite)", flush=True) |
| 140 | |
| 141 | |
| 142 | with tempfile.TemporaryDirectory(prefix="agora-limits-") as scratch: |
| 143 | root = pathlib.Path(scratch) |
| 144 | if args.only != "quota": |
| 145 | capacity(root / "capacity") |
| 146 | if args.only != "capacity": |
| 147 | quota(root) |
| 148 | print("limits: PASS", flush=True) |