diff --git a/.github/workflows/generated-allen.yml b/.github/workflows/generated-allen.yml index 520e6afd..d563965a 100644 --- a/.github/workflows/generated-allen.yml +++ b/.github/workflows/generated-allen.yml @@ -11,6 +11,11 @@ on: - 'public/assets/allen*.css' - 'public/allen/**' - 'crates/site-builder/**' + - 'scripts/allen/a2a.py' + - 'scripts/allen/test_a2a.py' + - 'scripts/allen/allen_chat.py' + - 'scripts/allen/nginx-allen-location.conf' + - 'scripts/allen/nginx-allen-zones.conf' - '.github/workflows/generated-allen.yml' push: branches: [main] @@ -24,6 +29,11 @@ on: - 'public/assets/allen*.css' - 'public/allen/**' - 'crates/site-builder/**' + - 'scripts/allen/a2a.py' + - 'scripts/allen/test_a2a.py' + - 'scripts/allen/allen_chat.py' + - 'scripts/allen/nginx-allen-location.conf' + - 'scripts/allen/nginx-allen-zones.conf' - '.github/workflows/generated-allen.yml' permissions: contents: read @@ -65,3 +75,13 @@ jobs: name: aienos-dist path: dist retention-days: 7 + # The introduce A2A door. Python standard library only, so this does not + # build the site. Path filters above also schedule the site job. + a2a: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - name: A2A SendMessage tests + run: python3 scripts/allen/test_a2a.py diff --git a/scripts/allen/README.md b/scripts/allen/README.md index f6fd3b56..3a7c2bde 100644 --- a/scripts/allen/README.md +++ b/scripts/allen/README.md @@ -425,7 +425,13 @@ These methods are not supported. Each one is a JSON-RPC error and stores nothing Older slash names of those same methods return the same codes. `scripts/allen/a2a.py` lists them. +A missing or empty `A2A-Version` is version 0.3. Spec section 3.6.2 says an empty value is 0.3, and section 3.6.1 assumes 0.3 for an empty header. This door implements 1.0 only, so that request returns `-32009` and stores nothing. Send `A2A-Version: 1.0`. When the header is absent, the query parameter `A2A-Version` is read instead. + +Rate-limit and daily-cap refusals stay JSON-RPC `-32603`. Spec section 3.3.2 lists "rate limit exceeded" as an example of that code. The A2A table from `-32001` to `-32009` has no rate-limit code. + The location is `location = /allen/api/a2a` in `nginx-allen-location.conf`. +`$allen_notjson` allows only `application/json`, so this location uses +`$allen_a2a_notjson`, which also allows `application/a2a+json`. On the hub, after that file is installed as `/etc/nginx/snippets/aienos-allen.conf`: sudo nginx -t @@ -438,12 +444,29 @@ Then check the response. This asks for `GetTask`, which is not supported, and it curl -sS -D - -o /tmp/a2a-check.json -X POST https://www.aienos.com/aien/api/a2a \ -H 'Content-Type: application/json' \ + -H 'A2A-Version: 1.0' \ --data '{"jsonrpc":"2.0","id":"deploy-check","method":"GetTask","params":{}}' Expect HTTP 200, a `Cache-Control: no-store` header, and a JSON body whose error code is `-32004`. Nothing is stored. Do not send a consented `SendMessage` as the deploy check. +The same call with `Content-Type: application/a2a+json` must not be 415. +`$allen_notjson` would refuse that media type. This location does not use it: + + curl -sS -D - -o /tmp/a2a-ctype.json -X POST https://www.aienos.com/aien/api/a2a \ + -H 'Content-Type: application/a2a+json' \ + -H 'A2A-Version: 1.0' \ + --data '{"jsonrpc":"2.0","id":"ctype-check","method":"GetTask","params":{}}' + +Expect HTTP 200, not 415, `Cache-Control: no-store`, and error code `-32004`. + +The same call with no `A2A-Version` header is version 0.3 and returns `-32009`: + + curl -sS -D - -o /tmp/a2a-version.json -X POST https://www.aienos.com/aien/api/a2a \ + -H 'Content-Type: application/json' \ + --data '{"jsonrpc":"2.0","id":"version-check","method":"GetTask","params":{}}' + Rollback: restore the previous snippet, run `nginx -t`, then reload. ## Build loop (homes, save, publish, gallery) diff --git a/scripts/allen/a2a.py b/scripts/allen/a2a.py index f8ac8841..c7bfcb0f 100644 --- a/scripts/allen/a2a.py +++ b/scripts/allen/a2a.py @@ -28,9 +28,13 @@ Any other method returns JSON-RPC -32601 Method not found. Nothing is stored. GetExtendedAgentCard, agent/getAuthenticatedExtendedCard: -32004 Unsupported operation. capabilities.extendedAgentCard is false. -A request with an A2A-Version header other than 1.0 returns -32009 and stores -nothing. A missing header is accepted as 1.0. Notifications (a request with no -id) are rejected with -32600. This door does not take a silent store. +A2A-Version: spec 3.6.2 says an empty value is version 0.3, and spec 3.6.1 +assumes 0.3 when the header is empty. A missing header is that empty case. +This door implements 1.0 only, so a missing or empty version is 0.3 and +returns -32009, and nothing is stored. Send A2A-Version: 1.0. When the header +is absent, the query parameter A2A-Version is read instead (spec 3.6.1). Any +other version returns -32009. Notifications (a request with no id) are +rejected with -32600. This door does not take a silent store. SendMessage params.message is the introduction. Fields come from message.metadata, then from each JSON data part (a later part overrides). A text part is the @@ -49,6 +53,7 @@ body. Cache-Control stays no-store. import json import secrets +from urllib.parse import parse_qs, urlsplit # The introduce door's field names. consent is checked by that door, not copied # into the stored record. @@ -133,15 +138,39 @@ def controls(text): return any((ord(c) < 32 and c not in "\n\t") or ord(c) == 127 for c in text) -def version_error(headers): - """None when the call may proceed. A missing header means 1.0.""" +def _header(headers, name): + """(value, present). Missing is not the same as an empty value.""" if headers is None: - return None - raw = headers.get("A2A-Version") - if raw is None: - return None - version = str(raw).strip() - if version == "" or version == "1.0": + return None, False + for key in headers.keys(): + if str(key).lower() == name.lower(): + return headers.get(key), True + return None, False + + +def version_token(headers, path=""): + """The version this door must apply. + + Spec 3.6.2: an empty value is 0.3. Spec 3.6.1: an empty header is assumed + to be 0.3, and a client may send A2A-Version as a query parameter instead + of the header. A missing header is that empty case, so it is 0.3 unless + the query parameter is present. This door speaks 1.0 only. + """ + raw, present = _header(headers, "A2A-Version") + if not present and path: + query = parse_qs(urlsplit(path).query, keep_blank_values=True) + if "A2A-Version" in query: + raw = query["A2A-Version"][0] if query["A2A-Version"] else "" + present = True + if not present or raw is None or str(raw).strip() == "": + return "0.3" + return str(raw).strip() + + +def version_error(headers, path=""): + """None when the call is version 1.0. Otherwise VersionNotSupportedError.""" + version = version_token(headers, path) + if version == "1.0": return None return (-32009, "Version is not supported", error_info("VERSION_NOT_SUPPORTED", {"version": version})) @@ -271,6 +300,8 @@ def map_intro(status, body): return -32602, "Invalid parameters", bad_request("message", msg) if err == "anonymous": return -32602, "Invalid parameters", bad_request("X-Allen-Anonymous", msg) + # Spec 3.3.2 names "rate limit exceeded" as an example of -32603. The + # -32001 to -32009 table has no rate-limit code, so this stays -32603. if err == "rate": return -32603, "Internal error", error_info("RATE_LIMITED", {"message": msg}) if err == "busy": @@ -293,7 +324,7 @@ def result_message(body, context_id): }} -def dispatch(raw, headers, accept): +def dispatch(raw, headers, accept, path=""): """One JSON-RPC call. accept(intro) is the introduce door. Returns (http_status, object, extra_headers). This function does not write @@ -303,7 +334,7 @@ def dispatch(raw, headers, accept): kind, parsed = parse(raw) if kind == "error": return 200, parsed, None - ver = version_error(headers) + ver = version_error(headers, path) if ver: return 200, error_obj(parsed["id"], ver[0], ver[1], ver[2]), None method = parsed["method"] diff --git a/scripts/allen/allen_chat.py b/scripts/allen/allen_chat.py index 0e4cdd30..138f845c 100755 --- a/scripts/allen/allen_chat.py +++ b/scripts/allen/allen_chat.py @@ -1375,7 +1375,8 @@ class Handler(BaseHTTPRequestHandler): that still carries Sec-Fetch-Site is a browser and refused; with neither it is a non-browser client (server-side callers, tests), which the Content-Type rule still binds. Content-Type must be application/json, except transcribe, which checks its audio type - itself; so a cross-site "simple" request (text/plain, form) never executes.""" + itself, and /a2a, which also accepts application/a2a+json. A cross-site "simple" + request (text/plain, form) never executes.""" origin = self.headers.get("Origin") if origin is not None: ok = origin in self.app.args.allow_origin @@ -1386,7 +1387,10 @@ class Handler(BaseHTTPRequestHandler): return False if r != "transcribe": ctype = self.headers.get("Content-Type", "").split(";")[0].strip().lower() - if ctype != "application/json": + allowed = {"application/json"} + if r == "a2a": + allowed.add("application/a2a+json") + if ctype not in allowed: self.refuse(415, "content_type", "Send the request as application/json.") return False return True @@ -2053,7 +2057,7 @@ class Handler(BaseHTTPRequestHandler): app.stats.add("refused_" + body["error"]) return code, body, retry - status, obj, extra = a2a.dispatch(raw, self.headers, accept) + status, obj, extra = a2a.dispatch(raw, self.headers, accept, self.path) self.send_json(status, obj, extra) def project_summary(self): diff --git a/scripts/allen/nginx-allen-location.conf b/scripts/allen/nginx-allen-location.conf index 3fd738f3..781be674 100644 --- a/scripts/allen/nginx-allen-location.conf +++ b/scripts/allen/nginx-allen-location.conf @@ -128,10 +128,12 @@ location ^~ /allen/api/ { # Consent and no-store match introduce: nothing is stored unless consent is # the JSON boolean true, and the response carries Cache-Control: no-store. # Agora's board is a different service at /agora/a2a. + # application/a2a+json is allowed here via $allen_a2a_notjson. $allen_notjson + # would answer 415 for that media type, so this location does not use it. location = /allen/api/a2a { if ($proxy_protocol_addr = "") { return 503; } if ($allen_xsite) { return 403; } - if ($allen_notjson) { return 415; } + if ($allen_a2a_notjson) { return 415; } limit_except POST { deny all; } limit_req zone=allen_submit burst=3 nodelay; limit_conn allen_conn 4; diff --git a/scripts/allen/nginx-allen-zones.conf b/scripts/allen/nginx-allen-zones.conf index 9f262c4b..2100c207 100644 --- a/scripts/allen/nginx-allen-zones.conf +++ b/scripts/allen/nginx-allen-zones.conf @@ -23,6 +23,13 @@ map $content_type $allen_notjson { default 1; "~*^application/json[ \t]*(;|$)" 0; } +# The A2A location also accepts application/a2a+json. $allen_notjson stays +# application/json only, so chat and introduce do not take that media type. +map $content_type $allen_a2a_notjson { + default 1; + "~*^application/json[ \t]*(;|$)" 0; + "~*^application/a2a\\+json[ \t]*(;|$)" 0; +} # The gateway listens only on the Spark's tailnet address. upstream allen_chat_gateway { diff --git a/scripts/allen/test_a2a.py b/scripts/allen/test_a2a.py index c9770416..eed79ff2 100644 --- a/scripts/allen/test_a2a.py +++ b/scripts/allen/test_a2a.py @@ -10,6 +10,7 @@ introduction is. import io import json import os +import re import sys import tempfile import threading @@ -99,11 +100,18 @@ class Call: self.body_read = False -def post(app, path, obj=None, raw=None, headers=None): +def post(app, path, obj=None, raw=None, headers=None, version="1.0", content_type="application/json"): if raw is None: raw = json.dumps(obj).encode() call = allen_chat.Handler.__new__(allen_chat.Handler) src = Call(app, raw, path, headers) + if "Content-Type" in src.headers: + src.headers.replace_header("Content-Type", content_type) + else: + src.headers["Content-Type"] = content_type + route = path.split("?", 1)[0] + if version is not False and route == "/allen/api/a2a" and "A2A-Version" not in src.headers: + src.headers["A2A-Version"] = version call.__dict__.update(src.__dict__) call.server = type("S", (), {"app": app})() call.do_POST() @@ -196,6 +204,8 @@ def test_consent(): ("missing consent", missing), ("consent false", intro(consent=False)), ("consent as string", intro(consent="true")), + ("consent number 1", intro(consent=1)), + ("consent yes", intro(consent="yes")), ) for name, fields in cases: st, hdrs, body = post(app, "/allen/api/a2a", rpc("SendMessage", message(fields))) @@ -290,6 +300,97 @@ def test_nothing_stored(): os.rmdir(drop) +def test_version(): + drop = tempfile.mkdtemp(prefix="a2a-version-") + app = App(drop) + try: + for name, kwargs in ( + ("missing header", {"version": False}), + ("empty header", {"version": ""}), + ("header 0.3", {"version": "0.3"}), + ("blank header", {"version": " "}), + ): + st, hdrs, body = post(app, "/allen/api/a2a", rpc("SendMessage", message(intro())), **kwargs) + err = (body or {}).get("error", {}) + check("A2A-Version %s is 0.3 and stores nothing" % name, + st == 200 and no_store(hdrs) and err.get("code") == -32009 and not files(drop), + "status %s code %s body %s" % (st, err.get("code"), body)) + st, hdrs, body = post(app, "/allen/api/a2a?A2A-Version=1.0", + rpc("SendMessage", message(intro(name="Query Version"))), version=False) + check("query A2A-Version 1.0 is accepted when the header is absent", + st == 200 and no_store(hdrs) and (body or {}).get("result", {}).get("message", {}).get("role") == "ROLE_AGENT" + and len(files(drop)) == 1, + "status %s code %s" % (st, (body or {}).get("error"))) + finally: + for name in files(drop): + os.remove(os.path.join(drop, name)) + os.rmdir(drop) + + +def nginx_patterns(conf, variable): + """Regexes that the named map assigns 0, after nginx double-quote escapes.""" + chunk = conf.split("map $content_type $%s {" % variable, 1)[1].split("}", 1)[0] + patterns = [] + for quoted in re.findall(r'"~\*(.*?)"\s+0;', chunk): + out = [] + i = 0 + while i < len(quoted): + if quoted[i] == "\\" and i + 1 < len(quoted): + nxt = quoted[i + 1] + out.append({"\\": "\\", "t": "\t", "n": "\n", "r": "\r"}.get(nxt, "\\" + nxt)) + i += 2 + else: + out.append(quoted[i]) + i += 1 + patterns.append("".join(out)) + return patterns + + +def ctype_allowed(patterns, ctype): + return any(re.search(pat, ctype, re.IGNORECASE) for pat in patterns) + + +def test_a2a_content_type(): + drop = tempfile.mkdtemp(prefix="a2a-ctype-") + app = App(drop) + zones = open(os.path.join(HERE, "nginx-allen-zones.conf"), encoding="utf-8").read() + loc = open(os.path.join(HERE, "nginx-allen-location.conf"), encoding="utf-8").read() + block = loc.split("location = /allen/api/a2a {", 1)[1].split("\n }", 1)[0] + a2a_pats = nginx_patterns(zones, "allen_a2a_notjson") + json_pats = nginx_patterns(zones, "allen_notjson") + try: + check("a2a location does not use $allen_notjson", + "$allen_notjson" not in block and "if ($allen_a2a_notjson)" in block, + block.strip().splitlines()[0] if block.strip() else "missing") + check("application/a2a+json is allowed only on the a2a map", + ctype_allowed(a2a_pats, "application/a2a+json") + and ctype_allowed(a2a_pats, "application/a2a+json; charset=utf-8") + and ctype_allowed(a2a_pats, "application/json") + and not ctype_allowed(a2a_pats, "text/plain") + and not ctype_allowed(json_pats, "application/a2a+json") + and ctype_allowed(json_pats, "application/json"), + "a2a %s json %s" % (a2a_pats, json_pats)) + st, hdrs, body = post(app, "/allen/api/a2a", rpc("SendMessage", message(intro(name="A2A Type"))), + content_type="application/a2a+json") + err = (body or {}).get("error") + check("application/a2a+json is not a 415 and stores the introduction", + st == 200 and st != 415 and no_store(hdrs) and err is None and len(files(drop)) == 1, + "status %s err %s drops %d" % (st, err, len(files(drop)))) + st, hdrs, body = post(app, "/allen/api/a2a", rpc("GetTask", message(intro())), + content_type="application/a2a+json; charset=utf-8") + check("application/a2a+json with a charset reaches the method", + st == 200 and (body or {}).get("error", {}).get("code") == -32004 and len(files(drop)) == 1, + "status %s body %s" % (st, body)) + st, _, body = post(app, "/allen/api/a2a", rpc("SendMessage", message(intro())), + content_type="text/plain") + check("text/plain is still 415 and stores nothing more", + st == 415 and len(files(drop)) == 1, "status %s drops %d body %s" % (st, len(files(drop)), body)) + finally: + for name in files(drop): + os.remove(os.path.join(drop, name)) + os.rmdir(drop) + + def test_docs_and_card(): doc = a2a.__doc__ required = ( @@ -328,6 +429,8 @@ def main(): test_malformed() test_unsupported() test_nothing_stored() + test_version() + test_a2a_content_type() test_docs_and_card() failed = [n for n, ok in results if not ok] print("%d/%d passed" % (len(results) - len(failed), len(results)))