326 lines
13 KiB
Python
326 lines
13 KiB
Python
"""Exercise the pure Marqdo network and agent packages against one frozen CLI."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import json
|
|
import os
|
|
import shutil
|
|
import socket
|
|
import ssl
|
|
import subprocess
|
|
import tempfile
|
|
import threading
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
NET = ROOT / "marqdo-net" / "demo.mq.md"
|
|
|
|
|
|
def args(cli, source, function, url, *, grant=True, **extra):
|
|
command = [str(cli), "call", str(source), function,
|
|
"--fuel", "16000000", "--timeout", "15"]
|
|
if grant:
|
|
command.extend(["--allow-net", "127.0.0.1"])
|
|
for name, value in {"url": url, **extra}.items():
|
|
command.extend(["--arg", f"{name}={json.dumps(value, ensure_ascii=False)}"])
|
|
return command
|
|
|
|
|
|
def typed_value(result):
|
|
assert result.returncode == 0, result.stderr or result.stdout
|
|
return unpack(json.loads(result.stdout)["value"])
|
|
|
|
|
|
def unpack(value):
|
|
kind = value["type"]
|
|
if kind == "map":
|
|
return {k: unpack(v) for k, v in value["entries"].items()}
|
|
if kind == "list":
|
|
return [unpack(item) for item in value["items"]]
|
|
if kind == "int":
|
|
return int(value["decimal"])
|
|
if kind == "none":
|
|
return None
|
|
return value["value"]
|
|
|
|
|
|
def read_request(connection):
|
|
pending = bytearray()
|
|
while b"\r\n\r\n" not in pending:
|
|
part = connection.recv(1024)
|
|
assert part, "unexpected EOF in request head"
|
|
pending.extend(part)
|
|
assert len(pending) <= 20000, "oversized test request"
|
|
head, body = pending.split(b"\r\n\r\n", 1)
|
|
lines = head.decode("ascii").split("\r\n")
|
|
headers = dict(line.split(": ", 1) for line in lines[1:])
|
|
size = int(headers.get("Content-Length", "0"))
|
|
while len(body) < size:
|
|
part = connection.recv(1024)
|
|
assert part, "unexpected EOF in request body"
|
|
body.extend(part)
|
|
assert len(body) == size
|
|
return lines[0], headers, bytes(body)
|
|
|
|
|
|
@contextmanager
|
|
def server(respond, *, tls=None, expect_tls_refusal=False, request_count=1):
|
|
errors = []
|
|
with socket.create_server(("127.0.0.1", 0)) as listener:
|
|
listener.settimeout(10)
|
|
scheme = "http" if tls is None else "https"
|
|
url = f"{scheme}://127.0.0.1:{listener.getsockname()[1]}"
|
|
|
|
def serve():
|
|
try:
|
|
for _ in range(request_count):
|
|
connection, _ = listener.accept()
|
|
with connection:
|
|
connection.settimeout(8)
|
|
if tls is None:
|
|
respond(connection)
|
|
else:
|
|
try:
|
|
secured = tls.wrap_socket(connection, server_side=True)
|
|
except ssl.SSLError:
|
|
if expect_tls_refusal:
|
|
return
|
|
raise
|
|
with secured:
|
|
assert not expect_tls_refusal, "untrusted TLS was accepted"
|
|
respond(secured)
|
|
except Exception as exc:
|
|
errors.append(exc)
|
|
|
|
worker = threading.Thread(target=serve, daemon=True)
|
|
worker.start()
|
|
try:
|
|
yield url
|
|
finally:
|
|
worker.join(11)
|
|
assert not worker.is_alive(), "mock server did not finish"
|
|
if errors:
|
|
raise errors[0]
|
|
|
|
|
|
def request(cli, respond, *, tls=None, env=None, method="GET", body=""):
|
|
with server(respond, tls=tls) as url:
|
|
cmd = args(cli, NET, "request", url + "/demo?q=ready", method=method, body=body)
|
|
result = subprocess.run(cmd + ["--json"], env=env, capture_output=True,
|
|
text=True, timeout=20)
|
|
return typed_value(result)
|
|
|
|
|
|
def reply(parts, check=None):
|
|
def respond(connection):
|
|
request_line, headers, body = read_request(connection)
|
|
if check:
|
|
check(request_line, headers, body)
|
|
for part in parts:
|
|
connection.sendall(part)
|
|
|
|
return respond
|
|
|
|
|
|
def fixed(status, body, content_type="text/plain"):
|
|
return (f"HTTP/1.1 {status} Test\r\nContent-Type: {content_type}\r\n"
|
|
f"Content-Length: {len(body)}\r\n\r\n").encode() + body
|
|
|
|
|
|
def data_chunk(data):
|
|
return f"{len(data):x}\r\n".encode() + data + b"\r\n"
|
|
|
|
|
|
def assert_result(actual, **fields):
|
|
assert all(actual.get(key) == value for key, value in fields.items()), actual
|
|
|
|
|
|
def http(cli):
|
|
payload = "多字节-".encode() + b"z" * 2048
|
|
|
|
def check_post(line, headers, body):
|
|
assert line == "POST /demo?q=ready HTTP/1.1", line
|
|
assert headers["Host"].startswith("127.0.0.1:"), headers
|
|
assert headers["Content-Type"] == "application/json", headers
|
|
assert json.loads(body) == {"query": "你好"}, body
|
|
|
|
wire = (b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"
|
|
+ data_chunk(payload[:1]) + data_chunk(payload[1:10])
|
|
+ data_chunk(payload[10:]) + b"0\r\nX-Example: end\r\n\r\n")
|
|
pieces = [wire[i:i + 1] for i in range(80)]
|
|
pieces.extend(wire[i:i + 1024] for i in range(80, len(wire), 1024))
|
|
response = request(cli, reply(pieces, check_post), method="POST",
|
|
body='{"query":"你好"}')
|
|
assert_result(response["value"], status=200, body=payload.decode())
|
|
for status in (404, 503):
|
|
response = request(cli, reply([fixed(status, b"problem")]))
|
|
assert_result(response["value"], status=status, body="problem")
|
|
for wire, code in [
|
|
(b"HTTP/1.1 200 OK\r\nContent-Length: 9\r\n\r\nshort", "http.eof"),
|
|
(b"HTTP/1.1 200 OK\r\nContent-Length: 32769\r\n\r\n", "http.framing"),
|
|
(b"HTTP/1.1 200 OK\r\nContent-Length: 1\r\nTransfer-Encoding: chunked\r\n\r\n",
|
|
"http.framing"),
|
|
(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\ng\r\na\r\n",
|
|
"http.chunked"),
|
|
]:
|
|
assert_result(request(cli, reply([wire])), ok=False, code=code)
|
|
|
|
|
|
def denied(cli):
|
|
with socket.create_server(("127.0.0.1", 0)) as listener:
|
|
url = f"http://127.0.0.1:{listener.getsockname()[1]}"
|
|
run = subprocess.run(args(cli, NET, "request", url, grant=False),
|
|
capture_output=True, text=True, timeout=10)
|
|
assert run.returncode == 1 and "permission.denied" in run.stderr, run
|
|
injected = subprocess.run(args(cli, NET, "request", url + "/a\r\nb") + ["--json"],
|
|
capture_output=True, text=True, timeout=10)
|
|
assert_result(typed_value(injected), ok=False, code="http.url")
|
|
listener.setblocking(False)
|
|
try:
|
|
accepted, _ = listener.accept()
|
|
except BlockingIOError:
|
|
return
|
|
accepted.close()
|
|
raise AssertionError("a denied request reached the network")
|
|
|
|
|
|
def tls_http(cli):
|
|
with tempfile.TemporaryDirectory(prefix="marqdo-reference-tls-") as name:
|
|
temporary = Path(name)
|
|
(temporary / "server.ext").write_text(
|
|
"subjectAltName=IP:127.0.0.1\nextendedKeyUsage=serverAuth\n")
|
|
|
|
def openssl(*arguments):
|
|
subprocess.run(["openssl", *arguments], cwd=temporary,
|
|
capture_output=True, check=True, timeout=15)
|
|
|
|
openssl("req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "2",
|
|
"-keyout", "ca.key", "-out", "ca.pem", "-subj", "/CN=Marqdo Test CA",
|
|
"-addext", "basicConstraints=critical,CA:TRUE")
|
|
openssl("req", "-new", "-newkey", "rsa:2048", "-nodes", "-keyout", "server.key",
|
|
"-out", "server.csr", "-subj", "/CN=localhost")
|
|
openssl("x509", "-req", "-in", "server.csr", "-CA", "ca.pem", "-CAkey", "ca.key",
|
|
"-set_serial", "1", "-days", "2", "-extfile", "server.ext", "-out", "server.pem")
|
|
tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
|
tls.load_cert_chain(temporary / "server.pem", temporary / "server.key")
|
|
# An environment-scoped CA loaded by rustls-native-certs.
|
|
env = dict(os.environ, SSL_CERT_FILE=str(temporary / "ca.pem"), SSL_CERT_DIR="")
|
|
response = request(cli, reply([fixed(200, b"verified")]), tls=tls, env=env)
|
|
assert_result(response["value"], status=200, body="verified")
|
|
env["SSL_CERT_FILE"] = str(temporary / "absent.pem")
|
|
with server(lambda _: None, tls=tls, expect_tls_refusal=True) as url:
|
|
rejected = subprocess.run(args(cli, NET, "request", url), env=env,
|
|
capture_output=True, text=True, timeout=12)
|
|
assert rejected.returncode == 1, rejected
|
|
|
|
|
|
def live_sse(cli):
|
|
observed = threading.Event()
|
|
first = "id: evt-1\r\nevent: token\r\ndata: 你\r\ndata: 好\r\n\r\n".encode()
|
|
second = b"data: done\n\n"
|
|
|
|
def respond(connection):
|
|
read_request(connection)
|
|
connection.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream; charset=utf-8\r\n"
|
|
b"Transfer-Encoding: chunked\r\n\r\n")
|
|
for i in range(0, len(first), 3):
|
|
connection.sendall(data_chunk(first[i:i + 3]))
|
|
assert observed.wait(6), "client produced no output before the next SSE event"
|
|
connection.sendall(data_chunk(second))
|
|
assert connection.recv(1) == b"", "client did not close after the second event"
|
|
|
|
with server(respond) as url, tempfile.TemporaryFile(mode="w+t") as diagnostics:
|
|
command = args(cli, NET, "events", url) + ["--event-stream", "jsonl"]
|
|
output = bytearray()
|
|
terminal = None
|
|
with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=diagnostics) as process:
|
|
for line in process.stdout:
|
|
event = json.loads(line)
|
|
if event["kind"] == "stdout.chunk":
|
|
output.extend(base64.b64decode(event["payload"]["data_base64"]))
|
|
if "token:evt-1:你\n好\n".encode() in output:
|
|
observed.set()
|
|
if event["kind"].startswith("run.") and event["kind"] != "run.started":
|
|
terminal = event["kind"]
|
|
code = process.wait(timeout=5)
|
|
diagnostics.seek(0)
|
|
assert code == 0 and terminal == "run.completed", diagnostics.read()
|
|
assert output.decode() == "token:evt-1:你\n好\nmessage:evt-1:done\n", output
|
|
|
|
|
|
def timeout(cli):
|
|
def stall(connection):
|
|
read_request(connection)
|
|
connection.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\n")
|
|
assert connection.recv(1) == b"", "timed-out client did not close the stream"
|
|
|
|
with server(stall) as url:
|
|
result = subprocess.run(args(cli, NET, "request", url),
|
|
capture_output=True, text=True, timeout=12)
|
|
assert result.returncode == 1 and "tcp read failed:" in result.stderr, result
|
|
|
|
|
|
def agent(cli):
|
|
with tempfile.TemporaryDirectory(prefix="marqdo-agent-") as name:
|
|
project = Path(name) / "agent"
|
|
shutil.copytree(ROOT / "marqdo-agent", project)
|
|
shutil.copytree(ROOT / "marqdo-net", project / "deps" / "net")
|
|
for command in (["lock"], ["sync"], ["check", "index.mq.md"]):
|
|
result = subprocess.run([str(cli), *command], cwd=project, text=True,
|
|
capture_output=True, timeout=10)
|
|
assert result.returncode == 0, result.stderr
|
|
|
|
def ask(url, tools):
|
|
command = args(cli, project / "index.mq.md", "ask", url,
|
|
query="How many?", tools=tools)
|
|
return typed_value(subprocess.run(command + ["--json"], cwd=project,
|
|
capture_output=True, text=True, timeout=20))
|
|
|
|
calls = []
|
|
|
|
def mock(connection):
|
|
line, headers, body = read_request(connection)
|
|
assert line == "POST / HTTP/1.1" and headers["Accept"] == "application/json"
|
|
item = json.loads(body)
|
|
calls.append(item)
|
|
if len(item["messages"]) == 1:
|
|
response = {"model": "test-model", "tool": "sum", "input": [20, 22]}
|
|
else:
|
|
assert item["tools"] == []
|
|
assert item["messages"][-1] == {"role": "tool", "tool": "sum", "value": 42}
|
|
response = {"model": "test-model", "answer": "42"}
|
|
connection.sendall(fixed(200, json.dumps(response).encode(), "application/json"))
|
|
|
|
with server(mock, request_count=2) as url:
|
|
successful = ask(url, ["sum"])
|
|
assert len(calls) == 2 and calls[0]["tools"] == ["sum"]
|
|
assert_result(successful["value"], answer="42", model="test-model",
|
|
tools=[{"model": "test-model", "tool": "sum", "output": 42}])
|
|
calls.clear()
|
|
with server(mock) as url:
|
|
rejected = ask(url, [])
|
|
assert_result(rejected, ok=False, code="agent.tool_denied")
|
|
assert len(calls) == 1
|
|
with server(reply([fixed(503, b"unavailable")])) as url:
|
|
unavailable = ask(url, ["sum"])
|
|
assert_result(unavailable, ok=False, code="agent.http")
|
|
|
|
|
|
CASES = {
|
|
"HTTP status, POST and bounded framing": http,
|
|
"URL validation and denial before connect": denied,
|
|
"TLS with an explicit local trust root": tls_http,
|
|
"live SSE visibility and caller close": live_sse,
|
|
"socket read timeout and teardown": timeout,
|
|
"agent tool authority and two-turn provenance": agent,
|
|
}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
cli = Path(os.environ["MARQDO_BIN"]).resolve()
|
|
for name, check in CASES.items():
|
|
check(cli)
|
|
print(f"PASS: {name}", flush=True)
|