test: exercise external HTTP and live SSE on the frozen CLI

This commit is contained in:
Marqdo Extension Fixtures committed 2026-11-22 20:33:32 +08:00
1 parent e22ec95b09
commit 943f3b5275
8 files changed
+960

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
/marqdo.lock
/.marqdo/
+25
View File
@@ -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
```
+39
View File
@@ -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}`
+144
View File
@@ -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`
+5
View File
@@ -0,0 +1,5 @@
project:
name: marqdo-net
version: 0.1.0
marqdo: ">=3.0.0-beta.1,<4.0.0"
dependencies: {}
+307
View File
@@ -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`
+162
View File
@@ -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}`
+276
View File
@@ -0,0 +1,276 @@
"""Exercise the pure Marqdo network package against one frozen CLI."""
from __future__ import annotations
import base64
import json
import os
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):
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:
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
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,
}
if __name__ == "__main__":
cli = Path(os.environ["MARQDO_BIN"]).resolve()
for name, check in CASES.items():
check(cli)
print(f"PASS: {name}", flush=True)