Add frozen HTTP/SSE and Agent conformance fixtures #1
No files matched your search
+7
-5
@@ -26,7 +26,7 @@ works" claim. Unknown/newer protocol versions fail closed.
|
||||
| macOS arm64/x86_64 | **unverified** by this repository unless `tests/run_all.py` is run there with a native build |
|
||||
| Windows x86_64 | **unsupported** for plugin/provider C ABI in this fixture; the pure `.mq.md`, kernel and tool cases are portable but not claimed until run |
|
||||
|
||||
`plugin/build_all.sh` and `provider/build_all.sh` build for the *host* target
|
||||
`plugin/build.sh` and `provider/build.sh` build for the *host* target
|
||||
and write that target triple + artifact SHA-256 into the generated manifest;
|
||||
the committed manifests contain zero digests and are templates only.
|
||||
|
||||
@@ -55,7 +55,9 @@ repository never claims `strict` L2 or an OS sandbox for worker transports.
|
||||
|
||||
## Environment assumptions
|
||||
|
||||
Linux x86_64, Python 3 (stdlib only), a C compiler (`cc`), Git. No network is
|
||||
required: the consumer test creates its pinned Git repository locally with
|
||||
`git init` + `git commit` and a full SHA. No Node/Python runtime is required
|
||||
for the kernel case: `mocklang` is a POSIX shell script.
|
||||
Linux x86_64 with glibc, Python 3 (stdlib only), a C compiler (`cc`), Git and
|
||||
OpenSSL's CLI for the ephemeral TLS fixture. The cases use loopback only.
|
||||
The pinned Git consumer creates its source repository locally. The Agent
|
||||
consumer stages a path dependency and runs the normal lock and sync path.
|
||||
The foreign kernel is a POSIX shell script. The suite consumes an extracted
|
||||
release archive with `marqdo`, `marqdo-provider-worker` and `stdlib/`.
|
||||
@@ -1,7 +1,7 @@
|
||||
# marqdo-extension-conformance
|
||||
|
||||
Independent, physically separate conformance fixtures for
|
||||
[RFC-EXT-0001](../marqdo-cli/docs/architecture/RFC-EXT-0001.md): a third-party
|
||||
[RFC-EXT-0001](https://git.cflmy.cn/cflmy/marqdo-cli/src/branch/master/docs/architecture/RFC-EXT-0001.md): a third-party
|
||||
repository that provides all five extension kinds **without modifying or
|
||||
recompiling `marqdo-cli`**.
|
||||
|
||||
@@ -17,22 +17,19 @@ the CLI workspace.
|
||||
| `kernel/` | Foreign kernel (`mocklang`) | `kernel/kernel.json`, one-shot process |
|
||||
| `provider/` | Resource provider v2 (`demo.sensor`) | `provider/provider.json`, worker helper + C ABI |
|
||||
| `tool/` | CLI Tool | `tool/tool.json`, `inspect-ext` command |
|
||||
| [`marqdo-net/`](marqdo-net/README.md) | HTTP(S)/SSE library | Blocking streams over the published resource API |
|
||||
| [`marqdo-agent/`](marqdo-agent/README.md) | Agent library | A sequential mock-model conversation with an explicit tool allowlist |
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
cargo build --release -p marqdo-cli # in ../marqdo-cli (once)
|
||||
export MARQDO_BIN=/abs/path/to/target/release/marqdo
|
||||
# Ship the provider helper sibling exactly as the release archive does:
|
||||
cp /abs/path/to/target/release/marqdo-provider-worker "$(dirname "$MARQDO_BIN")"/
|
||||
|
||||
./scripts/build_all.sh
|
||||
python3 tests/run_all.py # writes evidence/results.json
|
||||
export MARQDO_BIN=/absolute/path/to/extracted/install/marqdo
|
||||
python3 tests/run_all.py # builds the C fixtures and writes evidence/results.json
|
||||
```
|
||||
|
||||
`tests/verify_frozen_cli.py` hashes `$MARQDO_BIN` before and after the suite and
|
||||
fails if the binary changed. The committed `evidence/results.json` is generated,
|
||||
not hand-edited; `evidence/manifest.json` is produced by the CLI repository's
|
||||
fails if the binary changed. The runner checks both executable digests and
|
||||
generates `evidence/results.json`; `evidence/manifest.json` is produced by the CLI repository's
|
||||
`tools/ci/verify_extension_contracts.py`.
|
||||
|
||||
## Contract
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
/marqdo.lock
|
||||
/.marqdo/
|
||||
/deps/
|
||||
@@ -0,0 +1,17 @@
|
||||
# marqdo-agent reference package
|
||||
|
||||
`ask(url, query, tools = [])` uses the pinned `marqdo-net` dependency to
|
||||
perform a bounded two-turn conversation with the fixture model contract.
|
||||
The endpoint receives JSON with `messages` and `tools` and responds with a
|
||||
`model` identity plus an `answer` or a `tool` and `input`. The caller may
|
||||
enable the pure `sum` tool. The tool input is bounded and checked before
|
||||
action. A tool response and its model identity are included in provenance.
|
||||
The second turn asks for the final answer and permits no additional action.
|
||||
|
||||
For a local copy, put `marqdo-net` in `deps/net` under this package, then run
|
||||
`marqdo lock`, `marqdo sync` and `marqdo check index.mq.md`. The external
|
||||
conformance suite performs those steps in a temporary directory and operates
|
||||
a loopback mock service without model credentials.
|
||||
|
||||
The reference executes requests sequentially. The parallel success/failure/
|
||||
timeout scenario requires the proposed Task and cancellation contracts.
|
||||
@@ -0,0 +1,105 @@
|
||||
---
|
||||
import:
|
||||
http: "@net"
|
||||
json: "std:data/json"
|
||||
---
|
||||
|
||||
# @exec Agent reference
|
||||
|
||||
## ask
|
||||
|
||||
Use a bounded two-turn model conversation. The mock model may request one
|
||||
local tool explicitly enabled by the caller. Both turns use the same endpoint.
|
||||
The result includes the model identity and tool outcome as provenance.
|
||||
|
||||
`params(url, query, tools = [])`
|
||||
`if 长度(query) > 4096`
|
||||
`return failure("agent.input_limit", "Prompt exceeds the reference agent limit")`
|
||||
`end`
|
||||
`first = exchange(url, [{role: "user", content: query}], tools)`
|
||||
`if not first.ok`
|
||||
`return first`
|
||||
`end`
|
||||
`reply = first.value`
|
||||
`if map.has(reply, "answer")`
|
||||
`return answer(reply, [])`
|
||||
`end`
|
||||
`if not map.has(reply, "tool") or 类型(reply.tool) != "Text" or not map.has(reply, "input")`
|
||||
`return failure("agent.response", "Expected an answer or a tool request")`
|
||||
`end`
|
||||
`tool = local_tool(reply.tool, reply.input, tools)`
|
||||
`if not tool.ok`
|
||||
`return tool`
|
||||
`end`
|
||||
`transcript = [{role: "user", content: query}, {role: "assistant", tool: reply.tool, input: reply.input}, {role: "tool", tool: reply.tool, value: tool.value}]`
|
||||
`second = exchange(url, transcript, [])`
|
||||
`if not second.ok`
|
||||
`return second`
|
||||
`end`
|
||||
`return answer(second.value, [{model: reply.model, tool: reply.tool, output: tool.value}])`
|
||||
|
||||
## exchange
|
||||
|
||||
`params(url, messages, tools)`
|
||||
`request = json.格式化({messages: messages, tools: tools})`
|
||||
`result = http.request(url, "POST", request, "application/json")`
|
||||
`if not result.ok`
|
||||
`return result`
|
||||
`end`
|
||||
`received = result.value`
|
||||
`if received.status != 200`
|
||||
`return failure("agent.http", "Model returned HTTP " + 文本(received.status))`
|
||||
`end`
|
||||
`parsed = json.解析(received.body)`
|
||||
`if not parsed.ok`
|
||||
`return failure("agent.response", "Model returned invalid JSON")`
|
||||
`end`
|
||||
`reply = parsed.value`
|
||||
`if 类型(reply) != "Map" or not map.has(reply, "model") or 类型(reply.model) != "Text"`
|
||||
`return failure("agent.response", "Model identity is missing")`
|
||||
`end`
|
||||
`return {ok: true, value: reply}`
|
||||
|
||||
## local_tool
|
||||
|
||||
The model describes a request. The caller supplies the explicit local
|
||||
allowlist, and the library validates the data before choosing the action.
|
||||
|
||||
`params(name, input, tools)`
|
||||
`allowed = false`
|
||||
`i = 0`
|
||||
`while i < 长度(tools)`
|
||||
`if tools[i] == name`
|
||||
`allowed = true`
|
||||
`end`
|
||||
`i = i + 1`
|
||||
`end`
|
||||
`if not allowed or name != "sum"`
|
||||
`return failure("agent.tool_denied", "Tool is unavailable for this conversation")`
|
||||
`end`
|
||||
`if 类型(input) != "List" or 长度(input) > 32`
|
||||
`return failure("agent.tool_input", "sum expects up to 32 integers")`
|
||||
`end`
|
||||
`sum = 0`
|
||||
`i = 0`
|
||||
`while i < 长度(input)`
|
||||
`if 类型(input[i]) != "Int"`
|
||||
`return failure("agent.tool_input", "sum expects integers")`
|
||||
`end`
|
||||
`sum = sum + input[i]`
|
||||
`i = i + 1`
|
||||
`end`
|
||||
`return {ok: true, value: sum}`
|
||||
|
||||
## answer
|
||||
|
||||
`params(reply, tools)`
|
||||
`if not map.has(reply, "answer") or 类型(reply.answer) != "Text"`
|
||||
`return failure("agent.response", "Expected the model's final answer")`
|
||||
`end`
|
||||
`return {ok: true, value: {answer: reply.answer, model: reply.model, tools: tools}}`
|
||||
|
||||
## failure
|
||||
|
||||
`params(code, message)`
|
||||
`return {ok: false, code: code, message: message}`
|
||||
@@ -0,0 +1,7 @@
|
||||
project:
|
||||
name: marqdo-agent
|
||||
version: 0.1.0
|
||||
marqdo: ">=3.0.0-beta.1,<4.0.0"
|
||||
dependencies:
|
||||
net:
|
||||
path: "./deps/net"
|
||||
@@ -0,0 +1,2 @@
|
||||
/marqdo.lock
|
||||
/.marqdo/
|
||||
@@ -0,0 +1,25 @@
|
||||
# marqdo-net reference package
|
||||
|
||||
This package composes blocking TCP/TLS resources, bounded Memory and the
|
||||
shipped UTF-8 and stream helpers. Supply the destination's exact host via
|
||||
`--allow-net`. The caller owns host selection and any additional address
|
||||
policy. HTTPS uses the CLI's normal trust store.
|
||||
|
||||
- `request(url, method = "GET", body = "", accept = "text/plain")` returns a
|
||||
Result with the HTTP status, headers and UTF-8 body. HTTP error statuses
|
||||
are returned as status data. Transport errors follow the CLI's host policy.
|
||||
- `sse.start/next/close` delivers one event at a time, including the carried
|
||||
event ID and multiline data. The caller must use the reader returned by
|
||||
`next` and close it after consumption, early exit, or a recoverable error.
|
||||
- The reference accepts ASCII HTTP(S) URLs with a DNS name or IPv4 and an
|
||||
optional numeric port. Supply a URL-encoded path. GET and JSON POST are
|
||||
supported, with 16 KiB request and 32 KiB response body budgets. SSE
|
||||
accepts LF and CRLF. The client uses one connection per request and does
|
||||
not follow redirects.
|
||||
|
||||
The package uses the existing blocking socket timeout. Closing a reader stops
|
||||
future reads. Interrupting an in-flight read requires a later resource protocol.
|
||||
|
||||
```sh
|
||||
marqdo call marqdo-net/demo.mq.md request --arg 'url="http://127.0.0.1:8080/"' --allow-net 127.0.0.1 --json
|
||||
```
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
import:
|
||||
http: "./index.mq.md"
|
||||
sse: "./sse.mq.md"
|
||||
---
|
||||
|
||||
# @exec Network examples
|
||||
|
||||
## request
|
||||
|
||||
`params(url, method = "GET", body = "")`
|
||||
`return http.request(url, method, body)`
|
||||
|
||||
## events
|
||||
|
||||
`params(url, maximum = 2)`
|
||||
`started = sse.start(url)`
|
||||
`if not started.ok`
|
||||
`return started`
|
||||
`end`
|
||||
`reader = started.value`
|
||||
`i = 0`
|
||||
`while i < maximum`
|
||||
`item = sse.next(reader)`
|
||||
`if not item.ok`
|
||||
`sse.close(reader)`
|
||||
`return item`
|
||||
`end`
|
||||
`reader = item.value.reader`
|
||||
`event = item.value.event`
|
||||
`if event == None`
|
||||
`sse.close(reader)`
|
||||
`return {ok: false, code: "demo.eof", message: "Stream ended before the requested events"}`
|
||||
`end`
|
||||
`print(event.kind + ":" + event.id + ":" + event.data)`
|
||||
`i = i + 1`
|
||||
`end`
|
||||
`sse.close(reader)`
|
||||
`return {ok: true, value: i}`
|
||||
@@ -0,0 +1,144 @@
|
||||
---
|
||||
import:
|
||||
utf8: "std:text/utf8"
|
||||
fmt: "std:format"
|
||||
io: "std:io/stream"
|
||||
response: "./response.mq.md"
|
||||
---
|
||||
|
||||
# @exec HTTP client
|
||||
|
||||
## start
|
||||
|
||||
Open one HTTP(S) request. The returned response owns a stream that the caller
|
||||
must close. Body text is UTF-8. The request target must already be URL encoded.
|
||||
|
||||
`params(url, method = "GET", body = "", accept = "text/plain")`
|
||||
`if method != "GET" and method != "POST"`
|
||||
`return response.failure("http.method", "Only GET and POST are supported")`
|
||||
`end`
|
||||
`if accept != "text/plain" and accept != "application/json" and accept != "text/event-stream"`
|
||||
`return response.failure("http.accept", "Unsupported Accept value")`
|
||||
`end`
|
||||
`endpoint = target(url)`
|
||||
`if not endpoint.ok`
|
||||
`return endpoint`
|
||||
`end`
|
||||
`endpoint = endpoint.value`
|
||||
`if 长度(body) > 16384`
|
||||
`return response.failure("http.request_limit", "Request text exceeds its byte budget")`
|
||||
`end`
|
||||
`size = fmt.字节长度(body)`
|
||||
`if size > 16384 or (method == "GET" and size > 0)`
|
||||
`return response.failure("http.request_limit", "Invalid request body length")`
|
||||
`end`
|
||||
`head = method + " " + endpoint.path + " HTTP/1.1\r\nHost: " + endpoint.authority + "\r\nConnection: close\r\nAccept: " + accept + "\r\n"`
|
||||
`if method == "POST"`
|
||||
`head = head + "Content-Type: application/json\r\nContent-Length: " + 文本(size) + "\r\n"`
|
||||
`end`
|
||||
`buf = memory.new(1, 1)`
|
||||
`length = utf8.编码(head + "\r\n" + body, buf, 0)`
|
||||
`handle = resource.open(endpoint.kind, endpoint.address, ["read", "write"])`
|
||||
`sent = io.写全部(handle, buf, 0, length)`
|
||||
`if not sent.ok`
|
||||
`resource.close(handle)`
|
||||
`return sent`
|
||||
`end`
|
||||
`result = response.open(handle, buf)`
|
||||
`if not result.ok`
|
||||
`resource.close(handle)`
|
||||
`end`
|
||||
`return result`
|
||||
|
||||
## request
|
||||
|
||||
Return status, normalized headers and a bounded UTF-8 response body.
|
||||
|
||||
`params(url, method = "GET", body = "", accept = "text/plain")`
|
||||
`opened = start(url, method, body, accept)`
|
||||
`if not opened.ok`
|
||||
`return opened`
|
||||
`end`
|
||||
`incoming = opened.value`
|
||||
`result = response.collect(incoming.stream)`
|
||||
`resource.close(incoming.stream.cursor.handle)`
|
||||
`if not result.ok`
|
||||
`return result`
|
||||
`end`
|
||||
`return {ok: true, value: {status: incoming.status, headers: incoming.headers, body: result.value}}`
|
||||
|
||||
## target
|
||||
|
||||
`params(url)`
|
||||
`invalid = response.failure("http.url", "Expected HTTP(S), a DNS name or IPv4, and an optional numeric port")`
|
||||
`if 长度(url) > 2048`
|
||||
`return invalid`
|
||||
`end`
|
||||
`points = text.codepoints(url)`
|
||||
`separator = 0`
|
||||
`while separator < 长度(points) and points[separator] != 58`
|
||||
`separator = separator + 1`
|
||||
`end`
|
||||
`if separator + 3 >= 长度(points) or points[separator + 1] != 47 or points[separator + 2] != 47`
|
||||
`return invalid`
|
||||
`end`
|
||||
`scheme = string_part(points, 0, separator)`
|
||||
`kind = "tcp"`
|
||||
`port = 80`
|
||||
`if scheme == "https"`
|
||||
`kind = "tls"`
|
||||
`port = 443`
|
||||
`else`
|
||||
`if scheme != "http"`
|
||||
`return invalid`
|
||||
`end`
|
||||
`end`
|
||||
`first = separator + 3`
|
||||
`last = first`
|
||||
`while last < 长度(points) and points[last] != 47 and points[last] != 63`
|
||||
`last = last + 1`
|
||||
`end`
|
||||
`authority = string_part(points, first, last)`
|
||||
`split = first`
|
||||
`while split < last and points[split] != 58`
|
||||
`c = points[split]`
|
||||
`if not ((c >= 48 and c <= 57) or (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 45 or c == 46)`
|
||||
`return invalid`
|
||||
`end`
|
||||
`split = split + 1`
|
||||
`end`
|
||||
`if split == first or split - first > 253`
|
||||
`return invalid`
|
||||
`end`
|
||||
`if split < last`
|
||||
`port = response.number(string_part(points, split + 1, last), 10, 65535)`
|
||||
`if port == None or port == 0`
|
||||
`return invalid`
|
||||
`end`
|
||||
`end`
|
||||
`path = "/"`
|
||||
`if last < 长度(points)`
|
||||
`i = last`
|
||||
`while i < 长度(points)`
|
||||
`if points[i] < 33 or points[i] > 126 or points[i] == 35 or points[i] == 92`
|
||||
`return invalid`
|
||||
`end`
|
||||
`i = i + 1`
|
||||
`end`
|
||||
`path = string_part(points, last, 长度(points))`
|
||||
`if points[last] == 63`
|
||||
`path = "/" + path`
|
||||
`end`
|
||||
`end`
|
||||
`host = string_part(points, first, split)`
|
||||
`return {ok: true, value: {kind: kind, address: host + ":" + 文本(port), authority: authority, path: path}}`
|
||||
|
||||
## string_part
|
||||
|
||||
`params(points, first, last)`
|
||||
`result = ""`
|
||||
`while first < last`
|
||||
`result = result + text.from_codepoint(points[first])`
|
||||
`first = first + 1`
|
||||
`end`
|
||||
`return result`
|
||||
@@ -0,0 +1,5 @@
|
||||
project:
|
||||
name: marqdo-net
|
||||
version: 0.1.0
|
||||
marqdo: ">=3.0.0-beta.1,<4.0.0"
|
||||
dependencies: {}
|
||||
@@ -0,0 +1,307 @@
|
||||
---
|
||||
import:
|
||||
utf8: "std:text/utf8"
|
||||
---
|
||||
|
||||
# @exec HTTP response framing
|
||||
|
||||
## failure
|
||||
|
||||
`params(code, message)`
|
||||
`return {ok: false, code: code, message: message}`
|
||||
|
||||
## number
|
||||
|
||||
Parse a bounded unsigned decimal or hexadecimal number.
|
||||
|
||||
`params(token, base, limit)`
|
||||
`points = text.codepoints(token)`
|
||||
`if 长度(points) == 0`
|
||||
`return None`
|
||||
`end`
|
||||
`n = 0`
|
||||
`i = 0`
|
||||
`while i < 长度(points)`
|
||||
`p = points[i]`
|
||||
`digit = p - 48`
|
||||
`if p < 48 or p > 57`
|
||||
`digit = base`
|
||||
`if base == 16 and p >= 65 and p <= 70`
|
||||
`digit = p - 55`
|
||||
`end`
|
||||
`if base == 16 and p >= 97 and p <= 102`
|
||||
`digit = p - 87`
|
||||
`end`
|
||||
`end`
|
||||
`if digit >= base`
|
||||
`return None`
|
||||
`end`
|
||||
`n = n * base + digit`
|
||||
`if n > limit`
|
||||
`return None`
|
||||
`end`
|
||||
`i = i + 1`
|
||||
`end`
|
||||
`return n`
|
||||
|
||||
## raw_byte
|
||||
|
||||
`params(initial)`
|
||||
`cursor = initial`
|
||||
`if cursor.index == cursor.count and not cursor.eof`
|
||||
`read = resource.read(cursor.handle, cursor.buf, 0, 1024)`
|
||||
`if not read.ok`
|
||||
`return read`
|
||||
`end`
|
||||
`cursor = {handle: cursor.handle, buf: cursor.buf, index: 0, count: read.value.count, eof: read.value.eof}`
|
||||
`end`
|
||||
`if cursor.index == cursor.count`
|
||||
`return {ok: true, value: {byte: None, cursor: cursor}}`
|
||||
`end`
|
||||
`b = cursor.buf[cursor.index]`
|
||||
`return {ok: true, value: {byte: b, cursor: map.set(cursor, "index", cursor.index + 1)}}`
|
||||
|
||||
## raw_line
|
||||
|
||||
Read a bounded ASCII line ending in CRLF, including across resource reads.
|
||||
|
||||
`params(cursor)`
|
||||
`line = ""`
|
||||
`ended = false`
|
||||
`while 长度(line) <= 2048`
|
||||
`result = raw_byte(cursor)`
|
||||
`if not result.ok`
|
||||
`return result`
|
||||
`end`
|
||||
`cursor = result.value.cursor`
|
||||
`b = result.value.byte`
|
||||
`if b == None`
|
||||
`return failure("http.eof", "Unexpected EOF in HTTP framing")`
|
||||
`end`
|
||||
`if ended and b == 10`
|
||||
`return {ok: true, value: {line: line, cursor: cursor}}`
|
||||
`end`
|
||||
`if ended or b >= 127 or (b < 32 and b != 9 and b != 13)`
|
||||
`return failure("http.framing", "Invalid HTTP framing line")`
|
||||
`end`
|
||||
`if b == 13`
|
||||
`ended = true`
|
||||
`else`
|
||||
`line = line + text.from_codepoint(b)`
|
||||
`end`
|
||||
`end`
|
||||
`return failure("http.line_limit", "HTTP framing line exceeds 2048 bytes")`
|
||||
|
||||
## field
|
||||
|
||||
`params(line)`
|
||||
`points = text.codepoints(line)`
|
||||
`i = 0`
|
||||
`key = ""`
|
||||
`while i < 长度(points) and points[i] != 58`
|
||||
`p = points[i]`
|
||||
`if p >= 65 and p <= 90`
|
||||
`p = p + 32`
|
||||
`end`
|
||||
`if not ((p >= 97 and p <= 122) or (p >= 48 and p <= 57) or p == 45)`
|
||||
`return failure("http.header", "Unsupported HTTP header name")`
|
||||
`end`
|
||||
`key = key + text.from_codepoint(p)`
|
||||
`i = i + 1`
|
||||
`end`
|
||||
`if i == 0 or i == 长度(points)`
|
||||
`return failure("http.header", "Invalid HTTP header")`
|
||||
`end`
|
||||
`i = i + 1`
|
||||
`j = 长度(points)`
|
||||
`while i < j and (points[i] == 32 or points[i] == 9)`
|
||||
`i = i + 1`
|
||||
`end`
|
||||
`while j > i and (points[j - 1] == 32 or points[j - 1] == 9)`
|
||||
`j = j - 1`
|
||||
`end`
|
||||
`value = ""`
|
||||
`while i < j`
|
||||
`value = value + text.from_codepoint(points[i])`
|
||||
`i = i + 1`
|
||||
`end`
|
||||
`return {ok: true, value: {key: key, text: value}}`
|
||||
|
||||
## open
|
||||
|
||||
`params(handle, buf)`
|
||||
`first = raw_line({handle: handle, buf: buf, index: 0, count: 0, eof: false})`
|
||||
`if not first.ok`
|
||||
`return first`
|
||||
`end`
|
||||
`cursor = first.value.cursor`
|
||||
`points = text.codepoints(first.value.line)`
|
||||
`if 长度(points) < 12`
|
||||
`return failure("http.status", "Invalid HTTP status line")`
|
||||
`end`
|
||||
`prefix = ""`
|
||||
`i = 0`
|
||||
`while i < 9`
|
||||
`prefix = prefix + text.from_codepoint(points[i])`
|
||||
`i = i + 1`
|
||||
`end`
|
||||
`if prefix != "HTTP/1.1 " and prefix != "HTTP/1.0 "`
|
||||
`return failure("http.status", "Unsupported HTTP protocol version")`
|
||||
`end`
|
||||
`digits = text.from_codepoint(points[9]) + text.from_codepoint(points[10]) + text.from_codepoint(points[11])`
|
||||
`status = number(digits, 10, 599)`
|
||||
`if status == None or status < 200 or (长度(points) > 12 and points[12] != 32)`
|
||||
`return failure("http.status", "Unsupported HTTP status")`
|
||||
`end`
|
||||
`headers = {}`
|
||||
`remaining = 32`
|
||||
`while remaining > 0`
|
||||
`part = raw_line(cursor)`
|
||||
`if not part.ok`
|
||||
`return part`
|
||||
`end`
|
||||
`cursor = part.value.cursor`
|
||||
`line = part.value.line`
|
||||
`if line == ""`
|
||||
`return framed(cursor, status, headers)`
|
||||
`end`
|
||||
`header = field(line)`
|
||||
`if not header.ok`
|
||||
`return header`
|
||||
`end`
|
||||
`entry = header.value`
|
||||
`if map.has(headers, entry.key) and (entry.key == "content-length" or entry.key == "transfer-encoding")`
|
||||
`return failure("http.framing", "Duplicate HTTP framing header")`
|
||||
`end`
|
||||
`headers = map.set(headers, entry.key, entry.text)`
|
||||
`remaining = remaining - 1`
|
||||
`end`
|
||||
`return failure("http.header_limit", "Too many HTTP headers")`
|
||||
|
||||
## framed
|
||||
|
||||
`params(cursor, status, headers)`
|
||||
`size = map.get(headers, "content-length")`
|
||||
`coding = map.get(headers, "transfer-encoding")`
|
||||
`framing = "close"`
|
||||
`left = 0`
|
||||
`if size != None`
|
||||
`left = number(size, 10, 32768)`
|
||||
`if left == None or coding != None`
|
||||
`return failure("http.framing", "Invalid or ambiguous response length")`
|
||||
`end`
|
||||
`framing = "fixed"`
|
||||
`end`
|
||||
`if coding != None`
|
||||
`if coding != "chunked" and coding != "Chunked"`
|
||||
`return failure("http.framing", "Unsupported Transfer-Encoding")`
|
||||
`end`
|
||||
`framing = "chunked"`
|
||||
`end`
|
||||
`if status == 204 or status == 304`
|
||||
`framing = "fixed"`
|
||||
`left = 0`
|
||||
`end`
|
||||
`stream = {cursor: cursor, framing: framing, left: left, separator: false, done: false, total: 0}`
|
||||
`return {ok: true, value: {status: status, headers: headers, stream: stream}}`
|
||||
|
||||
## next_chunk
|
||||
|
||||
`params(initial)`
|
||||
`stream = initial`
|
||||
`if stream.separator`
|
||||
`separator = raw_line(stream.cursor)`
|
||||
`if not separator.ok`
|
||||
`return separator`
|
||||
`end`
|
||||
`if separator.value.line != ""`
|
||||
`return failure("http.chunked", "Missing CRLF after HTTP chunk")`
|
||||
`end`
|
||||
`stream = map.set(stream, "cursor", separator.value.cursor)`
|
||||
`end`
|
||||
`size = raw_line(stream.cursor)`
|
||||
`if not size.ok`
|
||||
`return size`
|
||||
`end`
|
||||
`digits = ""`
|
||||
`points = text.codepoints(size.value.line)`
|
||||
`i = 0`
|
||||
`while i < 长度(points) and points[i] != 59`
|
||||
`digits = digits + text.from_codepoint(points[i])`
|
||||
`i = i + 1`
|
||||
`end`
|
||||
`count = number(digits, 16, 32768 - stream.total)`
|
||||
`if count == None`
|
||||
`return failure("http.chunked", "Invalid or oversized HTTP chunk")`
|
||||
`end`
|
||||
`stream = map.set(stream, "cursor", size.value.cursor)`
|
||||
`if count > 0`
|
||||
`return {ok: true, value: map.set(map.set(stream, "left", count), "separator", true)}`
|
||||
`end`
|
||||
`remaining = 32`
|
||||
`while remaining > 0`
|
||||
`trailer = raw_line(stream.cursor)`
|
||||
`if not trailer.ok`
|
||||
`return trailer`
|
||||
`end`
|
||||
`stream = map.set(stream, "cursor", trailer.value.cursor)`
|
||||
`if trailer.value.line == ""`
|
||||
`return {ok: true, value: map.set(stream, "done", true)}`
|
||||
`end`
|
||||
`remaining = remaining - 1`
|
||||
`end`
|
||||
`return failure("http.header_limit", "Too many HTTP trailers")`
|
||||
|
||||
## byte
|
||||
|
||||
`params(initial)`
|
||||
`stream = initial`
|
||||
`if stream.framing == "chunked" and stream.left == 0 and not stream.done`
|
||||
`chunk = next_chunk(stream)`
|
||||
`if not chunk.ok`
|
||||
`return chunk`
|
||||
`end`
|
||||
`stream = chunk.value`
|
||||
`end`
|
||||
`if stream.done or (stream.framing == "fixed" and stream.left == 0)`
|
||||
`return {ok: true, value: {byte: None, stream: stream}}`
|
||||
`end`
|
||||
`raw = raw_byte(stream.cursor)`
|
||||
`if not raw.ok`
|
||||
`return raw`
|
||||
`end`
|
||||
`stream = map.set(stream, "cursor", raw.value.cursor)`
|
||||
`b = raw.value.byte`
|
||||
`if b == None and stream.framing != "close"`
|
||||
`return failure("http.eof", "Unexpected EOF in HTTP body")`
|
||||
`end`
|
||||
`if b != None`
|
||||
`if stream.total >= 32768`
|
||||
`return failure("http.body_limit", "Response exceeds 32768 bytes")`
|
||||
`end`
|
||||
`stream = map.set(stream, "total", stream.total + 1)`
|
||||
`if stream.framing != "close"`
|
||||
`stream = map.set(stream, "left", stream.left - 1)`
|
||||
`end`
|
||||
`end`
|
||||
`return {ok: true, value: {byte: b, stream: stream}}`
|
||||
|
||||
## collect
|
||||
|
||||
`params(initial)`
|
||||
`stream = initial`
|
||||
`body = memory.new(1, 1)`
|
||||
`length = 0`
|
||||
`while true`
|
||||
`result = byte(stream)`
|
||||
`if not result.ok`
|
||||
`return result`
|
||||
`end`
|
||||
`stream = result.value.stream`
|
||||
`b = result.value.byte`
|
||||
`if b == None`
|
||||
`return utf8.解码(body, 0, length)`
|
||||
`end`
|
||||
`body[length] = b`
|
||||
`length = length + 1`
|
||||
`end`
|
||||
@@ -0,0 +1,162 @@
|
||||
---
|
||||
import:
|
||||
http: "./index.mq.md"
|
||||
response: "./response.mq.md"
|
||||
utf8: "std:text/utf8"
|
||||
---
|
||||
|
||||
# @exec Server-Sent Events
|
||||
|
||||
## start
|
||||
|
||||
`params(url, method = "GET", body = "")`
|
||||
`opened = http.start(url, method, body, "text/event-stream")`
|
||||
`if not opened.ok`
|
||||
`return opened`
|
||||
`end`
|
||||
`incoming = opened.value`
|
||||
`if incoming.status != 200`
|
||||
`resource.close(incoming.stream.cursor.handle)`
|
||||
`return response.failure("sse.status", "Expected HTTP 200, got " + 文本(incoming.status))`
|
||||
`end`
|
||||
`content_type = map.get(incoming.headers, "content-type")`
|
||||
`if not event_stream(content_type)`
|
||||
`resource.close(incoming.stream.cursor.handle)`
|
||||
`return response.failure("sse.content_type", "Expected text/event-stream")`
|
||||
`end`
|
||||
`return {ok: true, value: {stream: incoming.stream, buffer: memory.new(1, 1), id: ""}}`
|
||||
|
||||
## event_stream
|
||||
|
||||
`params(content_type)`
|
||||
`if content_type == None`
|
||||
`return false`
|
||||
`end`
|
||||
`points = text.codepoints(content_type)`
|
||||
`media = ""`
|
||||
`i = 0`
|
||||
`while i < 长度(points) and points[i] != 59`
|
||||
`p = points[i]`
|
||||
`if p >= 65 and p <= 90`
|
||||
`p = p + 32`
|
||||
`end`
|
||||
`media = media + text.from_codepoint(p)`
|
||||
`i = i + 1`
|
||||
`end`
|
||||
`return media == "text/event-stream"`
|
||||
|
||||
## close
|
||||
|
||||
`params(reader)`
|
||||
`return resource.close(reader.stream.cursor.handle)`
|
||||
|
||||
## next
|
||||
|
||||
Read one complete event and return an updated reader. Carry the last event ID
|
||||
forward. The caller can close the stream after any event.
|
||||
|
||||
`params(reader)`
|
||||
`stream = reader.stream`
|
||||
`event = ""`
|
||||
`data = ""`
|
||||
`has_data = false`
|
||||
`id = reader.id`
|
||||
`remaining = 8192`
|
||||
`while true`
|
||||
`part = read_line(stream, reader.buffer)`
|
||||
`if not part.ok`
|
||||
`return part`
|
||||
`end`
|
||||
`stream = part.value.stream`
|
||||
`line = part.value.line`
|
||||
`if line == None`
|
||||
`return {ok: true, value: {reader: {stream: stream, buffer: reader.buffer, id: id}, event: None}}`
|
||||
`end`
|
||||
`remaining = remaining - part.value.count - 1`
|
||||
`if remaining < 0`
|
||||
`return response.failure("sse.limit", "SSE frame exceeds 8192 bytes")`
|
||||
`end`
|
||||
`if line == ""`
|
||||
`if has_data`
|
||||
`if event == ""`
|
||||
`event = "message"`
|
||||
`end`
|
||||
`return {ok: true, value: {reader: {stream: stream, buffer: reader.buffer, id: id}, event: {kind: event, id: id, data: data}}}`
|
||||
`end`
|
||||
`event = ""`
|
||||
`remaining = 8192`
|
||||
`else`
|
||||
`field = split_field(line)`
|
||||
`if field.name == "event"`
|
||||
`event = field.value`
|
||||
`end`
|
||||
`if field.name == "id" and not field.nul`
|
||||
`id = field.value`
|
||||
`end`
|
||||
`if field.name == "data"`
|
||||
`if has_data`
|
||||
`data = data + "\n"`
|
||||
`end`
|
||||
`data = data + field.value`
|
||||
`has_data = true`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
|
||||
## read_line
|
||||
|
||||
`params(initial, buf)`
|
||||
`stream = initial`
|
||||
`length = 0`
|
||||
`while length <= 4096`
|
||||
`item = response.byte(stream)`
|
||||
`if not item.ok`
|
||||
`return item`
|
||||
`end`
|
||||
`stream = item.value.stream`
|
||||
`b = item.value.byte`
|
||||
`if b == None`
|
||||
`return {ok: true, value: {line: None, stream: stream}}`
|
||||
`end`
|
||||
`if b == 10`
|
||||
`size = length`
|
||||
`if size > 0 and buf[size - 1] == 13`
|
||||
`size = size - 1`
|
||||
`end`
|
||||
`decoded = utf8.解码(buf, 0, size)`
|
||||
`if not decoded.ok`
|
||||
`return decoded`
|
||||
`end`
|
||||
`return {ok: true, value: {line: decoded.value, stream: stream, count: length}}`
|
||||
`end`
|
||||
`buf[length] = b`
|
||||
`length = length + 1`
|
||||
`end`
|
||||
`return response.failure("sse.line_limit", "SSE line exceeds 4096 bytes")`
|
||||
|
||||
## split_field
|
||||
|
||||
`params(line)`
|
||||
`points = text.codepoints(line)`
|
||||
`name = ""`
|
||||
`i = 0`
|
||||
`while i < 长度(points) and points[i] != 58`
|
||||
`name = name + text.from_codepoint(points[i])`
|
||||
`i = i + 1`
|
||||
`end`
|
||||
`if i < 长度(points)`
|
||||
`i = i + 1`
|
||||
`end`
|
||||
`if i < 长度(points) and points[i] == 32`
|
||||
`i = i + 1`
|
||||
`end`
|
||||
`value = ""`
|
||||
`nul = false`
|
||||
`while i < 长度(points)`
|
||||
`if points[i] == 0`
|
||||
`nul = true`
|
||||
`end`
|
||||
`value = value + text.from_codepoint(points[i])`
|
||||
`i = i + 1`
|
||||
`end`
|
||||
`return {name: name, value: value, nul: nul}`
|
||||
+1
-1
@@ -6,7 +6,7 @@ set -euo pipefail
|
||||
here="$(cd "$(dirname "$0")" && pwd)"
|
||||
out="$here/build"
|
||||
mkdir -p "$out"
|
||||
host="$(rustc -vV | sed -n 's/^host: //p')"
|
||||
host="$("$here/../scripts/host-target.sh")"
|
||||
case "$host" in
|
||||
*apple-darwin*) ext="dylib"; flags=(-dynamiclib -fPIC) ;;
|
||||
*windows*) ext="dll"; flags=(-shared) ;;
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ set -euo pipefail
|
||||
here="$(cd "$(dirname "$0")" && pwd)"
|
||||
out="$here/build"
|
||||
mkdir -p "$out"
|
||||
host="$(rustc -vV | sed -n 's/^host: //p')"
|
||||
host="$("$here/../scripts/host-target.sh")"
|
||||
case "$host" in
|
||||
*windows*) echo "unsupported: Windows C ABI provider is not implemented in this fixture" >&2; exit 3 ;;
|
||||
*apple-darwin*) ext="dylib"; flags=(-dynamiclib -fPIC) ;;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build every native fixture for the host target and generate complete
|
||||
# manifests. Requires: cc, git, rustc (for the host triple), python3.
|
||||
# manifests. Requires: cc, git, python3 (Linux x86_64 glibc).
|
||||
set -euo pipefail
|
||||
here="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
"$here/plugin/build.sh"
|
||||
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
# The supported lane builds public C ABI fixtures without a Rust toolchain.
|
||||
set -euo pipefail
|
||||
case "$(uname -s):$(uname -m)" in
|
||||
Linux:x86_64)
|
||||
getconf GNU_LIBC_VERSION >/dev/null
|
||||
printf '%s\n' x86_64-unknown-linux-gnu
|
||||
;;
|
||||
*)
|
||||
# Preserve the original host-triple discovery for experimental lanes.
|
||||
rustc -vV | sed -n 's/^host: //p'
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,325 @@
|
||||
"""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)
|
||||
@@ -26,6 +26,8 @@ import tempfile
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from reference_apps import CASES as REFERENCE_CASES
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
EVIDENCE = ROOT / "evidence"
|
||||
RESULTS = EVIDENCE / "results.json"
|
||||
@@ -56,6 +58,8 @@ class Runner:
|
||||
self.cli = cli
|
||||
self.cases: list[Case] = []
|
||||
self.cli_hash = sha256_file(cli)
|
||||
self.provider_worker = cli.with_name("marqdo-provider-worker")
|
||||
self.provider_worker_hash = sha256_file(self.provider_worker) if self.provider_worker.is_file() else None
|
||||
self.tool_sha = git_sha(ROOT)
|
||||
self.env = dict(os.environ)
|
||||
self.env["MARQDO_BIN"] = str(cli)
|
||||
@@ -507,6 +511,18 @@ class Runner:
|
||||
finally:
|
||||
shutil.rmtree(workspace, ignore_errors=True)
|
||||
|
||||
def check_reference_apps(self) -> None:
|
||||
for name, check in REFERENCE_CASES.items():
|
||||
case = self.case("reference_applications", name)
|
||||
try:
|
||||
check(self.cli)
|
||||
except Exception as error:
|
||||
case.status = "FAIL"
|
||||
case.detail = str(error)
|
||||
else:
|
||||
case.status = "PASS"
|
||||
case.detail = "frozen CLI loopback check"
|
||||
|
||||
# -- utilities -------------------------------------------------------
|
||||
@staticmethod
|
||||
def read_yaml_artifact(manifest: Path) -> str:
|
||||
@@ -526,6 +542,14 @@ class Runner:
|
||||
case = self.case("negative_security", "frozen CLI binary did not change")
|
||||
case.status = "PASS"
|
||||
case.detail = f"sha256 {self.cli_hash}"
|
||||
if self.provider_worker_hash is not None:
|
||||
worker = self.case("negative_security", "frozen provider worker did not change")
|
||||
if self.provider_worker.is_file() and sha256_file(self.provider_worker) == self.provider_worker_hash:
|
||||
worker.status = "PASS"
|
||||
worker.detail = f"sha256 {self.provider_worker_hash}"
|
||||
else:
|
||||
worker.status = "FAIL"
|
||||
worker.detail = "provider worker digest changed"
|
||||
results: dict[str, str] = {}
|
||||
for category in CATEGORIES:
|
||||
cases = [item for item in self.cases if item.category == category]
|
||||
@@ -561,6 +585,11 @@ class Runner:
|
||||
for item in self.cases
|
||||
],
|
||||
}
|
||||
if self.provider_worker_hash is not None:
|
||||
payload["provider_worker_sha256"] = self.provider_worker_hash
|
||||
payload["reference_applications"] = {
|
||||
case.name: case.status for case in self.cases if case.category == "reference_applications"
|
||||
}
|
||||
EVIDENCE.mkdir(exist_ok=True)
|
||||
RESULTS.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n")
|
||||
failures = [item for item in self.cases if item.status == "FAIL"]
|
||||
@@ -633,6 +662,7 @@ def main() -> int:
|
||||
runner.check_provider()
|
||||
runner.check_tool()
|
||||
runner.check_package()
|
||||
runner.check_reference_apps()
|
||||
return runner.report()
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user