interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

branch main Branches Tags History

aienos.com / scripts / allen / test_a2a.py

441 lines · 18983 bytes Raw Blame History
1#!/usr/bin/env python3
2"""A2A SendMessage against the introduce door. No sandbox, no model, no network listen.
3
4Drives Handler.do_POST on a throwaway drop directory. A consented send stores one
5introduce record. Missing or false consent, malformed JSON-RPC, and an unsupported
6method store nothing. The JSON-RPC envelope is not written even when the
7introduction is.
8"""
9
10import io
11import json
12import os
13import re
14import sys
15import tempfile
16import threading
17from email.message import Message
18
19HERE = os.path.dirname(os.path.abspath(__file__))
20sys.path.insert(0, HERE)
21sys.path.insert(0, os.path.join(HERE, "contacts"))
22
23import a2a # noqa: E402
24import allen_chat # noqa: E402
25import allen_contacts_ingest # noqa: E402
26
27ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
28SENTINEL = "SENTINEL-a2a-message-not-stored-9f3c2a"
29results = []
30
31
32def check(name, ok, detail):
33 results.append((name, ok))
34 print("%s %s: %s" % ("PASS" if ok else "FAIL", name, detail), flush=True)
35
36
37def intro(**over):
38 body = {
39 "consent": True, "kind": "agent", "name": "Test Agent", "org": "",
40 "contact": "test@example.org", "github": "", "origin": "",
41 "purpose": "testing the door", "homepage": "", "framework": "",
42 "model": "", "human": "Drake (test)",
43 }
44 body.update(over)
45 return body
46
47
48class App:
49 """The pieces accept_introduction actually uses. Not a full gateway."""
50
51 def __init__(self, drop):
52 self.args = type("A", (), {"contacts_drop": drop, "submit_per_day": 40})()
53 self.stats = allen_chat.Stats()
54 self.intro_rate = allen_chat.Buckets(3, 1200)
55 self.salt = b"a2a-test-salt!!"
56 self.trusted = {"127.0.0.1"}
57 self.visitor_secret = None
58 self.day = (None, 0)
59 self.day_lock = threading.Lock()
60
61 def drop(self, rec, d=None, name=None):
62 allen_chat.App.drop(self, rec, d, name)
63
64 def submit_day(self):
65 return allen_chat.App.submit_day(self)
66
67 def client_key(self, handler):
68 return allen_chat.App.client_key(self, handler)
69
70
71def files(drop):
72 return sorted(f for f in os.listdir(drop) if not f.startswith("."))
73
74
75def tree_text(drop):
76 out = []
77 for name in files(drop):
78 with open(os.path.join(drop, name), "rb") as f:
79 out.append(f.read())
80 return b"\n".join(out)
81
82
83class Call:
84 def __init__(self, app, raw, path, extra=None):
85 self.app = app
86 self.headers = Message()
87 self.headers["Content-Type"] = "application/json"
88 self.headers["Content-Length"] = str(len(raw))
89 self.headers["X-Real-IP"] = "203.0.113.50"
90 for k, v in (extra or {}).items():
91 self.headers[k] = v
92 self.rfile = io.BytesIO(raw)
93 self.wfile = io.BytesIO()
94 self.client_address = ("127.0.0.1", 9)
95 self.close_connection = False
96 self.command = "POST"
97 self.path = path
98 self.requestline = "POST %s HTTP/1.1" % path
99 self.request_version = "HTTP/1.1"
100 self.body_read = False
101
102
103def post(app, path, obj=None, raw=None, headers=None, version="1.0", content_type="application/json"):
104 if raw is None:
105 raw = json.dumps(obj).encode()
106 call = allen_chat.Handler.__new__(allen_chat.Handler)
107 src = Call(app, raw, path, headers)
108 if "Content-Type" in src.headers:
109 src.headers.replace_header("Content-Type", content_type)
110 else:
111 src.headers["Content-Type"] = content_type
112 route = path.split("?", 1)[0]
113 if version is not False and route == "/allen/api/a2a" and "A2A-Version" not in src.headers:
114 src.headers["A2A-Version"] = version
115 call.__dict__.update(src.__dict__)
116 call.server = type("S", (), {"app": app})()
117 call.do_POST()
118 data = call.wfile.getvalue()
119 head, _, body = data.partition(b"\r\n\r\n")
120 line = head.split(b"\r\n", 1)[0]
121 status = int(line.split()[1])
122 hdrs = {}
123 for row in head.split(b"\r\n")[1:]:
124 if b":" in row:
125 k, v = row.split(b":", 1)
126 hdrs[k.decode().lower()] = v.decode().strip()
127 payload = json.loads(body.decode()) if body else None
128 return status, hdrs, payload
129
130
131def rpc(method, message, rid="t1", params_extra=None):
132 params = {"message": message}
133 if params_extra:
134 params.update(params_extra)
135 return {"jsonrpc": "2.0", "id": rid, "method": method, "params": params}
136
137
138def message(fields, text=None, message_id="msg-1", context_id=None, part_meta=None):
139 parts = []
140 if text is not None:
141 part = {"text": text, "mediaType": "text/plain"}
142 if part_meta is not None:
143 part["metadata"] = part_meta
144 parts.append(part)
145 parts.append({"data": fields, "mediaType": "application/json"})
146 msg = {"role": "ROLE_USER", "messageId": message_id, "parts": parts}
147 if context_id is not None:
148 msg["contextId"] = context_id
149 return msg
150
151
152def no_store(hdrs):
153 return hdrs.get("cache-control") == "no-store"
154
155
156def test_valid_send():
157 drop = tempfile.mkdtemp(prefix="a2a-valid-")
158 app = App(drop)
159 try:
160 st, hdrs, body = post(app, "/allen/api/introduce", intro())
161 drops = files(drop)
162 rec = json.load(open(os.path.join(drop, drops[0]))) if drops else {}
163 check("introduce door still stores one consented record",
164 st == 200 and body.get("stored") is True and len(drops) == 1
165 and rec.get("name") == "Test Agent" and "consent" not in rec
166 and no_store(hdrs),
167 "status %s drops %d" % (st, len(drops)))
168 os.remove(os.path.join(drop, drops[0]))
169 st, hdrs, body = post(app, "/allen/api/a2a", rpc("SendMessage", message(intro())))
170 drops = files(drop)
171 raw = open(os.path.join(drop, drops[0]), "rb").read() if drops else b""
172 rec = json.loads(raw) if raw else {}
173 parsed = allen_contacts_ingest.parse_drop(raw) if raw else None
174 result = (body or {}).get("result", {}).get("message", {})
175 data = next((p.get("data") for p in result.get("parts", []) if "data" in p), {})
176 check("SendMessage with consent stores one introduce record",
177 st == 200 and no_store(hdrs) and body.get("jsonrpc") == "2.0"
178 and result.get("role") == "ROLE_AGENT"
179 and data.get("stored") is True and data.get("id") == rec.get("id")
180 and len(drops) == 1 and parsed is not None
181 and rec.get("purpose") == "testing the door" and "consent" not in rec
182 and "jsonrpc" not in raw.decode() and "SendMessage" not in raw.decode(),
183 "status %s drops %d role %s" % (st, len(drops), result.get("role")))
184 st, hdrs, body = post(app, "/allen/api/a2a",
185 rpc("message/send", message(intro(name="Legacy Agent"), message_id="msg-2"), rid=2))
186 drops = files(drop)
187 check("legacy message/send is the same call",
188 st == 200 and no_store(hdrs) and len(drops) == 2
189 and body.get("result", {}).get("message", {}).get("role") == "ROLE_AGENT",
190 "status %s drops %d" % (st, len(drops)))
191 finally:
192 for name in files(drop):
193 os.remove(os.path.join(drop, name))
194 os.rmdir(drop)
195
196
197def test_consent():
198 drop = tempfile.mkdtemp(prefix="a2a-consent-")
199 app = App(drop)
200 try:
201 missing = intro()
202 missing.pop("consent")
203 cases = (
204 ("missing consent", missing),
205 ("consent false", intro(consent=False)),
206 ("consent as string", intro(consent="true")),
207 ("consent number 1", intro(consent=1)),
208 ("consent yes", intro(consent="yes")),
209 )
210 for name, fields in cases:
211 st, hdrs, body = post(app, "/allen/api/a2a", rpc("SendMessage", message(fields)))
212 err = (body or {}).get("error", {})
213 text = json.dumps(err)
214 check("refuses %s and stores nothing" % name,
215 st == 200 and no_store(hdrs) and err.get("code") == -32602
216 and "Nothing was stored" in text and not files(drop),
217 "status %s code %s drops %d" % (st, err.get("code"), len(files(drop))))
218 st, hdrs, body = post(app, "/allen/api/a2a", rpc("SendMessage", message(intro())),
219 headers={"X-Allen-Anonymous": "1"})
220 err = (body or {}).get("error", {})
221 check("anonymous mode stores nothing",
222 st == 200 and no_store(hdrs) and err.get("code") == -32602
223 and "nothing was stored" in json.dumps(err).lower() and not files(drop),
224 "status %s code %s" % (st, err.get("code")))
225 finally:
226 os.rmdir(drop)
227
228
229def test_malformed():
230 drop = tempfile.mkdtemp(prefix="a2a-bad-")
231 app = App(drop)
232 try:
233 cases = (
234 ("not json", b"{", -32700),
235 ("empty body", b"", -32700),
236 ("json array", b"[1,2]", -32600),
237 ("missing id", b'{"jsonrpc":"2.0","method":"SendMessage"}', -32600),
238 ("wrong version", b'{"jsonrpc":"1.0","id":1,"method":"SendMessage"}', -32600),
239 )
240 for name, raw, code in cases:
241 st, hdrs, body = post(app, "/allen/api/a2a", raw=raw)
242 err = (body or {}).get("error", {})
243 check("malformed %s" % name,
244 st == 200 and no_store(hdrs) and err.get("code") == code and not files(drop),
245 "status %s code %s body %s" % (st, err.get("code"), body))
246 finally:
247 os.rmdir(drop)
248
249
250def test_unsupported():
251 drop = tempfile.mkdtemp(prefix="a2a-method-")
252 app = App(drop)
253 try:
254 for method, code in (("GetTask", -32004), ("SendStreamingMessage", -32004),
255 ("CreateTaskPushNotificationConfig", -32003),
256 ("GetExtendedAgentCard", -32004), ("nope", -32601)):
257 st, hdrs, body = post(app, "/allen/api/a2a",
258 {"jsonrpc": "2.0", "id": 7, "method": method, "params": {}})
259 err = (body or {}).get("error", {})
260 check("unsupported %s" % method,
261 st == 200 and no_store(hdrs) and err.get("code") == code
262 and body.get("id") == 7 and not files(drop),
263 "status %s code %s" % (st, err.get("code")))
264 finally:
265 os.rmdir(drop)
266
267
268def test_nothing_stored():
269 """The envelope, message id, and unused text are not on disk. Failures write no file."""
270 drop = tempfile.mkdtemp(prefix="a2a-store-")
271 app = App(drop)
272 before = set(os.listdir(drop))
273 try:
274 post(app, "/allen/api/a2a", raw=b"not-json")
275 post(app, "/allen/api/a2a", {"jsonrpc": "2.0", "id": 1, "method": "GetTask", "params": {}})
276 bare = intro()
277 bare.pop("consent")
278 post(app, "/allen/api/a2a", rpc("SendMessage", message(bare)))
279 post(app, "/allen/api/a2a", rpc("SendMessage", message(intro(consent=False))))
280 check("refusals create no file", files(drop) == [] and set(os.listdir(drop)) == before,
281 "entries %s" % os.listdir(drop))
282 fields = intro(purpose="testing the door")
283 msg = message(fields, text=SENTINEL, message_id=SENTINEL, context_id=SENTINEL,
284 part_meta={"note": SENTINEL})
285 st, hdrs, body = post(app, "/allen/api/a2a", rpc("SendMessage", msg, rid="keep"))
286 blob = tree_text(drop)
287 check("consented send does not store the message envelope",
288 st == 200 and no_store(hdrs) and len(files(drop)) == 1
289 and SENTINEL.encode() not in blob
290 and b"jsonrpc" not in blob and b"SendMessage" not in blob
291 and b"testing the door" in blob and b'"consent"' not in blob,
292 "status %s files %s" % (st, files(drop)))
293 # The reply may echo the context id. That echo is the HTTP body, not a file.
294 echoed = (body or {}).get("result", {}).get("message", {}).get("contextId")
295 check("context id is returned and not stored",
296 echoed == SENTINEL and SENTINEL.encode() not in blob, "context %s" % echoed)
297 finally:
298 for name in files(drop):
299 os.remove(os.path.join(drop, name))
300 os.rmdir(drop)
301
302
303def test_version():
304 drop = tempfile.mkdtemp(prefix="a2a-version-")
305 app = App(drop)
306 try:
307 for name, kwargs in (
308 ("missing header", {"version": False}),
309 ("empty header", {"version": ""}),
310 ("header 0.3", {"version": "0.3"}),
311 ("blank header", {"version": " "}),
312 ):
313 st, hdrs, body = post(app, "/allen/api/a2a", rpc("SendMessage", message(intro())), **kwargs)
314 err = (body or {}).get("error", {})
315 check("A2A-Version %s is 0.3 and stores nothing" % name,
316 st == 200 and no_store(hdrs) and err.get("code") == -32009 and not files(drop),
317 "status %s code %s body %s" % (st, err.get("code"), body))
318 st, hdrs, body = post(app, "/allen/api/a2a?A2A-Version=1.0",
319 rpc("SendMessage", message(intro(name="Query Version"))), version=False)
320 check("query A2A-Version 1.0 is accepted when the header is absent",
321 st == 200 and no_store(hdrs) and (body or {}).get("result", {}).get("message", {}).get("role") == "ROLE_AGENT"
322 and len(files(drop)) == 1,
323 "status %s code %s" % (st, (body or {}).get("error")))
324 finally:
325 for name in files(drop):
326 os.remove(os.path.join(drop, name))
327 os.rmdir(drop)
328
329
330def nginx_patterns(conf, variable):
331 """Regexes that the named map assigns 0, after nginx double-quote escapes."""
332 chunk = conf.split("map $content_type $%s {" % variable, 1)[1].split("}", 1)[0]
333 patterns = []
334 for quoted in re.findall(r'"~\*(.*?)"\s+0;', chunk):
335 out = []
336 i = 0
337 while i < len(quoted):
338 if quoted[i] == "\\" and i + 1 < len(quoted):
339 nxt = quoted[i + 1]
340 out.append({"\\": "\\", "t": "\t", "n": "\n", "r": "\r"}.get(nxt, "\\" + nxt))
341 i += 2
342 else:
343 out.append(quoted[i])
344 i += 1
345 patterns.append("".join(out))
346 return patterns
347
348
349def ctype_allowed(patterns, ctype):
350 return any(re.search(pat, ctype, re.IGNORECASE) for pat in patterns)
351
352
353def test_a2a_content_type():
354 drop = tempfile.mkdtemp(prefix="a2a-ctype-")
355 app = App(drop)
356 zones = open(os.path.join(HERE, "nginx-allen-zones.conf"), encoding="utf-8").read()
357 loc = open(os.path.join(HERE, "nginx-allen-location.conf"), encoding="utf-8").read()
358 block = loc.split("location = /allen/api/a2a {", 1)[1].split("\n }", 1)[0]
359 a2a_pats = nginx_patterns(zones, "allen_a2a_notjson")
360 json_pats = nginx_patterns(zones, "allen_notjson")
361 try:
362 check("a2a location does not use $allen_notjson",
363 "$allen_notjson" not in block and "if ($allen_a2a_notjson)" in block,
364 block.strip().splitlines()[0] if block.strip() else "missing")
365 check("application/a2a+json is allowed only on the a2a map",
366 ctype_allowed(a2a_pats, "application/a2a+json")
367 and ctype_allowed(a2a_pats, "application/a2a+json; charset=utf-8")
368 and ctype_allowed(a2a_pats, "application/json")
369 and not ctype_allowed(a2a_pats, "text/plain")
370 and not ctype_allowed(json_pats, "application/a2a+json")
371 and ctype_allowed(json_pats, "application/json"),
372 "a2a %s json %s" % (a2a_pats, json_pats))
373 st, hdrs, body = post(app, "/allen/api/a2a", rpc("SendMessage", message(intro(name="A2A Type"))),
374 content_type="application/a2a+json")
375 err = (body or {}).get("error")
376 check("application/a2a+json is not a 415 and stores the introduction",
377 st == 200 and st != 415 and no_store(hdrs) and err is None and len(files(drop)) == 1,
378 "status %s err %s drops %d" % (st, err, len(files(drop))))
379 st, hdrs, body = post(app, "/allen/api/a2a", rpc("GetTask", message(intro())),
380 content_type="application/a2a+json; charset=utf-8")
381 check("application/a2a+json with a charset reaches the method",
382 st == 200 and (body or {}).get("error", {}).get("code") == -32004 and len(files(drop)) == 1,
383 "status %s body %s" % (st, body))
384 st, _, body = post(app, "/allen/api/a2a", rpc("SendMessage", message(intro())),
385 content_type="text/plain")
386 check("text/plain is still 415 and stores nothing more",
387 st == 415 and len(files(drop)) == 1, "status %s drops %d body %s" % (st, len(files(drop)), body))
388 finally:
389 for name in files(drop):
390 os.remove(os.path.join(drop, name))
391 os.rmdir(drop)
392
393
394def test_docs_and_card():
395 doc = a2a.__doc__
396 required = (
397 "SendMessage", "message/send", "SendStreamingMessage", "GetTask", "ListTasks",
398 "CancelTask", "SubscribeToTask", "CreateTaskPushNotificationConfig",
399 "GetTaskPushNotificationConfig", "ListTaskPushNotificationConfigs",
400 "DeleteTaskPushNotificationConfig", "GetExtendedAgentCard",
401 )
402 missing = [name for name in required if name not in doc]
403 check("code docs name every unsupported method", not missing, "missing %s" % missing)
404 card_path = os.path.join(ROOT, "om", "a2a", "agent-card.template.json")
405 card = json.load(open(card_path, encoding="utf-8"))
406 iface = card["supportedInterfaces"][0]
407 modes = ["text/plain", "application/json"]
408 published = []
409 for dirpath, _, names in os.walk(os.path.join(ROOT, "public")):
410 for name in names:
411 if name in ("agent-card.json", "agent.json", "server.json", "did.json"):
412 published.append(os.path.join(dirpath, name))
413 check("agent card template is unpublished",
414 card["name"] == "Aien" and card["version"] == "0.1.0"
415 and iface["protocolBinding"] == "JSONRPC" and iface["protocolVersion"] == "1.0"
416 and iface["url"] == "https://www.aienos.com/aien/api/a2a"
417 and card["defaultInputModes"] == modes and card["defaultOutputModes"] == modes
418 and card["capabilities"]["streaming"] is False
419 and card["capabilities"]["pushNotifications"] is False
420 and [s["id"] for s in card["skills"]] == ["introduce"]
421 and not published
422 and not os.path.exists(os.path.join(ROOT, "public", ".well-known", "agent-card.json")),
423 "published %s" % published)
424
425
426def main():
427 test_valid_send()
428 test_consent()
429 test_malformed()
430 test_unsupported()
431 test_nothing_stored()
432 test_version()
433 test_a2a_content_type()
434 test_docs_and_card()
435 failed = [n for n, ok in results if not ok]
436 print("%d/%d passed" % (len(results) - len(failed), len(results)))
437 sys.exit(1 if failed else 0)
438
439
440if __name__ == "__main__":
441 main()