feat(PR-04): SSE execution loop, 7-route server and session security

- replace src/server.rs with src/server/{mod,routes,security,sse}.rs implementing
  exactly the RFC-0002 §6.2 routes: GET /, GET /file, GET /assets, GET
  /api/documents, POST /api/runs, GET /api/runs/{id}/events, POST
  /api/runs/{id}/cancel; old /api/health, /api/document, /api/run and
  /api/clear-run are gone (404)
- SSE writes the event-stream directly to the socket and flushes every frame and
  heartbeat (tiny_http's chunked writer would delay frames); Last-Event-ID
  replay or authoritative snapshot, 128-event ring, terminal close, heartbeat
  comments, at most two observers per run, no polling route
- per-session HttpOnly SameSite=Strict cookie + X-View-CSRF, exact same-origin
  Origin, loopback Host, Sec-Fetch-Site cross-site rejection, JSON-only 64 KiB
  run POSTs; cancel is an authenticated bodyless control POST
- reader.js: Analysis-driven function form with text-only command preview,
  pure/project mode + explicit fs grants with second confirmation, one POST then
  EventSource, cancel, live result/stdout/stderr/Trace panel and keyed source
  anchors (skipped when stale); no innerHTML of CLI data and no status polling
- render: hidden live run shell, generic explicit-run dialog, function call
  buttons carrying Analysis function ids/params, data-analysis-digest/document
  attributes; remove the old run-confirm dialog and run-page reload path
- add tests/security/ suite, rewrite HTTP/SSE integration tests, update browser
  suite for EventSource/dark theme/RFC width matrix (incl. 2048x1133)
- ADR-0009 + docs/evidence/PR-04 with real Chromium log/screenshots and a real
  frozen-CLI SSE run (285 Trace v2 events, CLI SHA unchanged)
- unit 63 + contract 41 + integration 40 + security 11 pass; clippy clean
This commit is contained in:
cflmy committed 2026-11-22 14:30:40 +08:00
1 parent e13c1828a4
commit 046834bcb6
35 files changed
+3812 -1963

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""Explicit real-run acceptance over the frozen CLI + Live SSE server.
Usage: python3 scripts/acceptance-run.py http://127.0.0.1:PORT/
Prints a PASS line and exits non-zero on any failure. Never polls: it creates
one run, observes one SSE stream until the single terminal event, and asserts
the verified Trace binding.
"""
import http.cookiejar
import json
import re
import sys
import urllib.request
url = sys.argv[1]
origin = url.rstrip("/")
jar = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
def get(path):
with opener.open(origin + path, timeout=30) as response:
return response.read().decode("utf-8")
page = get("/")
csrf = re.search(r'name="mq-csrf-token" content="([0-9a-f]+)"', page)
assert csrf, "csrf token missing"
digest = re.search(r'data-analysis-digest="(sha256:[0-9a-f]{64})"', page)
assert digest, "analysis digest missing"
body = json.dumps({
"document": "index.mq.md",
"target": {"kind": "entry"},
"parameters": [],
"analysis_digest": digest.group(1),
"mode": "pure",
"grants": {"read": [], "write": []},
"client_request_id": "acceptance-real-run-1",
}).encode()
request = urllib.request.Request(
origin + "/api/runs",
data=body,
headers={
"Content-Type": "application/json",
"Origin": origin,
"X-View-CSRF": csrf.group(1),
},
method="POST",
)
with opener.open(request, timeout=60) as response:
assert response.status == 202, response.status
accepted = json.loads(response.read().decode("utf-8"))
assert accepted["state"] == "accepted", accepted
events_url = origin + accepted["events_url"]
terminal = None
with opener.open(events_url, timeout=120) as stream:
data_lines = []
for raw in stream:
line = raw.decode("utf-8").rstrip("\n")
if line.startswith("data: "):
data_lines.append(line[6:])
elif line == "" and data_lines:
event = json.loads("\n".join(data_lines))
data_lines = []
if event.get("state") in (
"succeeded",
"failed",
"cancelled",
"timed_out",
"unavailable",
):
terminal = event
break
assert terminal is not None, "no terminal SSE event"
assert terminal["state"] == "succeeded", terminal
assert terminal["result"]["success"] is True, terminal["result"]
assert terminal["trace"]["status"] == "verified", terminal.get("trace")
print(
"explicit real run: PASS (run_id=%s events=%d)"
% (accepted["run_id"], len(terminal["trace"]["events"]))
)
+2 -34
View File
@@ -85,7 +85,7 @@ for _ in $(seq 1 100); do
[[ -n "$browse_url" ]] && break
sleep 0.1
done
if [[ -n "$browse_url" ]] && curl -sf "${browse_url}api/health" | grep -q '"ok": true'; then
if [[ -n "$browse_url" ]] && curl -sf "${browse_url}api/documents" | grep -q '"schema": "marqdo.view-documents"'; then
record browse PASS
else
record browse FAIL
@@ -108,39 +108,7 @@ for _ in $(seq 1 100); do
sleep 0.1
done
if [[ -n "$run_url" ]]; then
if python3 - "$run_url" <<'PY'
import json
import re
import sys
import urllib.request
url = sys.argv[1]
def get(path):
with urllib.request.urlopen(url.rstrip("/") + path, timeout=30) as response:
return response.read().decode("utf-8")
page = get("/")
match = re.search(r'name="mq-csrf-token" content="([0-9a-f]+)"', page)
assert match, "csrf token missing"
token = match.group(1)
body = json.dumps({"path": "index.mq.md", "mode": "pure", "confirm": True}).encode()
request = urllib.request.Request(
url.rstrip("/") + "/api/run",
data=body,
headers={"Content-Type": "application/json", "X-MQ-CSRF": token},
method="POST",
)
with urllib.request.urlopen(request, timeout=120) as response:
result = json.loads(response.read().decode("utf-8"))
assert result["ok"] is True, result
assert result["state"] == "succeeded", result
run_page = get(result["redirect"])
assert 'id="mq-run-panel"' in run_page, "run panel missing"
assert 'data-run-state="succeeded"' in run_page, "succeeded state missing"
assert "mq-run-chip" in run_page, "trace chips missing"
print("explicit real run: PASS (state=%s events=%s)" % (result["state"], result["events"]))
PY
if python3 "$repo_root/scripts/acceptance-run.py" "$run_url"
then
record real_run PASS
else
+3 -5
View File
@@ -8,11 +8,9 @@ set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"
cargo test --locked --test http_live
cargo test --locked --test rendering
cargo test --locked --test export
cargo test --locked --test no_coupling
cargo test --locked --test asset_integrity
cargo test --locked --test security
cargo test --locked --test integration
cargo test --locked --test contract
if [[ -n "${MARQDO_FROZEN_BIN:-}" ]]; then
MARQDO_BIN="$MARQDO_FROZEN_BIN" ./scripts/test-export.sh