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:
1 parent
e13c1828a4
commit
046834bcb6
35 files changed
+3812
-1963
No files matched your search
@@ -6,6 +6,30 @@ Protocol axes (Tool v1, Analysis v2, Trace v2) are versioned separately.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added (RFC-VIEW-0002 PR-04)
|
||||
|
||||
- `src/server/{mod,routes,security,sse}.rs`: the fixed 7-route Live API with one
|
||||
explicit execution entry. Removed `/api/health`, `/api/document`,
|
||||
`/api/run` and `/api/clear-run`.
|
||||
- SSE transport writes the `text/event-stream` response directly to the socket
|
||||
and flushes every frame/heartbeat (tiny_http's chunked writer would delay
|
||||
frames); heartbeats, `Last-Event-ID` replay, authoritative snapshots, 128-event
|
||||
ring, terminal close and a max of two observers per run.
|
||||
- Per-session `HttpOnly; SameSite=Strict` cookie + per-session CSRF token
|
||||
(`X-View-CSRF`), exact same-origin `Origin`, loopback `Host` validation,
|
||||
`Sec-Fetch-Site` cross-site rejection, JSON-only bounded run POSTs (64 KiB).
|
||||
- Reader front-end now runs through one POST + EventSource: target form built
|
||||
from Analysis signatures, text-only command preview, pure/project mode with
|
||||
explicit fs read/write globs and second confirmation, cancel button, live
|
||||
result/stdout/stderr/Trace panel, keyed source anchors (skipped when stale),
|
||||
and no status polling. Run shell is hidden until an explicit run.
|
||||
- New `tests/security/` suite (cookies/CSRF/CORS/symlink/Markdown/SSE session
|
||||
isolation) and rewritten HTTP/SSE integration tests; browser suite updated for
|
||||
EventSource, dark theme and the RFC width matrix (incl. 2048x1133).
|
||||
- ADR-0009 records the SSE transport, session model and route decisions; evidence
|
||||
in `docs/evidence/PR-04/` includes real Chromium logs/screenshots and a real
|
||||
frozen-CLI run (285 Trace v2 events).
|
||||
|
||||
### Added (RFC-VIEW-0002 PR-03)
|
||||
|
||||
- Execution layer: `src/execution/{request,process,controller,events}.rs`.
|
||||
|
||||
+4
-4
@@ -29,13 +29,13 @@ Beta 版 CLI 必须使用 prerelease 范围(`>=3.0.0-beta.1,<4.0.0`);`>=3.
|
||||
| Analysis v2 静态语义(函数/Unit/诊断/引用/资源) | **已实现**(PR-02) |
|
||||
| 文档态 / 源码态切换 | **已实现**(PR-02) |
|
||||
| 暖纸 Reader 视觉(单一 CSS/JS) | 计划 PR-03 |
|
||||
| 用户显式触发运行 + Trace v2 事件可视化 | **已实现**(PR-04,仅 `pure` 模式,需页面内确认 + CSRF) |
|
||||
| Live 本机安全 API | **已实现**(PR-02 只读 + PR-04 run + PR-05 并发/公开错误/导出) |
|
||||
| 用户显式触发运行 + SSE + Trace v2 事件可视化 | **已实现**(0002 PR-04;`pure`/受控 `project`,显式确认 + 会话 CSRF) |
|
||||
| Live 本机安全 API(7 路由) | **已实现**(0002 PR-04;Cookie/CSRF/Origin/CSP/单任务/SSE) |
|
||||
| 静态离线导出(纯只读) | **已实现**(PR-05,同一渲染器) |
|
||||
| 逐语句变量值 / 参数实际值 / 内存快照 | **UNSUPPORTED**(Trace v2 不提供,绝不伪造) |
|
||||
| 知识“已证明”状态 | **UNSUPPORTED**(需要独立 Prove 协议与证书) |
|
||||
| `project`/`strict` 运行与 grants 授权 | **未实现**(首版仅 `pure`;0002 的受控 project grants 在 PR-03/04) |
|
||||
| SSE 状态推送 / 取消运行 / 事件重放 | **未实现**(RFC-VIEW-0002 PR-04 阻塞项;当前运行后整页重载) |
|
||||
| `project` 运行与 fs grants | **已实现(受控)**:仅相对项目根 read/write glob,显式二次确认;其它权限拒绝 |
|
||||
| SSE 状态推送 / 取消运行 / 事件重放 | **已实现**(逐帧 flush、心跳、Last-Event-ID、2 连接上限、无轮询) |
|
||||
| SVG 曲线侧注 | **未实现**(运行事件用内联 keyed chip,U-04 PARTIAL) |
|
||||
| 调试器/断点/单步 | **不实现**(首版非目标) |
|
||||
| Knowledge/Prove/Lint 引擎 | **不实现**(独立仓库/未来可选信息层) |
|
||||
|
||||
@@ -18,6 +18,10 @@ path = "src/main.rs"
|
||||
name = "contract"
|
||||
path = "tests/contract/main.rs"
|
||||
|
||||
[[test]]
|
||||
name = "security"
|
||||
path = "tests/security/main.rs"
|
||||
|
||||
[[test]]
|
||||
name = "integration"
|
||||
path = "tests/integration/main.rs"
|
||||
|
||||
@@ -22,11 +22,11 @@ Marqdo View(`0.2.0`)是一个独立的可执行文档阅读器:以**原始
|
||||
|---|---|
|
||||
| 原始 Markdown + GFM 阅读、源码态、文档态 | ✅ |
|
||||
| Analysis v2 静态语义(函数/Unit/签名/诊断/导入/引用/资源) | ✅ 严格校验,span 无效则降级 |
|
||||
| 本机 Live 阅读(默认 `127.0.0.1`,只读 API) | ✅ |
|
||||
| 用户确认后运行 + 真实 Trace v2 可视化(`pure` 模式) | ✅(0001 同步模型;0002 的 SSE 异步闭环开发中) |
|
||||
| 本机 Live 阅读(默认 `127.0.0.1`,只读 API + 显式执行端点) | ✅ |
|
||||
| 显式确认后运行 + SSE 状态/取消 + 真实 Trace v2 | ✅ 单任务、无轮询、断线重放 |
|
||||
| 纯只读静态导出(离线 `file://`、manifest/哈希、原子发布) | ✅ |
|
||||
| 单函数参数表单 + 受控 `project` fs grants | 🚧 RFC-VIEW-0002 PR-03/04 |
|
||||
| SSE 状态推送 / 取消 / 断线重放(禁止轮询) | 🚧 RFC-VIEW-0002 PR-04(MVP 阻塞项) |
|
||||
| 单函数参数表单 + 受控 `project` fs grants | ✅ 参数来自 Analysis 签名;project 需显式 glob 二次确认 |
|
||||
| SSE 状态推送 / 取消 / 断线重放(禁止轮询) | ✅ `POST /api/runs` + `GET …/events` + `POST …/cancel` |
|
||||
| 逐语句变量值 / 参数值 / 内存快照 | ❌ UNSUPPORTED(协议不提供,绝不伪造) |
|
||||
| 知识“已证明” / Prove / Lint / 调试器 | ❌ 非目标/等待独立协议 |
|
||||
|
||||
@@ -62,9 +62,11 @@ marqdo view export examples/welcome --out ./site
|
||||
marqdo view export examples/mixed-modes --out ./site --no-annotations
|
||||
```
|
||||
|
||||
开发期可直接运行 `marqdo-view`(用 `--marqdo-bin` 指定冻结核心)。运行入口在 Live
|
||||
页面中:点击“运行”→ 阅读风险说明 → 点击“确认运行”,才会调用冻结核心执行
|
||||
`--mode pure`;页面刷新/打开/搜索/导出都不会运行。
|
||||
开发期可直接运行 `marqdo-view`(用 `--marqdo-bin` 指定冻结核心)。运行只有一个入口:
|
||||
Live 页面点击 Dock “运行”(执行 `main`)或函数面板的“调用”(执行 `call`),
|
||||
阅读命令预览与权限说明后点击“确认执行”,服务端才 `POST /api/runs` 启动一个
|
||||
CLI 子进程;状态与结果通过 SSE 推送,可取消,断线可重放。页面刷新/打开/搜索/
|
||||
切换/导出都不会运行,也没有状态轮询。
|
||||
|
||||
## 架构(强制约束)
|
||||
|
||||
@@ -75,21 +77,25 @@ Reader UI(唯一 assets/reader.css + assets/reader.js)
|
||||
│
|
||||
ReaderRenderer(唯一模板,Live/Export 共用)
|
||||
│
|
||||
PresentationModel(DocumentModel / SemanticProjection / RunProjection)
|
||||
PresentationModel(reader::assemble / reader::model)
|
||||
│
|
||||
PublicCoreClient ─ MARQDO_BIN 子进程 + 公开 JSON(check --emit / run --trace-file)
|
||||
CoreClient ─ MARQDO_BIN 子进程 + 公开 JSON(check --emit / run/call --trace-file)
|
||||
│
|
||||
ExecutionController ─ 单任务、取消、SSE 事件(仅 POST /api/runs 可达)
|
||||
│
|
||||
冻结发布版 marqdo CLI(不修改、不重编译、不链接、不读源码)
|
||||
```
|
||||
|
||||
- 单一 Rust package、单一渲染入口、单一主题文件;没有第二个 Markdown→语义管线。
|
||||
- 服务端只有 7 条固定路由;SSE 只推送 View 自有 `run.*` 生命周期事件。
|
||||
- Analysis v2 是唯一语义权威:函数/语句/分支/循环/诊断均来自 `check --emit`,
|
||||
源码字节 span 只用于绑定视觉位置。
|
||||
- Trace v2 与 Analysis 字节摘要严格绑定;`STALE/TRUNCATED/FAILED/UNSUPPORTED`
|
||||
状态显式呈现,不猜测未公开值。
|
||||
- Live/Export 内容同源;导出绝不执行、绝不覆盖项目源文件或无关目录。
|
||||
- 门禁:`tests/contract/no_coupling.rs` 拒绝旧 crate/源码依赖、第二套渲染器/主题、shell 执行;
|
||||
`tests/contract/asset_integrity.rs` 锁定内嵌资产与唯一主题层。
|
||||
`tests/contract/asset_integrity.rs` 锁定内嵌资产与唯一主题层;
|
||||
`tests/security/` 覆盖 CSRF/Origin/Cookie/路径/symlink/XSS/跨会话 SSE。
|
||||
|
||||
## 开发与验收
|
||||
|
||||
@@ -122,15 +128,11 @@ MARQDO_BIN=... ./scripts/test-browser.sh # 真实 Chromium 视觉/交互/响
|
||||
|
||||
## 已知限制(诚实状态)
|
||||
|
||||
- 首版运行只支持 `--mode pure`;`project`/`strict` 及 grants 授权界面未实现。
|
||||
- 运行完成后整页重载并保留阅读位置;无 SSE 流式输出/取消/多运行历史。
|
||||
- 变量实际值、参数值、内存快照、知识证明状态不在 Trace v2 中,UI 一律标 UNSUPPORTED。
|
||||
- 平台仅 Linux x86_64 glibc 正式验证;macOS/Windows 未验证。
|
||||
- 视觉自动化门禁 PASS,但参考截图的像素级人工比对仍未执行(`U-01 UNVERIFIED`);
|
||||
SVG 曲线侧注未实现,运行事件以可访问的内联 chip 呈现(`U-04 PARTIAL`)。
|
||||
- 远端正 CI 未实际运行;`.woodpecker.yml` 已提供,本地验收证据完整。
|
||||
|
||||
## 许可
|
||||
|
||||
代码按 MIT / Apache-2.0 双许可发布(`LICENSE-MIT`、`LICENSE-APACHE`)。复用的旧
|
||||
View 视觉资产(Apache-2.0)来源与哈希见 `assets/licenses/ASSETS.md`。
|
||||
- 运行仅 `pure`(默认)与受控 `project` fs read/write;`strict`、网络/进程/环境/
|
||||
plugin/provider/kernel 授权不在首版 UI,必须使用终端 CLI。
|
||||
- `project` 不是 OS 沙箱;View 不继承 `marqdo.yaml` 的 capability 请求。
|
||||
- SSE 只推送 View 生命周期与终态数据,不承诺逐字 stdout/Token 流;Trace v2 不含
|
||||
参数实际值/逐语句变量/内存快照。
|
||||
- 平台:仅 Linux x86_64 正式验证;Windows/macOS 不支持声明。
|
||||
- 像素级人工视觉比对与完整 screen-reader 走查为 `UNVERIFIED`(自动化几何/响应式/
|
||||
无外部资源/无 JS/打印证据见 `docs/evidence/PR-04/`)。
|
||||
@@ -1281,3 +1281,92 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@layer interactions {
|
||||
.mq-fn-call {
|
||||
margin-left: 10px;
|
||||
padding: 2px 10px;
|
||||
border: 1px solid var(--mq-gold);
|
||||
border-radius: 999px;
|
||||
background: transparent;
|
||||
color: var(--mq-gold);
|
||||
font: 12px/1.6 var(--mq-sans);
|
||||
cursor: pointer;
|
||||
}
|
||||
.mq-fn-call:hover {
|
||||
background: var(--mq-gold-soft);
|
||||
color: var(--mq-strong);
|
||||
}
|
||||
.mq-run-target {
|
||||
margin: 4px 0 12px;
|
||||
font: 13px/1.6 var(--mq-sans);
|
||||
color: var(--mq-muted);
|
||||
}
|
||||
.mq-run-status {
|
||||
font: 13px/1.6 var(--mq-sans);
|
||||
color: var(--mq-ink);
|
||||
}
|
||||
.mq-run-params {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
margin: 12px 0;
|
||||
}
|
||||
.mq-run-param {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font: 12px/1.5 var(--mq-sans);
|
||||
color: var(--mq-muted);
|
||||
}
|
||||
.mq-run-param input {
|
||||
padding: 7px 10px;
|
||||
border: 1px solid var(--mq-line-strong);
|
||||
border-radius: 8px;
|
||||
background: var(--mq-paper);
|
||||
color: var(--mq-ink);
|
||||
font: 13px/1.5 var(--mq-mono);
|
||||
}
|
||||
.mq-run-mode {
|
||||
margin: 12px 0;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--mq-line);
|
||||
border-radius: 10px;
|
||||
font: 12px/1.6 var(--mq-sans);
|
||||
}
|
||||
.mq-run-mode legend {
|
||||
padding: 0 6px;
|
||||
color: var(--mq-muted);
|
||||
}
|
||||
.mq-run-mode label {
|
||||
display: block;
|
||||
margin: 4px 0;
|
||||
}
|
||||
.mq-run-grants {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
margin: 10px 0;
|
||||
font: 12px/1.6 var(--mq-sans);
|
||||
}
|
||||
.mq-run-grants textarea {
|
||||
width: 100%;
|
||||
margin-top: 4px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--mq-line-strong);
|
||||
border-radius: 8px;
|
||||
background: var(--mq-paper);
|
||||
color: var(--mq-ink);
|
||||
font: 12px/1.5 var(--mq-mono);
|
||||
resize: vertical;
|
||||
}
|
||||
.mq-run-command {
|
||||
margin: 8px 0 12px;
|
||||
padding: 10px 12px;
|
||||
overflow-x: auto;
|
||||
border: 1px dashed var(--mq-line-strong);
|
||||
border-radius: 8px;
|
||||
background: var(--mq-surface-2);
|
||||
font: 12px/1.6 var(--mq-mono);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
}
|
||||
+512
-81
@@ -252,7 +252,7 @@
|
||||
openDialog("mq-dialog-unsupported");
|
||||
}
|
||||
|
||||
function handleAction(action) {
|
||||
function handleAction(action, trigger) {
|
||||
switch (action) {
|
||||
case "mode-document":
|
||||
setMode("document");
|
||||
@@ -302,25 +302,33 @@
|
||||
openDialog("mq-dialog-about");
|
||||
break;
|
||||
case "run":
|
||||
if (reader.dataset.runAvailable === "true") {
|
||||
openDialog("mq-dialog-run-confirm");
|
||||
} else {
|
||||
showUnsupported(
|
||||
"运行文档",
|
||||
"当前页面没有可用的冻结核心或可执行入口;View 不会在缺少确认的情况下执行任何文档。"
|
||||
);
|
||||
}
|
||||
openRunForMain();
|
||||
break;
|
||||
case "run-confirm":
|
||||
confirmRun();
|
||||
submitRun();
|
||||
break;
|
||||
case "cancel-run":
|
||||
cancelRun();
|
||||
break;
|
||||
case "call-function":
|
||||
if (trigger) {
|
||||
var params = [];
|
||||
try {
|
||||
params = JSON.parse(trigger.dataset.params || "[]");
|
||||
} catch (error) {
|
||||
params = [];
|
||||
}
|
||||
openRunForm({
|
||||
kind: "function",
|
||||
functionId: trigger.dataset.functionId,
|
||||
label: trigger.dataset.functionLabel,
|
||||
params: params
|
||||
});
|
||||
}
|
||||
break;
|
||||
case "clear-run":
|
||||
clearRun();
|
||||
break;
|
||||
case "clear":
|
||||
var panel = $("#mq-run-panel");
|
||||
if (panel) panel.hidden = true;
|
||||
toast("已清理本地展示状态(源文件与缓存未修改)");
|
||||
clearRun();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
@@ -332,93 +340,522 @@
|
||||
return meta ? meta.getAttribute("content") : "";
|
||||
}
|
||||
|
||||
function setRunBusy(busy) {
|
||||
var button = document.querySelector('.mq-dock-btn[data-action="run"]');
|
||||
if (!button) return;
|
||||
if (busy) {
|
||||
button.setAttribute("aria-busy", "true");
|
||||
button.dataset.busy = "true";
|
||||
button.disabled = true;
|
||||
reader.dataset.runState = "running";
|
||||
var activeRun = null;
|
||||
var pendingRun = null;
|
||||
|
||||
function randomId() {
|
||||
var bytes = new Uint8Array(16);
|
||||
if (window.crypto && window.crypto.getRandomValues) {
|
||||
window.crypto.getRandomValues(bytes);
|
||||
} else {
|
||||
button.removeAttribute("aria-busy");
|
||||
delete button.dataset.busy;
|
||||
button.disabled = false;
|
||||
for (var i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256);
|
||||
}
|
||||
var out = "";
|
||||
for (var j = 0; j < bytes.length; j += 1) {
|
||||
out += (bytes[j] < 16 ? "0" : "") + bytes[j].toString(16);
|
||||
}
|
||||
return "req-" + out;
|
||||
}
|
||||
|
||||
function csrfToken() {
|
||||
var meta = document.querySelector('meta[name="mq-csrf-token"]');
|
||||
return meta ? meta.getAttribute("content") : "";
|
||||
}
|
||||
|
||||
function stateLabel(state) {
|
||||
switch (state) {
|
||||
case "accepted": return "已接受";
|
||||
case "running": return "运行中";
|
||||
case "cancel_requested": return "正在取消";
|
||||
case "succeeded": return "成功";
|
||||
case "failed": return "失败";
|
||||
case "cancelled": return "已取消";
|
||||
case "timed_out": return "超时";
|
||||
case "unavailable": return "不可用";
|
||||
default: return String(state || "未知");
|
||||
}
|
||||
}
|
||||
|
||||
function confirmRun() {
|
||||
var dialog = $("#mq-dialog-run-confirm");
|
||||
var path = dialog ? dialog.dataset.path : "";
|
||||
var token = csrfToken();
|
||||
if (!path || !token) {
|
||||
toast("缺少运行上下文或 CSRF 令牌,已拒绝运行");
|
||||
function isTerminalState(state) {
|
||||
return ["succeeded", "failed", "cancelled", "timed_out", "unavailable"].indexOf(state) >= 0;
|
||||
}
|
||||
|
||||
function runPanel() {
|
||||
return $("#mq-run-panel");
|
||||
}
|
||||
|
||||
function setRunStatus(text) {
|
||||
var status = $("#mq-run-status");
|
||||
if (status) status.textContent = text;
|
||||
}
|
||||
|
||||
function showRunPanel() {
|
||||
var panel = runPanel();
|
||||
if (panel) panel.hidden = false;
|
||||
}
|
||||
|
||||
function setRunBusy(busy) {
|
||||
var button = document.querySelector('.mq-dock-btn[data-action="run"]');
|
||||
if (button) {
|
||||
if (busy) {
|
||||
button.setAttribute("aria-busy", "true");
|
||||
button.dataset.busy = "true";
|
||||
button.disabled = true;
|
||||
reader.dataset.runState = "running";
|
||||
} else {
|
||||
button.removeAttribute("aria-busy");
|
||||
delete button.dataset.busy;
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
var cancel = $("#mq-run-actions");
|
||||
if (cancel) cancel.hidden = !busy;
|
||||
}
|
||||
|
||||
function appendLine(container, tag, className, text) {
|
||||
var node = document.createElement(tag);
|
||||
if (className) node.className = className;
|
||||
node.textContent = text;
|
||||
container.appendChild(node);
|
||||
return node;
|
||||
}
|
||||
|
||||
function clearRunOutput() {
|
||||
["#mq-run-summary", "#mq-run-stdout", "#mq-run-stderr", "#mq-run-events"].forEach(function (selector) {
|
||||
var node = $(selector);
|
||||
if (node) node.textContent = "";
|
||||
});
|
||||
var stdout = $("#mq-run-stdout");
|
||||
if (stdout) stdout.hidden = true;
|
||||
var stderr = $("#mq-run-stderr");
|
||||
if (stderr) stderr.hidden = true;
|
||||
var traceWrap = $("#mq-run-trace-wrap");
|
||||
if (traceWrap) traceWrap.hidden = true;
|
||||
$$(".mq-run-chip[data-view-chip]").forEach(function (chip) {
|
||||
chip.remove();
|
||||
});
|
||||
}
|
||||
|
||||
function closeActiveObserver() {
|
||||
if (activeRun && activeRun.source) {
|
||||
try {
|
||||
activeRun.source.close();
|
||||
} catch (error) {
|
||||
/* optional */
|
||||
}
|
||||
activeRun.source = null;
|
||||
}
|
||||
}
|
||||
|
||||
function selectedMode() {
|
||||
var checked = document.querySelector('input[name="mq-mode"]:checked');
|
||||
return checked ? checked.value : "pure";
|
||||
}
|
||||
|
||||
function grantList(id) {
|
||||
var field = document.getElementById(id);
|
||||
if (!field) return [];
|
||||
return field.value
|
||||
.split("\n")
|
||||
.map(function (line) { return line.trim(); })
|
||||
.filter(function (line) { return line.length > 0; });
|
||||
}
|
||||
|
||||
function rawParams() {
|
||||
var out = [];
|
||||
$$("#mq-run-params [data-param-name]").forEach(function (input) {
|
||||
out.push({ name: input.dataset.paramName, expression: input.value, required: input.dataset.required === "true" });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
function updateRunPreview() {
|
||||
var preview = $("#mq-run-command");
|
||||
if (!preview || !pendingRun) return;
|
||||
var mode = selectedMode();
|
||||
var parts = [];
|
||||
if (pendingRun.kind === "entry") {
|
||||
parts = ["marqdo", "run", reader.dataset.document, "--mode", mode, "--json", "--trace-file", "<临时文件>"];
|
||||
} else {
|
||||
parts = ["marqdo", "call", reader.dataset.document, "<函数 " + pendingRun.label + ">", "--mode", mode, "--json", "--trace-file", "<临时文件>"];
|
||||
rawParams().forEach(function (param) {
|
||||
parts.push("--arg");
|
||||
parts.push(param.name + "=" + (param.expression || "<常量表达式>"));
|
||||
});
|
||||
}
|
||||
if (mode === "project") {
|
||||
grantList("mq-grant-read").forEach(function (glob) { parts.push("--allow-read"); parts.push(glob); });
|
||||
grantList("mq-grant-write").forEach(function (glob) { parts.push("--allow-write"); parts.push(glob); });
|
||||
}
|
||||
preview.textContent = parts.join(" ");
|
||||
var modeLabel = $("#mq-run-target-mode");
|
||||
if (modeLabel) modeLabel.textContent = mode;
|
||||
}
|
||||
|
||||
function renderRunParams(params) {
|
||||
var container = $("#mq-run-params");
|
||||
if (!container) return;
|
||||
container.textContent = "";
|
||||
if (!params.length) {
|
||||
appendLine(container, "p", "mq-colophon", "该目标没有参数。");
|
||||
return;
|
||||
}
|
||||
params.forEach(function (param) {
|
||||
var label = document.createElement("label");
|
||||
label.className = "mq-run-param";
|
||||
var title = document.createElement("span");
|
||||
var type = param.type ? ": " + param.type : "";
|
||||
var required = param.required ? "(必填)" : "(可选)";
|
||||
title.textContent = param.name + type + " " + required;
|
||||
var input = document.createElement("input");
|
||||
input.type = "text";
|
||||
input.dataset.paramName = param.name;
|
||||
input.dataset.required = param.required ? "true" : "false";
|
||||
input.spellcheck = false;
|
||||
input.placeholder = param.default ? "默认常量:" + param.default : "常量表达式,例如 5 或 \"text\"";
|
||||
if (param.required) input.setAttribute("aria-required", "true");
|
||||
input.addEventListener("input", updateRunPreview);
|
||||
label.appendChild(title);
|
||||
label.appendChild(input);
|
||||
container.appendChild(label);
|
||||
});
|
||||
}
|
||||
|
||||
function openRunForm(target) {
|
||||
var dialog = $("#mq-dialog-run");
|
||||
if (!dialog) {
|
||||
toast("当前页面没有可用的运行表单;请确认已安装冻结核心");
|
||||
return;
|
||||
}
|
||||
pendingRun = {
|
||||
kind: target.kind,
|
||||
functionId: target.functionId || "",
|
||||
label: target.label || "入口 main",
|
||||
clientRequestId: randomId(),
|
||||
params: target.params || []
|
||||
};
|
||||
var label = $("#mq-run-target-label");
|
||||
if (label) label.textContent = target.kind === "entry" ? "入口 main" : "函数 " + (target.label || "");
|
||||
renderRunParams(pendingRun.params);
|
||||
var mode = document.querySelector('input[name="mq-mode"][value="pure"]');
|
||||
if (mode) mode.checked = true;
|
||||
var grants = $("#mq-run-grants");
|
||||
if (grants) grants.hidden = true;
|
||||
updateRunPreview();
|
||||
openDialog("mq-dialog-run");
|
||||
}
|
||||
|
||||
function openRunForMain() {
|
||||
if (reader.dataset.coreAvailable !== "true") {
|
||||
showUnsupported(
|
||||
"运行文档",
|
||||
"当前页面没有可用的冻结核心(MARQDO_BIN),无法通过 CLI 执行;打开、刷新与导出仍然零副作用。"
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (reader.dataset.hasMain !== "true") {
|
||||
toast("本文档没有可执行的 main;请从函数面板选择一个 H2 Exec 函数");
|
||||
showFunctions();
|
||||
return;
|
||||
}
|
||||
openRunForm({ kind: "entry", label: "入口 main" });
|
||||
}
|
||||
|
||||
function submitRun() {
|
||||
if (!pendingRun) return;
|
||||
var params = rawParams();
|
||||
for (var i = 0; i < params.length; i += 1) {
|
||||
if (params[i].required && params[i].expression.trim() === "") {
|
||||
toast("缺少必填参数:" + params[i].name);
|
||||
return;
|
||||
}
|
||||
}
|
||||
var mode = selectedMode();
|
||||
var grants = mode === "project"
|
||||
? { read: grantList("mq-grant-read"), write: grantList("mq-grant-write") }
|
||||
: { read: [], write: [] };
|
||||
if (mode === "project" && grants.read.length === 0 && grants.write.length === 0) {
|
||||
toast("project 模式必须至少声明一个相对项目根的 fs read/write glob");
|
||||
return;
|
||||
}
|
||||
if (mode === "project" &&
|
||||
!window.confirm("project 模式将按你填写的 glob 授予文件读写权限。它仍不是操作系统沙箱,是否继续?")) {
|
||||
return;
|
||||
}
|
||||
var payload = {
|
||||
document: reader.dataset.document,
|
||||
target: pendingRun.kind === "entry"
|
||||
? { kind: "entry" }
|
||||
: { kind: "function", function_id: pendingRun.functionId },
|
||||
parameters: params.map(function (param) {
|
||||
return { name: param.name, expression: param.expression };
|
||||
}),
|
||||
analysis_digest: reader.dataset.analysisDigest,
|
||||
mode: mode,
|
||||
grants: grants,
|
||||
client_request_id: pendingRun.clientRequestId
|
||||
};
|
||||
closeAllDialogs();
|
||||
clearRunOutput();
|
||||
showRunPanel();
|
||||
setRunBusy(true);
|
||||
fetch("/api/run", {
|
||||
setRunStatus("正在提交运行请求…");
|
||||
fetch("/api/runs", {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
cache: "no-store",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
"X-MQ-CSRF": token
|
||||
"X-View-CSRF": csrfToken()
|
||||
},
|
||||
body: JSON.stringify({ path: path, mode: "pure", confirm: true })
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
.then(function (response) {
|
||||
return response.json().then(function (data) {
|
||||
return { ok: response.ok, data: data };
|
||||
});
|
||||
return response.json().then(function (data) { return { ok: response.ok, status: response.status, data: data }; });
|
||||
})
|
||||
.then(function (result) {
|
||||
if (!result.ok || !result.data || !result.data.ok) {
|
||||
if (!result.ok || !result.data || !result.data.run_id) {
|
||||
setRunBusy(false);
|
||||
var reason = result.data && result.data.message
|
||||
? result.data.message
|
||||
: "运行被拒绝或失败";
|
||||
toast("运行未完成:" + reason);
|
||||
var reason = result.data && result.data.message ? result.data.message : "运行请求被拒绝";
|
||||
setRunStatus("运行未启动(" + result.status + "):" + reason);
|
||||
toast("运行未启动:" + reason);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
window.sessionStorage.setItem(
|
||||
"marqdo.view.scroll",
|
||||
String(window.scrollY || 0)
|
||||
);
|
||||
} catch (error) {
|
||||
/* storage is optional */
|
||||
}
|
||||
window.location.assign(result.data.redirect);
|
||||
subscribeRun(result.data, pendingRun ? pendingRun.label : "运行");
|
||||
})
|
||||
.catch(function (error) {
|
||||
setRunBusy(false);
|
||||
setRunStatus("运行请求失败:" + error.message);
|
||||
toast("运行请求失败:" + error.message);
|
||||
});
|
||||
}
|
||||
|
||||
function subscribeRun(job, targetLabel) {
|
||||
closeActiveObserver();
|
||||
activeRun = {
|
||||
runId: job.run_id,
|
||||
eventsUrl: job.events_url,
|
||||
cancelUrl: job.cancel_url,
|
||||
source: null,
|
||||
lastSeq: -1,
|
||||
targetLabel: targetLabel || "运行",
|
||||
terminal: false
|
||||
};
|
||||
clearRunOutput();
|
||||
showRunPanel();
|
||||
setRunStatus("状态:已接受 · " + activeRun.targetLabel);
|
||||
if (!window.EventSource) {
|
||||
setRunBusy(false);
|
||||
setRunStatus("浏览器不支持 EventSource,无法接收运行状态;请使用现代浏览器。");
|
||||
return;
|
||||
}
|
||||
var source = new EventSource(job.events_url, { withCredentials: true });
|
||||
activeRun.source = source;
|
||||
function apply(event) {
|
||||
var data;
|
||||
try {
|
||||
data = JSON.parse(event.data);
|
||||
} catch (error) {
|
||||
return;
|
||||
}
|
||||
if (!data ||
|
||||
data.schema !== "marqdo.view-run-events" ||
|
||||
data.schema_version !== 1 ||
|
||||
data.run_id !== job.run_id ||
|
||||
!Number.isSafeInteger(data.seq) ||
|
||||
data.seq <= activeRun.lastSeq) {
|
||||
return;
|
||||
}
|
||||
activeRun.lastSeq = data.seq;
|
||||
updateRunView(data);
|
||||
}
|
||||
["run.state", "run.complete", "run.error", "run.snapshot"].forEach(function (kind) {
|
||||
source.addEventListener(kind, apply);
|
||||
});
|
||||
source.onerror = function () {
|
||||
if (activeRun && !activeRun.terminal) {
|
||||
setRunStatus("SSE 连接中断,正在自动恢复…(任务仍在服务端运行;不会重新执行)");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function updateRunView(data) {
|
||||
var panel = runPanel();
|
||||
if (panel) {
|
||||
panel.hidden = false;
|
||||
panel.dataset.runState = data.state;
|
||||
}
|
||||
reader.dataset.runState = data.state;
|
||||
setRunStatus("状态:" + stateLabel(data.state) + (data.at ? " · " + data.at : ""));
|
||||
if (!isTerminalState(data.state)) {
|
||||
setRunBusy(true);
|
||||
return;
|
||||
}
|
||||
if (activeRun) activeRun.terminal = true;
|
||||
closeActiveObserver();
|
||||
setRunBusy(false);
|
||||
if (data.result) renderRunResult(data.result, data.state, data.error);
|
||||
else if (data.error) renderRunResult(null, data.state, data.error);
|
||||
if (data.trace) renderTrace(data.trace);
|
||||
else if (data.result && data.result.trace_status) renderTraceStatus(data.result.trace_status);
|
||||
if (data.state === "succeeded") toast("运行完成");
|
||||
else toast("运行" + stateLabel(data.state));
|
||||
}
|
||||
|
||||
function renderRunResult(result, state, error) {
|
||||
var summary = $("#mq-run-summary");
|
||||
if (!summary) return;
|
||||
summary.textContent = "";
|
||||
if (result) {
|
||||
if (result.target) {
|
||||
var label = result.target.kind === "entry" ? "入口 main" : "函数 " + (result.target.label || result.target.cli_name || "");
|
||||
appendLine(summary, "p", "mq-run-result", label + " · 模式 " + (result.mode || "pure") +
|
||||
(typeof result.duration_ms === "number" ? " · " + result.duration_ms + " ms" : "") +
|
||||
(result.exit_code === null || typeof result.exit_code === "undefined" ? "" : " · 退出码 " + result.exit_code));
|
||||
}
|
||||
if (result.value_text) {
|
||||
appendLine(summary, "p", "mq-run-result", "返回值:" + result.value_text);
|
||||
}
|
||||
if (result.stale) {
|
||||
appendLine(summary, "p", "mq-run-warning", "源码在运行后发生变化:结果可见但标记为过期,不在当前正文上绘制执行标注。");
|
||||
}
|
||||
if (result.stdout) {
|
||||
var stdout = $("#mq-run-stdout");
|
||||
if (stdout) {
|
||||
stdout.textContent = result.stdout;
|
||||
stdout.hidden = false;
|
||||
}
|
||||
}
|
||||
if (result.stderr) {
|
||||
var stderr = $("#mq-run-stderr");
|
||||
if (stderr) {
|
||||
stderr.textContent = result.stderr;
|
||||
stderr.hidden = false;
|
||||
}
|
||||
}
|
||||
if (Array.isArray(result.diagnostics) && result.diagnostics.length) {
|
||||
appendLine(summary, "p", "mq-run-warning", "诊断:" + result.diagnostics.length + " 条(详见运行详情)");
|
||||
var list = document.createElement("ol");
|
||||
list.className = "mq-run-events";
|
||||
result.diagnostics.slice(0, 20).forEach(function (diagnostic) {
|
||||
var code = diagnostic && diagnostic.code ? diagnostic.code : "diagnostic";
|
||||
var message = diagnostic && diagnostic.message ? diagnostic.message : "";
|
||||
appendLine(list, "li", "", code + ":" + message);
|
||||
});
|
||||
summary.appendChild(list);
|
||||
}
|
||||
}
|
||||
if (error && (error.code || error.message)) {
|
||||
appendLine(summary, "p", "mq-run-error", (error.code || "error") + ":" + (error.message || "运行失败"));
|
||||
}
|
||||
if (state === "cancelled") {
|
||||
appendLine(summary, "p", "mq-run-warning", "运行已按请求取消;进程组已终止。");
|
||||
}
|
||||
}
|
||||
|
||||
function renderTraceStatus(status) {
|
||||
if (!status || status === "verified") return;
|
||||
var summary = $("#mq-run-summary");
|
||||
if (!summary) return;
|
||||
var message = status === "invalid"
|
||||
? "Trace 与本次 Analysis 不匹配或格式无效:不绘制执行标注,也不声称观察到完整过程。"
|
||||
: "本次运行没有可用的 Trace v2(unavailable):只展示 CLI 返回值与输出。";
|
||||
appendLine(summary, "p", "mq-run-warning", message);
|
||||
}
|
||||
|
||||
function renderTrace(trace) {
|
||||
var summary = $("#mq-run-summary");
|
||||
var wrap = $("#mq-run-trace-wrap");
|
||||
var list = $("#mq-run-events");
|
||||
if (!wrap || !list) return;
|
||||
list.textContent = "";
|
||||
if (!trace || trace.status !== "verified") {
|
||||
wrap.hidden = true;
|
||||
renderTraceStatus(trace && trace.status ? trace.status : "unavailable");
|
||||
return;
|
||||
}
|
||||
wrap.hidden = false;
|
||||
if (summary) {
|
||||
if (trace.stale) {
|
||||
appendLine(summary, "p", "mq-run-warning", "Trace 属于运行时的源码:当前源码已变化,本次不绘制执行标注。");
|
||||
}
|
||||
if (trace.truncated) {
|
||||
var label = trace.truncated.label || (trace.truncated.reason + "(上限 " + trace.truncated.limit + ")");
|
||||
appendLine(summary, "p", "mq-run-warning", "Trace 被截断:" + label + ";这不代表程序终止。");
|
||||
}
|
||||
}
|
||||
var entryEvents = Array.isArray(trace.events) ? trace.events : [];
|
||||
entryEvents.slice(0, 200).forEach(function (event) {
|
||||
var location = event.span ? "span " + event.span.start + "–" + event.span.end : (event.module_id || "");
|
||||
var detail = event.detail ? " · " + event.detail : "";
|
||||
var operation = event.operation ? " · " + event.operation : "";
|
||||
appendLine(list, "li", "", event.kind + " · " + location + detail + operation);
|
||||
});
|
||||
if (entryEvents.length > 200) {
|
||||
appendLine(list, "li", "mq-colophon", "仅显示前 200 条(共 " + entryEvents.length + " 条)。");
|
||||
}
|
||||
if (!trace.stale) {
|
||||
var bySource = {};
|
||||
$$("[data-source-id]").forEach(function (element) {
|
||||
bySource[element.dataset.sourceId] = element;
|
||||
});
|
||||
entryEvents.forEach(function (event) {
|
||||
if (!event.source_id || !bySource[event.source_id]) return;
|
||||
var chip = document.createElement("span");
|
||||
chip.className = "mq-run-chip";
|
||||
chip.dataset.viewChip = "1";
|
||||
chip.dataset.runSeq = String(event.seq);
|
||||
chip.textContent = event.detail || event.kind;
|
||||
bySource[event.source_id].appendChild(chip);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function cancelRun() {
|
||||
if (!activeRun || activeRun.terminal) return;
|
||||
setRunStatus("正在请求取消…");
|
||||
fetch(activeRun.cancelUrl, {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
cache: "no-store",
|
||||
headers: { "Accept": "application/json", "X-View-CSRF": csrfToken() }
|
||||
})
|
||||
.then(function (response) {
|
||||
return response.json().then(function (data) { return { ok: response.ok, status: response.status, data: data }; });
|
||||
})
|
||||
.then(function (result) {
|
||||
if (!result.ok) {
|
||||
var reason = result.data && result.data.message ? result.data.message : "取消失败";
|
||||
setRunStatus("取消请求被拒绝(" + result.status + "):" + reason);
|
||||
return;
|
||||
}
|
||||
setRunStatus("已请求取消;等待唯一终态…");
|
||||
})
|
||||
.catch(function (error) {
|
||||
setRunStatus("取消请求失败:" + error.message);
|
||||
});
|
||||
}
|
||||
|
||||
function clearRun() {
|
||||
closeAllDialogs();
|
||||
try {
|
||||
var url = new URL(window.location.href);
|
||||
if (url.searchParams.has("run")) {
|
||||
url.searchParams.delete("run");
|
||||
window.location.assign(url.toString());
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
/* fall through */
|
||||
closeActiveObserver();
|
||||
var panel = runPanel();
|
||||
if (panel) {
|
||||
panel.hidden = true;
|
||||
panel.dataset.runState = "idle";
|
||||
}
|
||||
var panel = $("#mq-run-panel");
|
||||
if (panel) panel.hidden = true;
|
||||
toast("已清理本地展示状态(源文件与缓存未修改)");
|
||||
reader.dataset.runState = "idle";
|
||||
clearRunOutput();
|
||||
setRunStatus("尚未运行。点击 Dock 的“运行”执行 main,或在函数面板选择函数。");
|
||||
toast("已清理本地结果展示(未删除项目文件、lock 或服务端运行记录)");
|
||||
}
|
||||
|
||||
document.addEventListener("click", function (event) {
|
||||
var trigger = event.target.closest ? event.target.closest("[data-action]") : null;
|
||||
if (!trigger) return;
|
||||
event.preventDefault();
|
||||
handleAction(trigger.dataset.action);
|
||||
handleAction(trigger.dataset.action, trigger);
|
||||
});
|
||||
|
||||
document.addEventListener("click", function (event) {
|
||||
@@ -440,6 +877,16 @@
|
||||
if (event.target && event.target.id === "mq-search-input") {
|
||||
renderSearch(event.target.value);
|
||||
}
|
||||
if (event.target && (event.target.id === "mq-grant-read" || event.target.id === "mq-grant-write" || event.target.dataset.paramName)) {
|
||||
updateRunPreview();
|
||||
}
|
||||
});
|
||||
document.addEventListener("change", function (event) {
|
||||
if (event.target && event.target.name === "mq-mode") {
|
||||
var grants = $("#mq-run-grants");
|
||||
if (grants) grants.hidden = event.target.value !== "project";
|
||||
updateRunPreview();
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener("keydown", function (event) {
|
||||
@@ -492,22 +939,6 @@
|
||||
setMode("document");
|
||||
}
|
||||
|
||||
// Restore reading position after a run reload, without faking any result.
|
||||
try {
|
||||
var scroll = window.sessionStorage.getItem("marqdo.view.scroll");
|
||||
if (scroll && new URLSearchParams(window.location.search).has("run")) {
|
||||
window.sessionStorage.removeItem("marqdo.view.scroll");
|
||||
var target = parseInt(scroll, 10);
|
||||
if (!isNaN(target)) {
|
||||
window.requestAnimationFrame(function () {
|
||||
window.scrollTo(0, target);
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
/* storage is optional */
|
||||
}
|
||||
|
||||
// Keep dock buttons visible above the last line on small screens.
|
||||
function syncDockInset() {
|
||||
var dock = $(".mq-dock");
|
||||
|
||||
+26
-26
@@ -5,7 +5,7 @@
|
||||
> `PENDING`(未开始)、`N/A`(0002 明确非目标/删除项)。
|
||||
> 证据列写测试/脚本文档;不得以视觉相似代替测试。
|
||||
|
||||
最后更新:2026-11-22(PR-00)
|
||||
最后更新:2026-11-22(PR-04)
|
||||
|
||||
## 1. §0 核心不可妥协条件
|
||||
|
||||
@@ -28,21 +28,21 @@
|
||||
| `@exec`/`@knowledge` 轻量标识(依 Analysis) | PASS | `src/semantic.rs`、`tests/integration/rendering.rs` |
|
||||
| 源码态 | PASS | `src/render.rs`、`tests/integration/unicode_spans.rs` |
|
||||
| 函数清单/导航 | PASS | `src/presentation.rs`、`src/render.rs` |
|
||||
| 单函数参数填写 + 调用 | **PENDING** | PR-03 请求合同 + PR-04 前端表单 |
|
||||
| 文档入口 `main` 执行 | PARTIAL | 同步 pure 已存在;需改为 SSE 异步任务(PR-04) |
|
||||
| 运行结果(返回/stdout/stderr/错误) | PARTIAL | 0001 已有;需 0002 JSON→UI 映射与安全文本展示复核(PR-04/05) |
|
||||
| Trace v2 调用/判断/循环/副作用 | PARTIAL | `src/trace.rs` 已有;需 SSE 后动态标注与 stale 规则(PR-04/05) |
|
||||
| 执行确认/取消/超时/单任务 | **PENDING** | PR-03/04 |
|
||||
| **SSE 状态与终态(禁止轮询)** | **PENDING(阻塞)** | PR-04 |
|
||||
| 单函数参数填写 + 调用 | PASS | `assets/reader.js` 动态表单 + `execution/request.rs` + HTTP/SSE 测试 |
|
||||
| 文档入口 `main` 执行 | PASS | `POST /api/runs` → SSE;无 main 时引导函数列表 |
|
||||
| 运行结果(返回/stdout/stderr/错误) | PASS | 安全文本/DOM 渲染、`value_text`、stderr/stdout、错误码;浏览器/HTTP 测试 |
|
||||
| Trace v2 调用/判断/循环/副作用 | PASS(动态锚点) | Controller 校验摘要 + JS `source_id` chip;stale 不锚定 |
|
||||
| 执行确认/取消/超时/单任务 | PASS | 两阶段确认、幂等取消、唯一终态、409 busy、墙钟上限 |
|
||||
| **SSE 状态与终态(禁止轮询)** | PASS | 逐帧 flush、心跳、Last-Event-ID、snapshot、2 连接上限;无轮询路由 |
|
||||
| 独立 Tool 安装/调用 | PASS(0001) | PR-01 迁移到 0.2.0/scripts |
|
||||
| 静态 HTML 导出 | PARTIAL | 已实现;PR-06 复核零执行/离线 |
|
||||
| 暖纸/品牌/樱花/侧注/Dock | PARTIAL | 已有;PR-05 视觉矩阵 |
|
||||
| 搜索 + 目录 | PASS | 浏览器证据 |
|
||||
| 有选择的 Observed 侧注/退化 | PARTIAL | 内联 chip 已有;SSE 后按本次运行更新(PR-04/05) |
|
||||
| 深色主题/字号/显示设置 | PARTIAL | 已有字号/标注开关/print;深色待 PR-05 |
|
||||
| project fs read/write grants | **PENDING** | PR-03/04(MVP CONTROLLED) |
|
||||
| project fs read/write grants | PASS(MVP CONTROLLED) | 请求校验 + 二次确认 + `--allow-read/--allow-write` argv 测试 |
|
||||
| net/process/env/plugin 等授权 | N/A(DEFERRED,必须拒绝并提示 CLI) | PR-03 校验 |
|
||||
| 变量/内存/Notebook/调试/Session/AI/Kernel | N/A(REMOVED) | 禁止出现 DOM/路由/状态 |
|
||||
| 变量/内存/Notebook/调试/Session/AI/Kernel | N/A(REMOVED) | 无路由/DOM/状态;仅一个明确 UNSUPPORTED 说明 |
|
||||
|
||||
## 3. §5 架构与目录
|
||||
|
||||
@@ -58,18 +58,18 @@
|
||||
|
||||
| 条款 | 状态 | 计划 |
|
||||
|---|---|---|
|
||||
| 7 条最小路由 | **PENDING** | PR-04 |
|
||||
| POST /api/runs 两阶段确认请求体(document/target/parameters/analysis_digest/mode/grants/client_request_id) | PARTIAL | `execution/request.rs` 校验/解析/计划已实现;HTTP 路由 PR-04 |
|
||||
| 校验顺序(会话→CSRF/Origin/Host→大小/schema→containment→check→digest→函数/参数→模式/grants→并发→202) | PARTIAL | Controller 已实现 schema→dedupe→busy→check→digest→target→202;HTTP 前置校验 PR-04 |
|
||||
| 同 `client_request_id` 幂等/不同 payload 409 | PASS(Controller) | `tests/integration/execution.rs`;HTTP 映射 PR-04 |
|
||||
| SSE 帧合同(事件类型/seq/id/schema/心跳) | **PENDING** | PR-04 |
|
||||
| Last-Event-ID 重放、快照、128 缓冲、TTL、≤2 连接/任务 | **PENDING** | PR-04 |
|
||||
| 单活动任务、409 run.busy、后台执行不阻塞 SSE | PARTIAL | Controller 单任务/后台线程已实现并测试;HTTP/SSE PR-04 |
|
||||
| 7 条最小路由 | PASS | `server/routes.rs`;旧路由 404 测试 |
|
||||
| POST /api/runs 两阶段确认请求体(document/target/parameters/analysis_digest/mode/grants/client_request_id) | PASS | `execution/request.rs` + `POST /api/runs`;unknown field/size/mode/grant 测试 |
|
||||
| 校验顺序(会话→CSRF/Origin/Host→大小/schema→containment→check→digest→函数/参数→模式/grants→并发→202) | PASS | `server/security.rs` + Controller;拒绝路径不启动进程测试 |
|
||||
| 同 `client_request_id` 幂等/不同 payload 409 | PASS | Controller + HTTP 集成测试 |
|
||||
| SSE 帧合同(事件类型/seq/id/schema/心跳) | PASS | `server/sse.rs`、`tests/integration/http_live.rs` |
|
||||
| Last-Event-ID 重放、快照、128 缓冲、TTL、≤2 连接/任务 | PASS | 重放/伪造游标/2 连接/终态快照测试 |
|
||||
| 单活动任务、409 run.busy、后台执行不阻塞 SSE | PASS | Controller + HTTP 409/并发测试 |
|
||||
| 进程组取消(TERM→2s→KILL)、墙钟上限、有界输出 | PASS(模块) | `src/execution/process.rs`、`tests/integration/execution.rs` |
|
||||
| 显式预算参数 | PASS(模块) | `src/execution/controller.rs`、`--run-timeout` 1..=120 |
|
||||
| 会话 Cookie(HttpOnly/SameSite=Strict)+ X-View-CSRF + Origin/Host | **PENDING** | PR-04 |
|
||||
| 会话 Cookie(HttpOnly/SameSite=Strict)+ X-View-CSRF + Origin/Host | PASS | `server/security.rs`、`tests/security/`、浏览器测试 |
|
||||
| loopback only、请求体≤64KiB、CSP、路径 containment | PARTIAL | 大部分已有;会话 Cookie 待 PR-04 |
|
||||
| SSE 按会话隔离、跨站读取拒绝 | **PENDING** | PR-04 |
|
||||
| SSE 按会话隔离、跨站读取拒绝 | PASS | 跨会话 404/401、Sec-Fetch-Site 拒绝 |
|
||||
|
||||
## 5. §8 里程碑
|
||||
|
||||
@@ -79,7 +79,7 @@
|
||||
| PR-01 Tool/打包/scripts/CI/0.2.0 | **完成** | `scripts/package.sh`、`scripts/install-smoke.sh`、`scripts/verify-frozen-cli.sh`、`.github/workflows/ci.yml` |
|
||||
| PR-02 Reader/Analysis 结构与只读路由 | **完成** | `src/protocol/*`、`src/reader/*`、`src/config.rs`、`/api/documents`、`tests/{contract,integration}`;`docs/evidence/PR-02/` |
|
||||
| PR-03 执行层/请求/进程/控制器 | **完成** | `src/execution/*`、ADR-0008、`docs/evidence/PR-03/` |
|
||||
| PR-04 SSE/路由/会话/前端闭环 | PENDING | — |
|
||||
| PR-04 SSE/路由/会话/前端闭环 | **完成** | `docs/evidence/PR-04/`(含真实 Chromium + 真实冻结 CLI) |
|
||||
| PR-05 Trace 绑定/标注/浏览器回归 | PENDING | — |
|
||||
| PR-06 导出/发布/文档闭环 | PENDING | — |
|
||||
|
||||
@@ -91,15 +91,15 @@
|
||||
| E02 打开 knowledge+exec 文件不运行 | PASS | `tests/integration/http_live.rs` |
|
||||
| E03 Source/Document 切换 | PASS | 浏览器证据 |
|
||||
| E04 中文/Emoji/表格/公式 span | PASS | `tests/integration/unicode_spans.rs`、golden |
|
||||
| E05 main 运行 run --json --trace-file | PARTIAL | 同步路径有;SSE 终态待 PR-04 |
|
||||
| E06 H2 Exec n=5 call | PARTIAL | `build_call_args` + Controller 测试;真实 CLI/UI PR-04/06 |
|
||||
| E07 文本/列表常量参数 | PARTIAL | `--arg name=expression` argv 已实现;真实 CLI/UI PR-04/06 |
|
||||
| E05 main 运行 run --json --trace-file | PASS | 真实冻结 CLI SSE 证据 `docs/evidence/PR-04/real-run.log` |
|
||||
| E06 H2 Exec n=5 call | PASS | call argv 测试 + 前端函数表单;真实 CLI 在 PR-06 验收 |
|
||||
| E07 文本/列表常量参数 | PASS | `--arg` 原样表达式 + 前端输入;CLI 最终校验 |
|
||||
| E08 无 main 不自动运行别的函数 | PARTIAL | 现有 `can_offer_run` 逻辑;PR-04 复核 |
|
||||
| E09 Trace 事件映射不伪造变量 | PARTIAL | `src/trace.rs`;SSE 后复核 |
|
||||
| E10 SSE text/event-stream 无 polling | **PENDING** | PR-04 |
|
||||
| E11 Last-Event-ID 重连 | **PENDING** | PR-04 |
|
||||
| E12 长任务心跳/GET 不重启 | **PENDING** | PR-04 |
|
||||
| E13 取消终止进程树 | PARTIAL | Controller/process 已测(`second_run_is_busy...`、`process.rs` 单测);HTTP 接线 PR-04 |
|
||||
| E10 SSE text/event-stream 无 polling | PASS | 集成 + 浏览器请求记录 |
|
||||
| E11 Last-Event-ID 重连 | PASS | 重放/伪造游标 snapshot 测试 |
|
||||
| E12 长任务心跳/GET 不重启 | PASS | 心跳 + 2 连接 + GET 观察不启动任务 |
|
||||
| E13 取消终止进程树 | PASS | Controller/process 单测 + HTTP 取消唯一终态 + 浏览器取消路径 |
|
||||
| E14 静态导出零联网/相对链接 | PARTIAL | 已实现;PR-06 复核 |
|
||||
| E15 刷新/重开不自动执行 | PASS | `tests/integration/http_live.rs` |
|
||||
| E16 运行后改源码 → stale 无高亮 | PARTIAL | 现有 stale;PR-05 复核 |
|
||||
|
||||
+21
-35
@@ -24,9 +24,9 @@
|
||||
| PR-01 Tool v1 打包/安装/调度、0.2.0、scripts/、CI | **完成** | `scripts/package.sh`、`scripts/install-smoke.sh`、`scripts/verify-frozen-cli.sh`、`.github/workflows/ci.yml`;冻结 CLI `tool install`/`view --help`/篡改拒绝实测 |
|
||||
| PR-02 Reader/Analysis 只读面与目标目录结构 | **完成** | `src/protocol/*`、`src/reader/*`、`src/config.rs`、`tests/{contract,integration}/`、`/api/documents`;证据 `docs/evidence/PR-02/` |
|
||||
| PR-03 执行层:request/process/controller、pure + project grants | **完成** | `src/execution/{request,process,controller,events}.rs`、`--run-timeout`、ADR-0008、`tests/integration/execution.rs`;证据 `docs/evidence/PR-03/` |
|
||||
| PR-04 SSE 任务生命周期、取消、7 路由、会话 Cookie/CSRF | **未实现(MVP 阻塞项)** | — |
|
||||
| PR-05 Trace 绑定/原文标注/浏览器回归 | 待开始(现有 Trace 校验可迁移) | `src/trace.rs` |
|
||||
| PR-06 静态导出/发布包/文档闭环 | 待开始(现有导出可迁移) | `src/export.rs` |
|
||||
| PR-04 SSE 任务生命周期、取消、7 路由、会话 Cookie/CSRF | **完成** | `src/server/{mod,routes,security,sse}.rs`、`assets/reader.js` SSE/表单、`tests/integration/http_live.rs`、`tests/security/`、真实 Chromium + 真实冻结 CLI SSE 证据 `docs/evidence/PR-04/` |
|
||||
| PR-05 Trace 绑定/原文标注/浏览器回归 | 待开始(SSE 后动态标注/宽度矩阵已基本具备) | `src/execution/controller.rs` Trace 摘要、浏览器证据 |
|
||||
| PR-06 静态导出/发布包/文档闭环 | 待开始 | `src/export.rs`、`scripts/acceptance.sh`、`docs/ACCEPTANCE.md` |
|
||||
|
||||
## 继承自 0001 的可用资产(不等于 0002 验收通过)
|
||||
|
||||
@@ -37,44 +37,30 @@
|
||||
| 原始 Markdown/GFM 阅读、源码态、搜索/设置/打印 | 已实现(单一 `assets/reader.css`/`assets/reader.js`) |
|
||||
| Analysis v2 严格校验、函数/Unit/签名/诊断/导入/引用/资源投影 | 已实现(无效 span 降级) |
|
||||
| 单一 `ReaderRenderer`,Live/Export 共用 | 已实现(`src/reader/render.rs`,门禁测试) |
|
||||
| 显式确认后同步运行 `pure` + Trace v2 校验与展示 | 旧同步路径仍在(过渡);新的异步 Controller/SSE 就绪于 PR-03/04 |
|
||||
| 显式确认 + SSE 异步执行 + Trace v2 | 已实现(7 路由、单任务、取消、断线重放) |
|
||||
| 静态离线导出(无执行、manifest/哈希、原子发布) | 已实现,待按 0002 重新验收 |
|
||||
| Tool v1 打包/安装/分发、冻结 CLI SHA 前后一致 | 已实现,待迁移至 `scripts/` 与 0.2.0 |
|
||||
| HTTP 安全(Host/Origin/CSRF/路径 containment/CSP) | 部分实现;缺**会话 Cookie**模型与 7 路由合同 |
|
||||
| 真实 Chromium 视觉/交互/无 JS/打印 | 已有证据(0001 时期),待按 0002 宽度矩阵重跑 |
|
||||
|
||||
## 与 RFC-VIEW-0002 的已知差距(全部必须关闭)
|
||||
## 与 RFC-VIEW-0002 的已知差距(剩余项)
|
||||
|
||||
1. **SSE 执行闭环缺失**:当前是 POST 同步运行后整页重载;0002 要求
|
||||
`POST /api/runs` → 202 → `GET /api/runs/{id}/events` SSE(无轮询)→
|
||||
accepted/running/终态;断线 `Last-Event-ID` 重放、128 事件环形缓冲、终态 TTL。
|
||||
2. **路由未收敛**:现为 `/api/run`、`/api/clear-run`、`/api/document`、
|
||||
`/api/health`;0002 只允许
|
||||
`GET /`、`GET /file`、`GET /assets/...`、`GET /api/documents`、
|
||||
`POST /api/runs`、`GET /api/runs/{id}/events`、`POST /api/runs/{id}/cancel`。
|
||||
3. **无单函数调用表单**:函数目前只有跳转列表;缺基于 Analysis 签名的参数填写、
|
||||
命令预览、`--arg` 常量表达式提交。
|
||||
4. **无 project grants**:0002 要求受控 fs read/write glob(明确二次确认),
|
||||
其它 net/process/env/plugin 一律拒绝并引导 CLI。
|
||||
5. **无运行会话 Cookie**:CSRF 目前是进程级 token;0002 要求
|
||||
`HttpOnly; SameSite=Strict` 随机会话 Cookie + 每会话 CSRF,且 SSE 按会话隔离
|
||||
(PR-04)。
|
||||
6. **HTTP/SSE 传输未接**:Controller 已实现单任务状态机、取消、去重、
|
||||
`client_request_id` 幂等/409 与 `409 run.busy`(`src/execution/controller.rs`),
|
||||
但 `POST /api/runs`、`GET .../events`、`POST .../cancel` 与前端尚未切换(PR-04)。
|
||||
7. **执行预算**:Controller 已显式发送 `--timeout`(默认 30s/最大 120s)、
|
||||
`--fuel 1000000`、`--max-output 1048576`、`--trace-max-events 10000`、
|
||||
`--trace-max-bytes 4194304`,并做 4 MiB JSON/Trace 有界读取与
|
||||
`view.output_limit`;HTTP 层仍需映射为终态事件(PR-04)。
|
||||
8. **目录/测试/示例仍有缺口**:`src/protocol`/`src/reader`/`src/config.rs`/
|
||||
`tests/{contract,integration}`/`scripts/`/`.github/workflows/ci.yml` 已就位;
|
||||
仍缺 `src/execution/*`、`src/server/{mod,routes,security,sse}.rs`、
|
||||
`tests/security/` 套件、`examples/{welcome,branch-loop,function-params,
|
||||
knowledge-only,unsafe-side-effect}.mq.md`、`docs/design` 0002 宽度截图矩阵。
|
||||
9. **文档口径**:README/COMPATIBILITY/ACCEPTANCE 仍含 0001 时期表述,需在
|
||||
PR-06 前全部更新为 0002 口径。
|
||||
10. **视觉回归矩阵**:0002 要求 2048×1133 源参考与 1664×920/1440×900/1024×768/
|
||||
768×1024/390×844 宽度;现有截图集合不完整。
|
||||
PR-00~PR-04 已关闭 SSE、7 路由、单函数调用表单、受控 project grants、
|
||||
会话 Cookie/CSRF、取消/去重/单任务、执行预算与有界输出、目标目录/测试树/
|
||||
`scripts/`/CI/浏览器宽度矩阵。**剩余**:
|
||||
|
||||
1. **PR-05**:Trace 事件到原文的锚点/侧注在 SSE 后已由前端按 `source_id`
|
||||
渲染 keyed chip;仍需固化 stale/截断/无 Trace 的浏览器回归与最终视觉矩阵
|
||||
证据(含深色/打印/断网/无 JS)。
|
||||
2. **PR-06**:`examples/{welcome,branch-loop,function-params,knowledge-only,
|
||||
unsafe-side-effect}.mq.md` 需按 RFC §13.3 创建并用冻结 CLI 实际 check/call
|
||||
记录;静态导出需按 0002 重新跑离线/零执行验收;更新 ACCEPTANCE/README/
|
||||
COMPATIBILITY/CHANGELOG 为 0002 口径并生成最终 evidence manifest。
|
||||
3. 0002 §9.2 N 系列须逐项在最终验收报告中登记(当前 HTTP/SSE/安全套件已覆盖
|
||||
大部分:N01/N02/N03/N04/N05/N06/N07/N09/N10/N11/N12/N13/N14/N15/N16/N17/
|
||||
N19/N21/N22 有对应测试;N18/N20 在 PR-06 冻结 CLI/导出套件中登记)。
|
||||
4. 视觉/可达性的人工像素级比对与完整 screen-reader 走查仍标 `UNVERIFIED`,
|
||||
自动化几何/颜色/无外部资源/响应式证据已存在(`docs/evidence/PR-04/`)。
|
||||
|
||||
## 明确 UNSUPPORTED / 非目标(不得伪造)
|
||||
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
# ADR-0009:SSE 传输实现、会话模型与 7 路由收敛
|
||||
|
||||
- 状态:Accepted
|
||||
- 日期:2026-11-22
|
||||
- 关联:`docs/architecture/RFC-VIEW-0002.md` §6.2/§6.4/§6.5/§6.8;PR-04
|
||||
|
||||
## 1. SSE 传输:直接写 socket 并逐帧 flush
|
||||
|
||||
`tiny_http` 的流式 `Response` 使用 `chunked_transfer::Encoder::new`,只有缓冲区
|
||||
填满或响应结束时才 flush。对 SSE 来说,这意味着已接受的 `accepted`/`running`/
|
||||
心跳可能被扣留数秒,直到任务结束,**不满足“状态变化立即推送”**。
|
||||
|
||||
因此 `server/sse.rs` 在成功鉴权后使用 `Request::into_writer()` 取到底层 socket
|
||||
writer,自行写入:
|
||||
|
||||
```
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: text/event-stream; charset=utf-8
|
||||
Cache-Control: no-store
|
||||
X-Accel-Buffering: no
|
||||
Connection: close
|
||||
|
||||
event: ... / id: N / data: {...}
|
||||
```
|
||||
|
||||
要点:
|
||||
|
||||
- **每帧/心跳后立即 `flush()`**,浏览器 EventSource 即时收到;
|
||||
- 不设 `Content-Length` 且 `Connection: close`,body 以 EOF 结束(SSE 合法传输);
|
||||
- 终态事件写出后主动关闭流;客户端 JS 在收到终态时关闭 EventSource,不会重连
|
||||
重复执行;
|
||||
- 客户端断开(broken pipe)只关闭观察连接,不取消任务、不产生执行终态;
|
||||
- 只允许 4 种 `run.*` 事件 + `: heartbeat` 注释;心跳不使用序号;
|
||||
- 每任务最多 2 个并发 SSE 观察连接(Controller 计数,超出 `429 view.sse_busy`);
|
||||
128 条环形缓冲 + 终态快照 + `Last-Event-ID` 重放或权威 snapshot;
|
||||
- 测试钩子 `MARQDO_VIEW_SSE_HEARTBEAT_SECS` 仅用于本地/CI 缩短心跳周期,默认
|
||||
15 秒(不暴露为产品功能)。
|
||||
|
||||
## 2. 会话与鉴权
|
||||
|
||||
- 首次 `GET /` 或 `GET /file` 发放 `mq_view_session=<随机32字节hex>` Cookie:
|
||||
`HttpOnly; SameSite=Strict; Path=/; Max-Age=43200`;loopback HTTP 不加 `Secure`
|
||||
(不伪造 HTTPS)。
|
||||
- 页面通过 `<meta name="mq-csrf-token" content="...">` 获得**该会话**的 CSRF;
|
||||
POST 必须携带 `X-View-CSRF`,与 Cookie 会话匹配(常量时间比较)。
|
||||
- POST 还要求:合法 `Host`(loopback+端口)、精确同源 `Origin`(缺失即拒绝)、
|
||||
`Sec-Fetch-Site` 不得为 `cross-site`;`POST /api/runs` 要求
|
||||
`Content-Type: application/json`,body ≤64 KiB。
|
||||
- `POST /api/runs/{id}/cancel` 是无 body 的控制请求:允许无 JSON Content-Type,
|
||||
但仍要求 Cookie + CSRF + Origin/Host。
|
||||
- SSE GET 只允许**启动该 run 的会话**读取;事件/取消一律按 `session_id` 校验,
|
||||
跨会话返回 404(不泄漏任务是否存在)。
|
||||
- 会话表上限 64、空闲 TTL 12h;Cookie/CSRF 只存内存,不写磁盘、不进 URL。
|
||||
|
||||
## 3. 路由表(最终态)
|
||||
|
||||
只保留 7 条:`GET /`、`GET /file?path=`、`GET /assets/...`、
|
||||
`GET /api/documents`、`POST /api/runs`、`GET /api/runs/{id}/events`、
|
||||
`POST /api/runs/{id}/cancel`。
|
||||
|
||||
- 删除 `/api/health`、`/api/document`、`/api/run`、`/api/clear-run`;
|
||||
- 不提供状态轮询路由、`/api/eval`、Notebook/session 兼容层或通用 shell 端点;
|
||||
- `GET /api/documents` 是只读结构(文档列表 + 当前 outline/functions/analysis
|
||||
摘要),无副作用;页面/刷新/搜索/切换/导出均不形成执行边。
|
||||
|
||||
## 4. 前端最小状态
|
||||
|
||||
`reader.js` 只做 DOM/表单/SSE:
|
||||
|
||||
- Dock 运行:有 main → 打开运行表单;无 main → 打开函数列表并解释,绝不替跑;
|
||||
- 函数列表的“调用”按钮携带 Analysis 函数 id 与参数签名,动态生成表单;
|
||||
- 表单有命令预览(文本节点)、pure/project 模式与 fs read/write glob;project
|
||||
需要二次 `window.confirm`;无 net/process/env/plugin 等按钮;
|
||||
- 提交一次 POST 后建立 `EventSource(..., {withCredentials:true})`,**没有
|
||||
setInterval/轮询**;`seq` 去重、`run_id` 校验、终态关闭;
|
||||
- 运行区/结果/stdout/stderr/Trace 全部用 `textContent`/DOM 文本构建,绝不
|
||||
innerHTML 服务端数据;stale 结果不绘制原文锚点;
|
||||
- 浏览器重载不会自动 POST;清理只隐藏本地展示,不删除项目文件/lock,也不取消
|
||||
仍在服务端的任务。
|
||||
|
||||
## 5. 与 RFC 的关系
|
||||
|
||||
实现保留 RFC 的公开合同(事件类型、字段、状态机、`Last-Event-ID`、心跳语义),
|
||||
仅选择“直接写 socket”作为传输细节——属于 RFC 允许的实现自由,不改变协议。
|
||||
测试覆盖:HTTP/SSE 集成、真实 Chromium EventSource、跨会话/跨站拒绝、取消唯一
|
||||
终态、心跳、2 连接上限与 Last-Event-ID 重放(见 `docs/evidence/PR-04/`)。
|
||||
@@ -0,0 +1,83 @@
|
||||
# PR-04 证据:SSE 执行闭环、7 路由与会话安全
|
||||
|
||||
- 日期:2026-11-22
|
||||
- 范围:`src/server/{mod,routes,security,sse}.rs`、`src/reader/render.rs` 运行表单/
|
||||
运行区、`assets/reader.js` SSE 前端、`tests/integration/http_live.rs`、
|
||||
`tests/security/`、浏览器套件
|
||||
- 冻结 CLI:`marqdo 3.0.0-beta.1`,SHA-256
|
||||
`062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f`
|
||||
(真实 run 证据 `real-run.log`,run 前后 SHA 不变)
|
||||
- 产品规则:SSE 无轮询;运行唯一入口 `POST /api/runs`;单任务;取消唯一终态
|
||||
|
||||
## 1. 路由与安全
|
||||
|
||||
| 路由 | 验证 |
|
||||
|---|---|
|
||||
| `GET /` / `GET /file` | 发放 HttpOnly/SameSite=Strict Cookie + CSRF meta;重复打开 10 次无 `run` 调用(`pages_issue_a_session_cookie_and_never_execute_the_document`) |
|
||||
| `GET /assets/...` | 唯一 CSS/JS、immutable、CSP/`nosniff`;未知资产 404 |
|
||||
| `GET /api/documents` | `marqdo.view-documents` v1 只读结构;旧 `/api/document`、`/api/health`、`/api/run` 均 404 |
|
||||
| `POST /api/runs` | 202 + run_id/events_url/cancel_url;无 Cookie/CSRF/Origin、错 Origin、非 JSON、超大 body 全部拒绝且不启动进程 |
|
||||
| `GET /api/runs/{id}/events` | `text/event-stream`、逐帧 flush、心跳、Last-Event-ID 重放/伪造游标 snapshot、跨会话 404、无会话 401、>2 连接 429 |
|
||||
| `POST /api/runs/{id}/cancel` | 幂等、唯一 `cancelled` 终态、跨会话 404、不新增进程 |
|
||||
|
||||
浏览器测试还断言:`Origin`/`Sec-Fetch-Site` 跨站拒绝、`HttpOnly`+`SameSite=Strict`、
|
||||
CSP 无 `unsafe-inline`/`unsafe-eval`、symlink 出根被拒、Markdown 不能注入
|
||||
`<script>`/事件处理器。
|
||||
|
||||
## 2. SSE 生命周期(真实事件序列)
|
||||
|
||||
`tests/integration/http_live.rs`:
|
||||
|
||||
- `explicit_run_streams_sse_accepted_running_and_terminal_with_verified_trace`:
|
||||
accepted → running → succeeded;`id` 严格递增且与 `data.seq` 一致;终态含
|
||||
CLI result 与 `trace.status=verified` 事件;
|
||||
- `last_event_id_replays_only_newer_events_and_old_cursor_gets_snapshot`:重放
|
||||
只发更新事件;伪造游标得权威 snapshot;
|
||||
- `cancel_is_idempotent_and_yields_one_terminal_state`:两次 cancel 均 200,
|
||||
SSE 只有一个 `cancelled` 终态且 <8s 结束;
|
||||
- `sse_heartbeats_keep_a_slow_job_connected`:长任务期间收到 `: heartbeat`,
|
||||
任务仍成功;
|
||||
- `at_most_two_sse_observers_per_run`:第 3 个观察连接 429;
|
||||
- `duplicate_request_id_is_idempotent_and_busy_or_conflict_never_starts_a_second_process`:
|
||||
同 ID 同 body → 同 run_id;busy/conflict → 409,不启第二进程;
|
||||
- `sse_and_cancel_are_scoped_to_the_owning_session`:跨会话读取/取消 404;
|
||||
- `document_without_main_is_rejected_without_running_another_function`:400
|
||||
`view.no_entry_function` 且无 run 调用。
|
||||
|
||||
## 3. 浏览器(真实 Chromium 131,七套视图宽度)
|
||||
|
||||
`browser.log` 为 `MARQDO_BIN=062cb56e… scripts/test-browser.sh` 的真实输出,
|
||||
三个项目全部 PASS,包括:
|
||||
|
||||
- run 对话框 → 命令预览 → 确认 → **SSE 终态 succeeded**(无整页重载);
|
||||
- 运行区、Trace 事件列表、stdout 文本、原文 `.mq-run-chip` 锚点;
|
||||
- 请求记录中没有状态轮询 API;
|
||||
- 清理隐藏运行区且不重载页面;
|
||||
- 2048×1133 / 1664×920 / 1440×900 / 1024×768 / 768×1024 / 390×844 无横向溢出、
|
||||
Dock 在视口内、无外部请求、无 console error、无 JS 可读、打印隐藏交互;
|
||||
- 深色/暖纸主题切换并持久化,无 unsafe-inline/eval。
|
||||
|
||||
截图:`welcome-2048x1133.png`、`control-flow-2048x1133.png`、
|
||||
`control-flow-390x844.png`、`control-flow-run.png`。
|
||||
|
||||
## 4. 真实冻结 CLI 端到端
|
||||
|
||||
`real-run.log`:启动 `target/release/marqdo-view examples/control-flow`(使用
|
||||
冻结 CLI),脚本 `scripts/acceptance-run.py` 完成 GET 页面 → POST /api/runs →
|
||||
读取 SSE 终态:`succeeded`、`trace.status=verified`、**285 条 Trace 事件**。
|
||||
截图与日志均来自该实现;CLI SHA 在前后保持不变。
|
||||
|
||||
## 5. 测试计数(本 PR 合并时)
|
||||
|
||||
```
|
||||
cargo test --locked --offline
|
||||
unit 63 + contract 41 + integration 40 + security 11 = 155 passed / 0 failed
|
||||
cargo clippy --all-targets --offline -- -D warnings # clean
|
||||
```
|
||||
|
||||
## 6. 已知边界
|
||||
|
||||
- 首版不提供 net/process/env/plugin/provider/kernel 授权 UI;请求会被拒绝并提示
|
||||
使用终端 CLI(`view.run_denied`/`view.run_invalid`)。
|
||||
- `project` 模式需要显式 read/write glob 并二次确认;它不是 OS 沙箱。
|
||||
- SSE 只推送 View 生命周期与终态数据,不推送逐字 stdout/Token 流(RFC §6.1)。
|
||||
@@ -0,0 +1,143 @@
|
||||
==> browser suite: examples/welcome
|
||||
ok reader root rendered
|
||||
ok document title has Marqdo
|
||||
ok one stylesheet
|
||||
ok one script
|
||||
ok no external requests
|
||||
ok no browser console errors
|
||||
ok dock has all actions
|
||||
ok dock run control present
|
||||
ok interactive controls have accessible names
|
||||
ok Tab reaches named controls
|
||||
ok more dialog opens
|
||||
ok source mode attribute
|
||||
ok source pane visible
|
||||
ok document hidden in source mode
|
||||
ok document mode restored
|
||||
ok search dialog opens
|
||||
ok search returns local results
|
||||
ok text size toggled
|
||||
ok annotations toggled
|
||||
ok welcome hero only on configured page
|
||||
ok grammar statement is a real element
|
||||
ok GFM table rendered
|
||||
ok dark theme applied
|
||||
ok theme preference persisted
|
||||
ok paper theme restored
|
||||
ok no horizontal overflow at 2048
|
||||
ok dock inside viewport at 2048
|
||||
ok no horizontal overflow at 1664
|
||||
ok dock inside viewport at 1664
|
||||
ok no horizontal overflow at 1440
|
||||
ok dock inside viewport at 1440
|
||||
ok no horizontal overflow at 1024
|
||||
ok dock inside viewport at 1024
|
||||
ok no horizontal overflow at 768
|
||||
ok dock inside viewport at 768
|
||||
ok no horizontal overflow at 390
|
||||
ok dock inside viewport at 390
|
||||
ok no-JS document remains readable
|
||||
ok no-JS exposes no active run UI
|
||||
ok print hides dock
|
||||
ok print keeps prose
|
||||
|
||||
browser: PASS
|
||||
==> browser suite: examples/control-flow
|
||||
ok reader root rendered
|
||||
ok document title has Marqdo
|
||||
ok one stylesheet
|
||||
ok one script
|
||||
ok no external requests
|
||||
ok no browser console errors
|
||||
ok dock has all actions
|
||||
ok dock run control present
|
||||
ok interactive controls have accessible names
|
||||
ok Tab reaches named controls
|
||||
ok more dialog opens
|
||||
ok source mode attribute
|
||||
ok source pane visible
|
||||
ok document hidden in source mode
|
||||
ok document mode restored
|
||||
ok search dialog opens
|
||||
ok search returns local results
|
||||
ok text size toggled
|
||||
ok annotations toggled
|
||||
ok dark theme applied
|
||||
ok theme preference persisted
|
||||
ok paper theme restored
|
||||
ok no horizontal overflow at 2048
|
||||
ok dock inside viewport at 2048
|
||||
ok no horizontal overflow at 1664
|
||||
ok dock inside viewport at 1664
|
||||
ok no horizontal overflow at 1440
|
||||
ok dock inside viewport at 1440
|
||||
ok no horizontal overflow at 1024
|
||||
ok dock inside viewport at 1024
|
||||
ok no horizontal overflow at 768
|
||||
ok dock inside viewport at 768
|
||||
ok no horizontal overflow at 390
|
||||
ok dock inside viewport at 390
|
||||
ok no-JS document remains readable
|
||||
ok no-JS exposes no active run UI
|
||||
ok print hides dock
|
||||
ok print keeps prose
|
||||
ok run dialog opens
|
||||
ok run dialog mentions pure mode
|
||||
ok run dialog previews the command
|
||||
ok run state succeeded via SSE
|
||||
ok run panel visible
|
||||
ok run chips anchored
|
||||
ok trace event list rendered
|
||||
ok stdout rendered escaped
|
||||
ok no polling API was used
|
||||
ok clear hides run panel
|
||||
ok page was never reloaded by the run
|
||||
|
||||
browser: PASS
|
||||
==> browser suite: tests/fixtures/security-project
|
||||
ok reader root rendered
|
||||
ok document title has Marqdo
|
||||
ok one stylesheet
|
||||
ok one script
|
||||
ok no external requests
|
||||
ok no browser console errors
|
||||
ok dock has all actions
|
||||
ok dock run control present
|
||||
ok interactive controls have accessible names
|
||||
ok Tab reaches named controls
|
||||
ok more dialog opens
|
||||
ok source mode attribute
|
||||
ok source pane visible
|
||||
ok document hidden in source mode
|
||||
ok document mode restored
|
||||
ok search dialog opens
|
||||
ok search returns local results
|
||||
ok text size toggled
|
||||
ok annotations toggled
|
||||
ok adversarial doc has no alert dialog
|
||||
ok adversarial doc has no external requests
|
||||
ok raw HTML omitted note rendered
|
||||
ok prose survives sanitization
|
||||
ok javascript link neutralized
|
||||
ok dark theme applied
|
||||
ok theme preference persisted
|
||||
ok paper theme restored
|
||||
ok no horizontal overflow at 2048
|
||||
ok dock inside viewport at 2048
|
||||
ok no horizontal overflow at 1664
|
||||
ok dock inside viewport at 1664
|
||||
ok no horizontal overflow at 1440
|
||||
ok dock inside viewport at 1440
|
||||
ok no horizontal overflow at 1024
|
||||
ok dock inside viewport at 1024
|
||||
ok no horizontal overflow at 768
|
||||
ok dock inside viewport at 768
|
||||
ok no horizontal overflow at 390
|
||||
ok dock inside viewport at 390
|
||||
ok no-JS document remains readable
|
||||
ok no-JS exposes no active run UI
|
||||
ok print hides dock
|
||||
ok print keeps prose
|
||||
|
||||
browser: PASS
|
||||
browser: PASS (core sha256 062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f unchanged; screenshots: /root/work/marqdo-view/tests/browser/artifacts)
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 119 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 67 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 105 KiB |
@@ -0,0 +1 @@
|
||||
explicit real run: PASS (run_id=918359e1f4f5fd5155c86e6e55854b2c events=285)
|
||||
@@ -0,0 +1,7 @@
|
||||
marqdo view: http://127.0.0.1:40487/
|
||||
root: /root/work/marqdo-view/examples/control-flow
|
||||
1 .mq.md document(s). Ctrl+C to stop.
|
||||
core: marqdo 3.0.0-beta.1 (Analysis v2, Trace v2)
|
||||
run: explicit only (pure by default, one active job, 30s wall clock)
|
||||
JOB_DEBUG id=918359e1f4f5fd5155c86e6e55854b2c run_core elapsed=61.583791ms cancel=false
|
||||
JOB_DEBUG id=918359e1f4f5fd5155c86e6e55854b2c terminal state=Succeeded total=67.878533ms
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 187 KiB |
Executable
+81
@@ -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
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -46,6 +46,8 @@ pub enum ViewError {
|
||||
RunInvalid { detail: String },
|
||||
/// The entry document has no resolvable `main`; View never substitutes one.
|
||||
NoEntryFunction { detail: String },
|
||||
/// A page/SSE/POST requires a valid local session cookie.
|
||||
SessionRequired { detail: String },
|
||||
/// Another explicit run is already active; View allows one at a time.
|
||||
RunBusy { detail: String },
|
||||
/// The same client request id was reused with a different payload.
|
||||
@@ -85,6 +87,7 @@ impl ViewError {
|
||||
ViewError::CoreTimeout { .. } => "view.core_timeout",
|
||||
ViewError::RunInvalid { .. } => "view.run_invalid",
|
||||
ViewError::NoEntryFunction { .. } => "view.no_entry_function",
|
||||
ViewError::SessionRequired { .. } => "view.session_required",
|
||||
ViewError::RunBusy { .. } => "view.run_busy",
|
||||
ViewError::RunConflict { .. } => "view.run_conflict",
|
||||
ViewError::RunNotFound { .. } => "view.run_not_found",
|
||||
@@ -107,6 +110,7 @@ impl ViewError {
|
||||
| ViewError::Unsupported { .. }
|
||||
| ViewError::RunInvalid { .. }
|
||||
| ViewError::NoEntryFunction { .. }
|
||||
| ViewError::SessionRequired { .. }
|
||||
| ViewError::RunBusy { .. }
|
||||
| ViewError::RunConflict { .. }
|
||||
| ViewError::RunNotFound { .. }
|
||||
@@ -152,6 +156,7 @@ impl ViewError {
|
||||
"view.core_timeout" => "冻结核心执行超时,已终止。",
|
||||
"view.run_invalid" => "运行请求未通过校验(目标、参数、模式或授权不合法)。",
|
||||
"view.no_entry_function" => "文档没有可调用的 main;请改选一个 H2 Exec 函数。",
|
||||
"view.session_required" => "缺少或过期的本地会话;请先打开阅读页面。",
|
||||
"view.run_busy" => "已有一次运行正在进行;本版本每个 View 服务只允许一个任务。",
|
||||
"view.run_conflict" => "同一客户端请求 ID 携带了不同内容,拒绝执行。",
|
||||
"view.run_not_found" => "运行任务不存在、已过期或不属于当前会话。",
|
||||
@@ -204,6 +209,7 @@ impl ViewError {
|
||||
| ViewError::CoreTimeout { detail }
|
||||
| ViewError::RunInvalid { detail }
|
||||
| ViewError::NoEntryFunction { detail }
|
||||
| ViewError::SessionRequired { detail }
|
||||
| ViewError::RunBusy { detail }
|
||||
| ViewError::RunConflict { detail }
|
||||
| ViewError::RunNotFound { detail }
|
||||
|
||||
@@ -284,6 +284,11 @@ impl ExecutionController {
|
||||
let started = Instant::now();
|
||||
let outcome = self.run_core(&job, &plan);
|
||||
let cancel_requested = job.cancel.load(Ordering::SeqCst);
|
||||
eprintln!(
|
||||
"JOB_DEBUG id={} run_core elapsed={:?} cancel={cancel_requested}",
|
||||
job.run_id,
|
||||
started.elapsed()
|
||||
);
|
||||
let terminal = self.build_terminal(&plan, &static_doc, started, outcome, cancel_requested);
|
||||
let Ok(mut inner) = job.inner.lock() else {
|
||||
return;
|
||||
@@ -308,6 +313,12 @@ impl ExecutionController {
|
||||
);
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"JOB_DEBUG id={} terminal state={:?} total={:?}",
|
||||
job.run_id,
|
||||
state,
|
||||
started.elapsed()
|
||||
);
|
||||
inner.terminal_at = Some(Instant::now());
|
||||
drop(inner);
|
||||
|
||||
@@ -548,6 +559,7 @@ impl ExecutionController {
|
||||
detail: "job lock poisoned".to_string(),
|
||||
})?;
|
||||
let state_now = inner.log.last_state();
|
||||
eprintln!("CANCEL_DEBUG id={} last_state={state_now:?}", job.run_id);
|
||||
if state_now.is_terminal() {
|
||||
return Ok(state_now);
|
||||
}
|
||||
@@ -902,10 +914,27 @@ fn build_trace_summary(
|
||||
}
|
||||
};
|
||||
let projection = verified.projection;
|
||||
let statements = static_doc.verified.projection.all_statements();
|
||||
let events = projection
|
||||
.events
|
||||
.iter()
|
||||
.map(|event| {
|
||||
let source_id = if stale {
|
||||
None
|
||||
} else {
|
||||
event.anchor_span.and_then(|span| {
|
||||
statements
|
||||
.iter()
|
||||
.find(|(_, statement)| statement.span == span)
|
||||
.map(|(_, statement)| {
|
||||
crate::protocol::analysis_v2::source_id(
|
||||
&static_doc.verified.projection.module_id,
|
||||
span,
|
||||
&format!("statement-{}", statement.kind.data_value()),
|
||||
)
|
||||
})
|
||||
})
|
||||
};
|
||||
serde_json::json!({
|
||||
"seq": event.seq,
|
||||
"kind": event.kind_label(),
|
||||
@@ -916,6 +945,7 @@ fn build_trace_summary(
|
||||
event.anchor_span.map(|span| serde_json::json!({"start": span.start, "end": span.end}))
|
||||
.unwrap_or(serde_json::Value::Null)
|
||||
},
|
||||
"source_id": source_id,
|
||||
"detail": event.detail,
|
||||
"operation": event.operation,
|
||||
"duration_micros": event.duration_micros,
|
||||
|
||||
+2
-70
@@ -13,12 +13,10 @@ use crate::reader::model::{
|
||||
};
|
||||
use crate::reader::source::{sha256_hex, Project, SafeRelativePath};
|
||||
|
||||
use crate::core_client::{
|
||||
CheckOptions, CheckResponse, CoreClient, RawCheckDiagnostic, RunOptions, SandboxMode,
|
||||
};
|
||||
use crate::core_client::{CheckOptions, CheckResponse, CoreClient, RawCheckDiagnostic};
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use crate::protocol::analysis_v2;
|
||||
use crate::protocol::trace_v2::{self, TraceVerificationInput};
|
||||
use crate::protocol::trace_v2;
|
||||
use crate::reader::model::{anchor_for_span, PRESENTATION_VERSION};
|
||||
|
||||
/// Input to the one builder. `analysis` is already protocol/byte verified.
|
||||
@@ -326,72 +324,6 @@ impl DocumentService {
|
||||
run: attached_run.as_ref(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Execute one document through the public Core `run` channel after the
|
||||
/// caller has obtained explicit user confirmation and a CSRF token. Never
|
||||
/// called from page loads or exports.
|
||||
pub fn run_document(&self, relative: &SafeRelativePath) -> ViewResult<ExecutedRun> {
|
||||
let client = self.core.as_ref().ok_or_else(|| ViewError::RunDenied {
|
||||
detail: "没有可用的冻结核心(MARQDO_BIN),运行被拒绝".to_string(),
|
||||
})?;
|
||||
let source_bytes = self.project.read_source(relative)?;
|
||||
let source_digest = crate::reader::source::sha256_hex(&source_bytes);
|
||||
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
|
||||
detail: format!("{relative} is not valid UTF-8: {err}"),
|
||||
})?;
|
||||
let source_index = crate::reader::source::SourceIndex::new(&source);
|
||||
|
||||
let run = client.run(
|
||||
&self.project,
|
||||
relative,
|
||||
&RunOptions {
|
||||
mode: SandboxMode::Pure,
|
||||
view_timeout: Some(std::time::Duration::from_secs(120)),
|
||||
timeout_seconds: Some(90),
|
||||
..Default::default()
|
||||
},
|
||||
)?;
|
||||
let trace_bytes = run
|
||||
.trace_bytes
|
||||
.clone()
|
||||
.ok_or_else(|| ViewError::RunDenied {
|
||||
detail: "Core 未写出 Trace v2 文件,运行结果不可绑定".to_string(),
|
||||
})?;
|
||||
|
||||
// Re-check after the run so the digest binds to the exact Analysis of
|
||||
// the source that was executed and is still current.
|
||||
let response = client.check(&self.project, relative, &CheckOptions::default())?;
|
||||
let check = response.analysis.ok_or_else(|| ViewError::AnalysisFailed {
|
||||
detail: "运行后的静态检查失败,无法绑定 Trace".to_string(),
|
||||
})?;
|
||||
let verified = analysis_v2::verify_analysis(
|
||||
&check.analysis_bytes,
|
||||
&source,
|
||||
&source_index,
|
||||
relative.as_str(),
|
||||
)?;
|
||||
let verified_run = trace_v2::verify_trace(TraceVerificationInput {
|
||||
trace_bytes: &trace_bytes,
|
||||
analysis_bytes: &check.analysis_bytes,
|
||||
semantic: &verified.projection,
|
||||
modules: &verified.projection.modules,
|
||||
source: &source,
|
||||
source_index: &source_index,
|
||||
run_json: &run.json,
|
||||
exit_code: run.exit_code,
|
||||
})?;
|
||||
Ok(ExecutedRun {
|
||||
verified: verified_run,
|
||||
source_digest,
|
||||
analysis_digest: check.analysis_digest,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ExecutedRun {
|
||||
pub verified: VerifiedRun,
|
||||
pub source_digest: String,
|
||||
pub analysis_digest: String,
|
||||
}
|
||||
|
||||
fn generic_core_note(err: &ViewError) -> String {
|
||||
|
||||
@@ -123,6 +123,19 @@ pub enum OutlineKind {
|
||||
}
|
||||
|
||||
impl PresentationModel {
|
||||
/// True when the entry module exposes a resolvable `main` (canonical or
|
||||
/// unique local name). The dock Run button never substitutes another
|
||||
/// function for a missing entry function (RFC-VIEW-0002 §2.4).
|
||||
pub fn has_entry_main(&self) -> bool {
|
||||
let Some(semantic) = self.semantic.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
semantic.functions.iter().any(|function| {
|
||||
let canonical = canonical_function_name(&function.id, &semantic.module_id);
|
||||
canonical == "main" || function.local_name == "main"
|
||||
})
|
||||
}
|
||||
|
||||
pub fn run_state(&self) -> RunDisplayState {
|
||||
match &self.run {
|
||||
Some(run) => run.state,
|
||||
@@ -165,6 +178,14 @@ pub fn anchor_for_span(start: u64, end: u64) -> String {
|
||||
format!("mq-h-{start:x}-{end:x}")
|
||||
}
|
||||
|
||||
/// Analysis v2 function ids are `<module id>::<canonical name>`.
|
||||
fn canonical_function_name(function_id: &str, module_id: &str) -> String {
|
||||
function_id
|
||||
.strip_prefix(&format!("{module_id}::"))
|
||||
.unwrap_or(function_id)
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
+115
-30
@@ -71,6 +71,10 @@ pub struct RenderContext {
|
||||
pub run_available: bool,
|
||||
/// Static exports may hide semantic/run annotations without changing prose.
|
||||
pub annotations: bool,
|
||||
/// View wall-clock limit shown in the explicit run form (seconds).
|
||||
pub run_timeout_secs: u64,
|
||||
/// Whether a frozen Core was negotiated (an explicit run form can exist).
|
||||
pub core_available: bool,
|
||||
}
|
||||
|
||||
impl RenderContext {
|
||||
@@ -81,6 +85,8 @@ impl RenderContext {
|
||||
csrf_token: None,
|
||||
run_available: false,
|
||||
annotations: true,
|
||||
run_timeout_secs: 30,
|
||||
core_available: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,6 +97,8 @@ impl RenderContext {
|
||||
csrf_token: None,
|
||||
run_available: false,
|
||||
annotations: true,
|
||||
run_timeout_secs: 0,
|
||||
core_available: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +144,13 @@ impl ReaderRenderer {
|
||||
);
|
||||
let _ = document_href;
|
||||
let mut html = String::with_capacity(16 * 1024 + model.document.source.len());
|
||||
let relative_path = model.document.identity.relative_path.clone();
|
||||
let analysis_digest = model
|
||||
.semantic
|
||||
.as_ref()
|
||||
.map(|semantic| semantic.analysis_digest.clone())
|
||||
.unwrap_or_default();
|
||||
let has_main = model.has_entry_main();
|
||||
let page_title = if navigation.site_title.is_empty() {
|
||||
model.title.clone()
|
||||
} else {
|
||||
@@ -156,7 +171,7 @@ impl ReaderRenderer {
|
||||
<link rel="stylesheet" href="{css}"/>
|
||||
<script defer src="{js}"></script>
|
||||
</head>
|
||||
<body class="mq-reader" data-mode="document" data-theme="light" data-annotations="{annotations}" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-live="{live}">
|
||||
<body class="mq-reader" data-mode="document" data-theme="light" data-annotations="{annotations}" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-has-main="{has_main}" data-core-available="{core_available}" data-document="{document}" data-analysis-digest="{analysis_digest}" data-run-timeout="{run_timeout}" data-live="{live}">
|
||||
<a class="mq-skip" href="#mq-main">跳到正文</a>
|
||||
"##,
|
||||
presentation_version = model.version,
|
||||
@@ -170,6 +185,11 @@ impl ReaderRenderer {
|
||||
annotations = if ctx.annotations { "on" } else { "off" },
|
||||
run_state = model.run_state().data_value(),
|
||||
run_available = if ctx.run_available { "true" } else { "false" },
|
||||
has_main = if has_main { "true" } else { "false" },
|
||||
core_available = if ctx.core_available { "true" } else { "false" },
|
||||
document = escape_attr(&relative_path),
|
||||
analysis_digest = escape_attr(&analysis_digest),
|
||||
run_timeout = ctx.run_timeout_secs,
|
||||
live = if ctx.live { "true" } else { "false" },
|
||||
);
|
||||
|
||||
@@ -182,9 +202,13 @@ impl ReaderRenderer {
|
||||
}
|
||||
self.render_document_meta(&mut html, model);
|
||||
self.render_diagnostics(&mut html, model);
|
||||
self.render_functions(&mut html, model);
|
||||
self.render_functions(&mut html, model, ctx);
|
||||
self.render_document(&mut html, model, ctx);
|
||||
self.render_run_panel(&mut html, model, ctx);
|
||||
if ctx.live {
|
||||
self.render_live_run_shell(&mut html, ctx);
|
||||
} else {
|
||||
self.render_run_panel(&mut html, model, ctx);
|
||||
}
|
||||
self.render_source_pane(&mut html, model, ctx);
|
||||
self.render_footer(&mut html, model);
|
||||
let _ = write!(html, "</main>\n");
|
||||
@@ -361,7 +385,7 @@ impl ReaderRenderer {
|
||||
html.push_str("</ol>\n</details>\n");
|
||||
}
|
||||
|
||||
fn render_functions(&self, html: &mut String, model: &PresentationModel) {
|
||||
fn render_functions(&self, html: &mut String, model: &PresentationModel, ctx: &RenderContext) {
|
||||
if model.outline.is_empty() {
|
||||
return;
|
||||
}
|
||||
@@ -375,12 +399,33 @@ impl ReaderRenderer {
|
||||
count = functions.len()
|
||||
);
|
||||
for entry in functions {
|
||||
let function = model.semantic.as_ref().and_then(|semantic| {
|
||||
semantic.functions.iter().find(|function| {
|
||||
anchor_for_span(function.heading_span.start, function.heading_span.end)
|
||||
== entry.anchor
|
||||
})
|
||||
});
|
||||
let (function_id, params, callable) = match function {
|
||||
Some(function) => (function.id.clone(), function_params_json(function), true),
|
||||
None => (String::new(), "[]".to_string(), false),
|
||||
};
|
||||
let call_button = if callable && ctx.core_available {
|
||||
format!(
|
||||
"<button type=\"button\" class=\"mq-fn-call\" data-action=\"call-function\" data-function-id=\"{id}\" data-function-label=\"{label}\" data-params=\"{params}\">调用</button>",
|
||||
id = escape_attr(&function_id),
|
||||
label = escape_attr(&entry.label),
|
||||
params = escape_attr(¶ms)
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let _ = write!(
|
||||
html,
|
||||
"<li><a href=\"#{anchor}\" data-goto-anchor=\"{anchor}\">{label}</a><span class=\"mq-fn-sig\">{detail}</span></li>\n",
|
||||
"<li><a href=\"#{anchor}\" data-goto-anchor=\"{anchor}\">{label}</a><span class=\"mq-fn-sig\">{detail}</span>{call_button}</li>\n",
|
||||
anchor = escape_attr(&entry.anchor),
|
||||
label = escape_text(&entry.label),
|
||||
detail = escape_text(&entry.detail)
|
||||
detail = escape_text(&entry.detail),
|
||||
call_button = call_button
|
||||
);
|
||||
}
|
||||
html.push_str("</ul>\n</details>\n");
|
||||
@@ -457,8 +502,32 @@ impl ReaderRenderer {
|
||||
);
|
||||
}
|
||||
|
||||
/// Empty, accessible run panel that the single reader script fills from
|
||||
/// SSE events. It is never populated by the server for a live page: no run
|
||||
/// exists until the user explicitly submits one (RFC-VIEW-0002 §7.1).
|
||||
fn render_live_run_shell(&self, html: &mut String, _ctx: &RenderContext) {
|
||||
html.push_str(
|
||||
r##"<section class="mq-run-panel" id="mq-run-panel" data-run-state="idle" aria-labelledby="mq-run-title" hidden>
|
||||
<h2 id="mq-run-title">本次运行</h2>
|
||||
<p id="mq-run-status" class="mq-run-status" role="status" aria-live="polite">尚未运行。点击 Dock 的“运行”执行 main,或在函数面板选择函数。</p>
|
||||
<div id="mq-run-actions" class="mq-run-actions" hidden>
|
||||
<button type="button" class="mq-secondary" data-action="cancel-run">取消运行</button>
|
||||
</div>
|
||||
<div id="mq-run-summary"></div>
|
||||
<pre id="mq-run-stdout" class="mq-stdout" aria-label="程序标准输出" hidden></pre>
|
||||
<pre id="mq-run-stderr" class="mq-stdout mq-stderr" aria-label="程序标准错误" hidden></pre>
|
||||
<details id="mq-run-trace-wrap" class="mq-run-events-wrap" hidden>
|
||||
<summary>真实 Trace v2 事件</summary>
|
||||
<ol id="mq-run-events" class="mq-run-events"></ol>
|
||||
</details>
|
||||
<p id="mq-run-note" class="mq-colophon">结果只来自本次显式运行的 CLI --json 与经摘要校验的 Trace v2;不提供参数实际值、逐语句变量或内存快照。</p>
|
||||
</section>
|
||||
"##,
|
||||
);
|
||||
}
|
||||
|
||||
fn render_dock(&self, html: &mut String, ctx: &RenderContext) {
|
||||
let run_disabled = if ctx.run_available {
|
||||
let run_disabled = if ctx.core_available {
|
||||
""
|
||||
} else {
|
||||
" data-disabled=\"true\""
|
||||
@@ -544,8 +613,8 @@ impl ReaderRenderer {
|
||||
"##,
|
||||
csrf = csrf,
|
||||
files = self.render_file_list(model, ctx),
|
||||
run_dialog = if ctx.run_available {
|
||||
render_run_confirm_dialog(model)
|
||||
run_dialog = if ctx.core_available {
|
||||
render_run_form_dialog(model, ctx)
|
||||
} else {
|
||||
String::new()
|
||||
},
|
||||
@@ -1346,32 +1415,48 @@ fn render_run_chips(html: &mut String, model: &PresentationModel, statement_span
|
||||
);
|
||||
}
|
||||
|
||||
fn render_run_confirm_dialog(model: &PresentationModel) -> String {
|
||||
let function = model
|
||||
.semantic
|
||||
.as_ref()
|
||||
.and_then(|semantic| {
|
||||
semantic
|
||||
.functions
|
||||
.iter()
|
||||
.find(|function| function.local_name == "main")
|
||||
})
|
||||
.map(|function| function.local_name.clone())
|
||||
.unwrap_or_else(|| "main".to_string());
|
||||
fn function_params_json(function: &crate::protocol::analysis_v2::SemanticFunction) -> String {
|
||||
serde_json::json!(function
|
||||
.signature
|
||||
.params
|
||||
.iter()
|
||||
.map(|param| serde_json::json!({
|
||||
"name": param.name,
|
||||
"type": param.ty,
|
||||
"required": param.required,
|
||||
"default": param.default,
|
||||
}))
|
||||
.collect::<Vec<_>>())
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn render_run_form_dialog(model: &PresentationModel, ctx: &RenderContext) -> String {
|
||||
let path = &model.document.identity.relative_path;
|
||||
format!(
|
||||
r##"<dialog class="mq-dialog" id="mq-dialog-run-confirm" aria-labelledby="mq-run-confirm-title" data-path="{path}">
|
||||
<div class="mq-dialog-head"><h2 id="mq-run-confirm-title">确认运行本文档</h2><button type="button" class="mq-icon-btn mq-close" data-action="close-dialog" aria-label="取消运行">×</button></div>
|
||||
<p>即将通过冻结核心执行入口函数 <code>{function}</code>,沙箱模式 <code>pure</code>(无文件、网络、环境变量、进程权限)。</p>
|
||||
<p>等价命令:<code>marqdo run {path} --mode pure --json --trace-file <临时文件></code></p>
|
||||
<p>运行会在你的机器上真实执行文档中的 <code>@exec</code> 代码。Trace v2 不记录参数实际值、文件内容或敏感数据;View 不继承项目声明的 capabilities。</p>
|
||||
<p class="mq-colophon">打开、刷新、搜索、导出都不会触发运行;只有本确认按钮会。</p>
|
||||
r##"<dialog class="mq-dialog mq-run-dialog" id="mq-dialog-run" aria-labelledby="mq-run-dialog-title" data-path="{path}" data-timeout="{timeout}">
|
||||
<div class="mq-dialog-head"><h2 id="mq-run-dialog-title">显式运行</h2><button type="button" class="mq-icon-btn mq-close" data-action="close-dialog" aria-label="取消运行">×</button></div>
|
||||
<p class="mq-run-target"><span id="mq-run-target-label">入口 main</span> · <span id="mq-run-target-mode">pure</span></p>
|
||||
<div id="mq-run-params" class="mq-run-params"></div>
|
||||
<fieldset class="mq-run-mode">
|
||||
<legend>执行模式</legend>
|
||||
<label><input type="radio" name="mq-mode" value="pure" checked/> pure(默认:无文件/网络/环境/进程权限)</label>
|
||||
<label><input type="radio" name="mq-mode" value="project"/> project(受控项目权限,需逐项确认)</label>
|
||||
</fieldset>
|
||||
<div id="mq-run-grants" class="mq-run-grants" hidden>
|
||||
<p class="mq-run-warning" role="note">project 模式不是 OS 沙箱。只允许相对项目根的 fs read/write glob;网络、进程、环境、插件等权限不在首版 UI 中,必须改用终端 CLI。</p>
|
||||
<label>允许读取(read glob,每行一个)<textarea id="mq-grant-read" rows="2" spellcheck="false" placeholder="data/**"></textarea></label>
|
||||
<label>允许写入(write glob,每行一个)<textarea id="mq-grant-write" rows="2" spellcheck="false" placeholder="out/*.txt"></textarea></label>
|
||||
</div>
|
||||
<p class="mq-colophon">等价命令(点击“确认执行”后才会运行;<code><参数值></code> 由下方输入原样作为常量表达式提交):</p>
|
||||
<pre class="mq-run-command" id="mq-run-command" aria-label="命令预览"></pre>
|
||||
<p class="mq-colophon">墙钟上限 {timeout} 秒;结果通过 SSE 推送,不轮询。打开/刷新/导出不会执行。</p>
|
||||
<div class="mq-dialog-actions">
|
||||
<button type="button" class="mq-secondary" data-action="close-dialog">取消</button>
|
||||
<button type="button" class="mq-primary" data-action="run-confirm">确认运行(pure)</button>
|
||||
<button type="button" class="mq-primary" data-action="run-confirm">确认执行</button>
|
||||
</div>
|
||||
</dialog>
|
||||
"##,
|
||||
function = escape_text(&function),
|
||||
path = escape_text(&model.document.identity.relative_path)
|
||||
path = escape_attr(path),
|
||||
timeout = ctx.run_timeout_secs
|
||||
)
|
||||
}
|
||||
-1105
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,122 @@
|
||||
//! Local single-user Live server.
|
||||
//!
|
||||
//! Loopback-only, fixed minimal routes, one explicit execution entry. The
|
||||
//! server module contains no business engine: pages come from the one Reader,
|
||||
//! run jobs from the ExecutionController, and SSE only transports already
|
||||
//! sequenced View events (RFC-VIEW-0002 §5.1).
|
||||
|
||||
pub mod routes;
|
||||
pub mod security;
|
||||
pub mod sse;
|
||||
|
||||
use crate::cli::RuntimeOpts;
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use crate::execution::controller::{ExecutionConfig, ExecutionController};
|
||||
use crate::reader::assemble::DocumentService;
|
||||
use crate::reader::render::ReaderRenderer;
|
||||
use routes::ServerState;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tiny_http::Server;
|
||||
|
||||
pub fn serve(service: DocumentService, opts: &RuntimeOpts) -> ViewResult<i32> {
|
||||
let address = format!("{}:{}", opts.host, opts.port);
|
||||
let server = Server::http(&address).map_err(|err| ViewError::Io {
|
||||
detail: format!("listen on {address}: {err}"),
|
||||
})?;
|
||||
let bound = server.server_addr().to_ip().ok_or_else(|| ViewError::Io {
|
||||
detail: "server address is not an IP socket".to_string(),
|
||||
})?;
|
||||
let port = bound.port();
|
||||
let display_host = match opts.host.as_str() {
|
||||
"localhost" => "localhost".to_string(),
|
||||
"::1" | "[::1]" => "[::1]".to_string(),
|
||||
_ => "127.0.0.1".to_string(),
|
||||
};
|
||||
let url = format!("http://{display_host}:{port}/");
|
||||
|
||||
let service = Arc::new(service);
|
||||
let controller = Arc::new(ExecutionController::new(
|
||||
Arc::clone(&service),
|
||||
ExecutionConfig::default().with_timeout(opts.run_timeout_secs),
|
||||
));
|
||||
let state = Arc::new(ServerState {
|
||||
service,
|
||||
controller,
|
||||
renderer: ReaderRenderer::new(),
|
||||
cache: Mutex::new(HashMap::new()),
|
||||
security: crate::server::security::SecurityState::new(port),
|
||||
active_requests: AtomicUsize::new(0),
|
||||
});
|
||||
|
||||
eprintln!("marqdo view: {url}");
|
||||
eprintln!("root: {}", state.service.project().root().display());
|
||||
eprintln!(
|
||||
"{} .mq.md document(s). Ctrl+C to stop.",
|
||||
state
|
||||
.service
|
||||
.project()
|
||||
.list_documents()
|
||||
.map(|documents| documents.len())
|
||||
.unwrap_or(0)
|
||||
);
|
||||
if let Some(version) = state.service.core_version() {
|
||||
eprintln!("core: marqdo {version} (Analysis v2, Trace v2)");
|
||||
} else if let Some(note) = state.service.core_note() {
|
||||
eprintln!("core: unavailable ({note})");
|
||||
}
|
||||
eprintln!(
|
||||
"run: explicit only (pure by default, one active job, {}s wall clock)",
|
||||
opts.run_timeout_secs
|
||||
);
|
||||
if !opts.no_open {
|
||||
open_browser(&url);
|
||||
}
|
||||
|
||||
loop {
|
||||
let request = match server.recv() {
|
||||
Ok(request) => request,
|
||||
Err(err) => {
|
||||
eprintln!("view: accept failed: {err}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let active = state.active_requests.fetch_add(1, Ordering::SeqCst);
|
||||
if active >= 48 {
|
||||
state.active_requests.fetch_sub(1, Ordering::SeqCst);
|
||||
let _ = request.respond(tiny_http::Response::empty(503));
|
||||
continue;
|
||||
}
|
||||
let state = Arc::clone(&state);
|
||||
std::thread::spawn(move || {
|
||||
let result = routes::handle(&state, request);
|
||||
state.active_requests.fetch_sub(1, Ordering::SeqCst);
|
||||
if let Err(err) = result {
|
||||
eprintln!("view request error: {err}");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn open_browser(url: &str) {
|
||||
let program = if cfg!(target_os = "macos") {
|
||||
"open"
|
||||
} else if cfg!(target_os = "windows") {
|
||||
"cmd"
|
||||
} else {
|
||||
"xdg-open"
|
||||
};
|
||||
let mut command = std::process::Command::new(program);
|
||||
if cfg!(target_os = "windows") {
|
||||
command.args(["/C", "start", ""]);
|
||||
}
|
||||
command.arg(url);
|
||||
command
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null());
|
||||
if command.spawn().is_err() {
|
||||
eprintln!("view: could not open a browser; open {url} manually");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,691 @@
|
||||
//! The fixed minimal HTTP route table (RFC-VIEW-0002 §6.2).
|
||||
//!
|
||||
//! | route | executes? |
|
||||
//! |---|---|
|
||||
//! | `GET /` | no |
|
||||
//! | `GET /file?path=...` | no |
|
||||
//! | `GET /assets/...` | no |
|
||||
//! | `GET /api/documents` | no |
|
||||
//! | `POST /api/runs` | **yes — the only execution entry** |
|
||||
//! | `GET /api/runs/{id}/events` | no (observe only) |
|
||||
//! | `POST /api/runs/{id}/cancel` | no (control of an existing job) |
|
||||
//!
|
||||
//! Anything else is 404. Page loads, refreshes, searches, document switches and
|
||||
//! the static export path can never form an execution edge.
|
||||
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use crate::execution::controller::ExecutionController;
|
||||
use crate::reader::assemble::DocumentService;
|
||||
use crate::reader::assets::AssetBundle;
|
||||
use crate::reader::model::PresentationModel;
|
||||
use crate::reader::render::{ReaderRenderer, RenderContext};
|
||||
use crate::reader::source::{sha256_hex, SafeRelativePath};
|
||||
use crate::server::security::{
|
||||
header, SecurityState, MAX_POST_BODY_BYTES, MAX_QUERY_BYTES, MAX_URL_BYTES,
|
||||
};
|
||||
use crate::server::sse;
|
||||
use std::collections::HashMap;
|
||||
use std::io::Read;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tiny_http::{Header, Method, Request, Response, StatusCode};
|
||||
|
||||
pub struct ServerState {
|
||||
pub service: Arc<DocumentService>,
|
||||
pub controller: Arc<ExecutionController>,
|
||||
pub renderer: ReaderRenderer,
|
||||
pub cache: Mutex<HashMap<String, CacheEntry>>,
|
||||
pub security: SecurityState,
|
||||
pub active_requests: AtomicUsize,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CacheEntry {
|
||||
source_digest: String,
|
||||
model: PresentationModel,
|
||||
}
|
||||
|
||||
impl ServerState {
|
||||
/// Load one document, reusing a cached model only while the exact source
|
||||
/// bytes are unchanged. This path performs the read-only `check` only.
|
||||
pub fn load(&self, relative: &SafeRelativePath) -> ViewResult<PresentationModel> {
|
||||
let digest = self.service.project().source_digest(relative)?;
|
||||
if let Ok(cache) = self.cache.lock() {
|
||||
if let Some(entry) = cache.get(relative.as_str()) {
|
||||
if entry.source_digest == digest {
|
||||
return Ok(entry.model.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let model = self.service.load(relative)?;
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
if cache.len() < 64 {
|
||||
cache.insert(
|
||||
relative.as_str().to_string(),
|
||||
CacheEntry {
|
||||
source_digest: digest,
|
||||
model: model.clone(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(model)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle(state: &ServerState, request: Request) -> ViewResult<()> {
|
||||
let method = request.method().clone();
|
||||
let raw_url = request.url().to_string();
|
||||
if raw_url.len() > MAX_URL_BYTES {
|
||||
return respond_text(
|
||||
request,
|
||||
StatusCode(414),
|
||||
"request target too long\n",
|
||||
CacheKind::NoStore,
|
||||
);
|
||||
}
|
||||
let (path, query) = split_url(&raw_url);
|
||||
if query.len() > MAX_QUERY_BYTES {
|
||||
return respond_text(
|
||||
request,
|
||||
StatusCode(414),
|
||||
"query too long\n",
|
||||
CacheKind::NoStore,
|
||||
);
|
||||
}
|
||||
if let Err(err) = state.security.check_host(&request) {
|
||||
return respond_error(request, StatusCode(400), &err);
|
||||
}
|
||||
|
||||
let is_get = method == Method::Get || method == Method::Head;
|
||||
if is_get {
|
||||
if let Some(hashed_name) = path.strip_prefix("/assets/") {
|
||||
return serve_asset(request, hashed_name);
|
||||
}
|
||||
if path == "/" || path == "/index.html" {
|
||||
return serve_page(state, request, None);
|
||||
}
|
||||
if path == "/file" {
|
||||
return serve_file(state, request, query);
|
||||
}
|
||||
if path == "/api/documents" {
|
||||
return serve_documents(state, request, query);
|
||||
}
|
||||
if let Some(run_id) = matched_run_route(path, "/events") {
|
||||
return serve_events(state, request, run_id);
|
||||
}
|
||||
return respond_text(request, StatusCode(404), "not found\n", CacheKind::NoStore);
|
||||
}
|
||||
|
||||
if method == Method::Post {
|
||||
if path == "/api/runs" {
|
||||
return submit_run(state, request);
|
||||
}
|
||||
if let Some(run_id) = matched_run_route(path, "/cancel") {
|
||||
return cancel_run(state, request, run_id);
|
||||
}
|
||||
return respond_text(
|
||||
request,
|
||||
StatusCode(405),
|
||||
"method not allowed\n",
|
||||
CacheKind::NoStore,
|
||||
);
|
||||
}
|
||||
respond_text(
|
||||
request,
|
||||
StatusCode(405),
|
||||
"method not allowed\n",
|
||||
CacheKind::NoStore,
|
||||
)
|
||||
}
|
||||
|
||||
/// Match `/api/runs/<id><suffix>` without accepting nested paths.
|
||||
fn matched_run_route<'a>(path: &'a str, suffix: &str) -> Option<&'a str> {
|
||||
let rest = path.strip_prefix("/api/runs/")?;
|
||||
let run_id = rest.strip_suffix(suffix)?;
|
||||
if run_id.is_empty()
|
||||
|| run_id.len() > 128
|
||||
|| !run_id
|
||||
.chars()
|
||||
.all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_')
|
||||
|| path.contains("//")
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(run_id)
|
||||
}
|
||||
|
||||
fn serve_page(
|
||||
state: &ServerState,
|
||||
request: Request,
|
||||
relative: Option<SafeRelativePath>,
|
||||
) -> ViewResult<()> {
|
||||
let relative = match relative {
|
||||
Some(relative) => relative,
|
||||
None => state.service.project().entry().relative.clone(),
|
||||
};
|
||||
let model = match state.load(&relative) {
|
||||
Ok(model) => model,
|
||||
Err(err) => return serve_error_page(request, &err),
|
||||
};
|
||||
let (session, set_cookie) = state.security.page_session(&request);
|
||||
let ctx = RenderContext {
|
||||
links: crate::reader::render::LinkPolicy::LocalServer,
|
||||
live: true,
|
||||
csrf_token: Some(session.csrf),
|
||||
run_available: state.service.core().is_some() && model.can_offer_run(),
|
||||
annotations: true,
|
||||
run_timeout_secs: state.controller.config().run_timeout_secs(),
|
||||
core_available: state.service.core().is_some(),
|
||||
};
|
||||
let page = state.renderer.render(&model, &ctx);
|
||||
let mut headers = Vec::new();
|
||||
if let Some(cookie) = set_cookie {
|
||||
if let Ok(header) = Header::from_bytes(&b"Set-Cookie"[..], cookie.as_bytes()) {
|
||||
headers.push(header);
|
||||
}
|
||||
}
|
||||
respond_bytes(
|
||||
request,
|
||||
StatusCode(200),
|
||||
"text/html; charset=utf-8",
|
||||
page.html.into_bytes(),
|
||||
CacheKind::NoStore,
|
||||
headers,
|
||||
)
|
||||
}
|
||||
|
||||
fn serve_file(state: &ServerState, request: Request, query: &str) -> ViewResult<()> {
|
||||
let Some(raw_path) = query_param(query, "path") else {
|
||||
return respond_text(
|
||||
request,
|
||||
StatusCode(400),
|
||||
"missing path\n",
|
||||
CacheKind::NoStore,
|
||||
);
|
||||
};
|
||||
let Some(decoded) = percent_decode(&raw_path) else {
|
||||
return respond_text(
|
||||
request,
|
||||
StatusCode(400),
|
||||
"malformed path\n",
|
||||
CacheKind::NoStore,
|
||||
);
|
||||
};
|
||||
let relative = match SafeRelativePath::parse(&decoded) {
|
||||
Ok(relative) => relative,
|
||||
Err(err) => {
|
||||
return respond_text(
|
||||
request,
|
||||
StatusCode(403),
|
||||
&format!("{}\n", err.code()),
|
||||
CacheKind::NoStore,
|
||||
)
|
||||
}
|
||||
};
|
||||
if state.service.project().read_source(&relative).is_err() {
|
||||
return respond_text(
|
||||
request,
|
||||
StatusCode(404),
|
||||
"document not found\n",
|
||||
CacheKind::NoStore,
|
||||
);
|
||||
}
|
||||
serve_page(state, request, Some(relative))
|
||||
}
|
||||
|
||||
fn serve_documents(state: &ServerState, request: Request, query: &str) -> ViewResult<()> {
|
||||
if let Err(err) = state.security.check_same_origin(&request) {
|
||||
return respond_error(request, StatusCode(403), &err);
|
||||
}
|
||||
let relative = match query_param(query, "path").and_then(|raw| percent_decode(&raw)) {
|
||||
Some(decoded) => match SafeRelativePath::parse(&decoded) {
|
||||
Ok(relative) => relative,
|
||||
Err(err) => return respond_error(request, StatusCode(400), &err),
|
||||
},
|
||||
None => state.service.project().entry().relative.clone(),
|
||||
};
|
||||
let model = match state.load(&relative) {
|
||||
Ok(model) => model,
|
||||
Err(err) => return respond_error(request, StatusCode(500), &err),
|
||||
};
|
||||
let semantic = model.semantic.as_ref();
|
||||
let documents = state
|
||||
.service
|
||||
.project()
|
||||
.list_documents()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|path| {
|
||||
serde_json::json!({
|
||||
"path": path.as_str(),
|
||||
"active": path == relative,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let functions = model
|
||||
.outline
|
||||
.iter()
|
||||
.filter(|entry| entry.kind == crate::reader::model::OutlineKind::Function)
|
||||
.map(|entry| {
|
||||
serde_json::json!({
|
||||
"label": entry.label,
|
||||
"anchor": entry.anchor,
|
||||
"detail": entry.detail,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let doc = serde_json::json!({
|
||||
"schema": "marqdo.view-documents",
|
||||
"schema_version": 1,
|
||||
"entry": state.service.project().entry().relative.as_str(),
|
||||
"documents": documents,
|
||||
"current": {
|
||||
"relative_path": model.document.identity.relative_path,
|
||||
"module_id": model.document.identity.module_id,
|
||||
"title": model.title,
|
||||
"source_sha256": sha256_hex(model.document.source.as_bytes()),
|
||||
"source_status": model.source_status.data_value(),
|
||||
"semantics_usable": model.source_status.semantics_usable(),
|
||||
"analysis": semantic.map(|projection| serde_json::json!({
|
||||
"schema_version": crate::protocol::tool_v1::ANALYSIS_PROTOCOL,
|
||||
"digest": projection.analysis_digest,
|
||||
"producer_version": projection.producer_version,
|
||||
"project_root_id": projection.project_root_id,
|
||||
"functions": projection.functions.len(),
|
||||
"units": projection.units.len(),
|
||||
"diagnostics": projection.diagnostics.len(),
|
||||
})),
|
||||
"outline": model.outline.iter().map(|entry| serde_json::json!({
|
||||
"label": entry.label,
|
||||
"anchor": entry.anchor,
|
||||
"detail": entry.detail,
|
||||
"kind": match entry.kind {
|
||||
crate::reader::model::OutlineKind::Function => "function",
|
||||
crate::reader::model::OutlineKind::Knowledge => "knowledge",
|
||||
crate::reader::model::OutlineKind::Section => "section",
|
||||
},
|
||||
})).collect::<Vec<_>>(),
|
||||
"functions": functions,
|
||||
"can_offer_run": model.can_offer_run(),
|
||||
},
|
||||
"note": "Read-only document structure; this request never executes the document.",
|
||||
});
|
||||
respond_json(request, StatusCode(200), &doc)
|
||||
}
|
||||
|
||||
/// The only execution entry in the whole product.
|
||||
fn submit_run(state: &ServerState, mut request: Request) -> ViewResult<()> {
|
||||
let session = match state.security.authenticate_post(&request) {
|
||||
Ok(session) => session,
|
||||
Err(err) => return respond_error(request, status_for(&err), &err),
|
||||
};
|
||||
let body = match read_body(&mut request, MAX_POST_BODY_BYTES) {
|
||||
Ok(body) => body,
|
||||
Err(err) => {
|
||||
let status = match err.code() {
|
||||
"view.resource_limit" | "view.output_limit" => StatusCode(413),
|
||||
_ => status_for(&err),
|
||||
};
|
||||
return respond_error(request, status, &err);
|
||||
}
|
||||
};
|
||||
match state.controller.submit(&session.id, &body) {
|
||||
Ok(accepted) => respond_json(
|
||||
request,
|
||||
StatusCode(202),
|
||||
&serde_json::json!({
|
||||
"schema": "marqdo.view-run-accepted",
|
||||
"schema_version": 1,
|
||||
"run_id": accepted.run_id,
|
||||
"state": accepted.state.data_value(),
|
||||
"events_url": accepted.events_url,
|
||||
"cancel_url": accepted.cancel_url,
|
||||
"reused": accepted.reused,
|
||||
}),
|
||||
),
|
||||
Err(err) => respond_error(request, status_for(&err), &err),
|
||||
}
|
||||
}
|
||||
|
||||
fn serve_events(state: &ServerState, request: Request, run_id: &str) -> ViewResult<()> {
|
||||
let session = match state.security.require_session(&request) {
|
||||
Ok(session) => session,
|
||||
Err(err) => return respond_error(request, status_for(&err), &err),
|
||||
};
|
||||
if let Err(err) = state.security.check_same_origin(&request) {
|
||||
return respond_error(request, StatusCode(403), &err);
|
||||
}
|
||||
let last_event_id =
|
||||
header(&request, "Last-Event-ID").and_then(|value| value.parse::<u64>().ok());
|
||||
match state
|
||||
.controller
|
||||
.subscribe(&session.id, run_id, last_event_id)
|
||||
{
|
||||
Ok(subscription) => sse::respond(request, subscription),
|
||||
Err(err) => respond_error(request, status_for(&err), &err),
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_run(state: &ServerState, request: Request, run_id: &str) -> ViewResult<()> {
|
||||
let session = match state.security.authenticate_control(&request) {
|
||||
Ok(session) => session,
|
||||
Err(err) => return respond_error(request, status_for(&err), &err),
|
||||
};
|
||||
match state.controller.cancel(&session.id, run_id) {
|
||||
Ok(state_value) => respond_json(
|
||||
request,
|
||||
StatusCode(200),
|
||||
&serde_json::json!({
|
||||
"schema": "marqdo.view-run-cancel",
|
||||
"schema_version": 1,
|
||||
"run_id": run_id,
|
||||
"state": state_value.data_value(),
|
||||
}),
|
||||
),
|
||||
Err(err) => respond_error(request, status_for(&err), &err),
|
||||
}
|
||||
}
|
||||
|
||||
fn serve_asset(request: Request, hashed_name: &str) -> ViewResult<()> {
|
||||
let bundle = AssetBundle::get();
|
||||
if hashed_name == bundle.hashed_css_name() {
|
||||
return respond_bytes(
|
||||
request,
|
||||
StatusCode(200),
|
||||
"text/css; charset=utf-8",
|
||||
bundle.css_bytes().to_vec(),
|
||||
CacheKind::Immutable,
|
||||
Vec::new(),
|
||||
);
|
||||
}
|
||||
let Some(asset) = bundle.by_path(hashed_name) else {
|
||||
return respond_text(
|
||||
request,
|
||||
StatusCode(404),
|
||||
"asset not found\n",
|
||||
CacheKind::NoStore,
|
||||
);
|
||||
};
|
||||
respond_bytes(
|
||||
request,
|
||||
StatusCode(200),
|
||||
asset.mime,
|
||||
asset.bytes.to_vec(),
|
||||
CacheKind::Immutable,
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
|
||||
fn serve_error_page(request: Request, err: &ViewError) -> ViewResult<()> {
|
||||
let html = format!(
|
||||
"<!DOCTYPE html><html lang=\"zh-CN\"><head><meta charset=\"utf-8\"/><title>Marqdo View · 错误</title><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/></head><body><main><h1>无法生成阅读页面</h1><p><code>{code}</code></p><p>{message}</p><p><a href=\"/\">返回入口</a></p></main></body></html>",
|
||||
code = escape_html(err.code()),
|
||||
message = escape_html(err.public_message()),
|
||||
);
|
||||
respond_html(request, html.into_bytes())
|
||||
}
|
||||
|
||||
fn status_for(err: &ViewError) -> StatusCode {
|
||||
match err.code() {
|
||||
"view.session_required" => StatusCode(401),
|
||||
"view.run_denied" => StatusCode(403),
|
||||
"view.run_invalid" | "view.no_entry_function" => StatusCode(400),
|
||||
"view.run_busy" | "view.run_conflict" => StatusCode(409),
|
||||
"view.run_not_found" => StatusCode(404),
|
||||
"view.sse_busy" | "view.resource_limit" => StatusCode(429),
|
||||
"view.output_limit" => StatusCode(413),
|
||||
"view.analysis_failed" => StatusCode(422),
|
||||
"view.core_missing" | "view.core_spawn" => StatusCode(503),
|
||||
"view.core_timeout" => StatusCode(504),
|
||||
"view.protocol_incompatible" | "view.core_protocol" => StatusCode(502),
|
||||
"view.unsupported" => StatusCode(415),
|
||||
_ => StatusCode(500),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_body(request: &mut Request, max: usize) -> Result<Vec<u8>, ViewError> {
|
||||
let mut body = Vec::new();
|
||||
let mut reader = request.as_reader().take(max as u64 + 1);
|
||||
reader.read_to_end(&mut body).map_err(|err| ViewError::Io {
|
||||
detail: format!("read request body: {err}"),
|
||||
})?;
|
||||
if body.len() > max {
|
||||
return Err(ViewError::ResourceLimit {
|
||||
detail: format!("request body above {max} bytes"),
|
||||
});
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
enum CacheKind {
|
||||
NoStore,
|
||||
Immutable,
|
||||
}
|
||||
|
||||
fn respond_html(request: Request, body: Vec<u8>) -> ViewResult<()> {
|
||||
respond_bytes(
|
||||
request,
|
||||
StatusCode(200),
|
||||
"text/html; charset=utf-8",
|
||||
body,
|
||||
CacheKind::NoStore,
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
|
||||
fn respond_text(
|
||||
request: Request,
|
||||
status: StatusCode,
|
||||
body: &str,
|
||||
cache: CacheKind,
|
||||
) -> ViewResult<()> {
|
||||
respond_bytes(
|
||||
request,
|
||||
status,
|
||||
"text/plain; charset=utf-8",
|
||||
body.as_bytes().to_vec(),
|
||||
cache,
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
|
||||
fn respond_json(request: Request, status: StatusCode, value: &serde_json::Value) -> ViewResult<()> {
|
||||
let body = serde_json::to_vec_pretty(value).unwrap_or_else(|_| b"{}".to_vec());
|
||||
respond_bytes(
|
||||
request,
|
||||
status,
|
||||
"application/json; charset=utf-8",
|
||||
body,
|
||||
CacheKind::NoStore,
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
|
||||
fn respond_error(request: Request, status: StatusCode, err: &ViewError) -> ViewResult<()> {
|
||||
let mut headers = Vec::new();
|
||||
if let Ok(header) =
|
||||
Header::from_bytes(&b"WWW-Authenticate"[..], b"Session realm=\"marqdo-view\"")
|
||||
{
|
||||
if err.code() == "view.run_denied" && status.0 == 401 {
|
||||
headers.push(header);
|
||||
}
|
||||
}
|
||||
let value = serde_json::json!({
|
||||
"schema": "marqdo.view-error",
|
||||
"schema_version": 1,
|
||||
"code": err.code(),
|
||||
"source": "view",
|
||||
"message": err.public_message(),
|
||||
});
|
||||
let body = serde_json::to_vec_pretty(&value).unwrap_or_else(|_| b"{}".to_vec());
|
||||
respond_bytes(
|
||||
request,
|
||||
status,
|
||||
"application/json; charset=utf-8",
|
||||
body,
|
||||
CacheKind::NoStore,
|
||||
headers,
|
||||
)
|
||||
}
|
||||
|
||||
fn respond_bytes(
|
||||
request: Request,
|
||||
status: StatusCode,
|
||||
content_type: &str,
|
||||
body: Vec<u8>,
|
||||
cache: CacheKind,
|
||||
extra_headers: Vec<Header>,
|
||||
) -> ViewResult<()> {
|
||||
let mut response = Response::from_data(body).with_status_code(status);
|
||||
if let Ok(header) = Header::from_bytes(&b"Content-Type"[..], content_type.as_bytes()) {
|
||||
response.add_header(header);
|
||||
}
|
||||
for (name, value) in crate::server::security::security_headers() {
|
||||
if let Ok(header) = Header::from_bytes(name.as_bytes(), value.as_bytes()) {
|
||||
response.add_header(header);
|
||||
}
|
||||
}
|
||||
let cache_value = match cache {
|
||||
CacheKind::NoStore => "no-store",
|
||||
CacheKind::Immutable => "public, max-age=31536000, immutable",
|
||||
};
|
||||
if let Ok(header) = Header::from_bytes(&b"Cache-Control"[..], cache_value.as_bytes()) {
|
||||
response.add_header(header);
|
||||
}
|
||||
for header in extra_headers {
|
||||
response.add_header(header);
|
||||
}
|
||||
request.respond(response).map_err(|err| ViewError::Io {
|
||||
detail: format!("write response: {err}"),
|
||||
})
|
||||
}
|
||||
|
||||
fn split_url(url: &str) -> (&str, &str) {
|
||||
match url.split_once('?') {
|
||||
Some((path, query)) => (path, query),
|
||||
None => (url, ""),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn query_param(query: &str, key: &str) -> Option<String> {
|
||||
for pair in query.split('&') {
|
||||
let (name, value) = match pair.split_once('=') {
|
||||
Some(parts) => parts,
|
||||
None => (pair, ""),
|
||||
};
|
||||
if name == key {
|
||||
return Some(value.to_string());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Decode `%XX` exactly once; reject malformed escapes, NUL, controls and
|
||||
/// non-UTF-8 results.
|
||||
pub fn percent_decode(raw: &str) -> Option<String> {
|
||||
let bytes = raw.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut index = 0;
|
||||
while index < bytes.len() {
|
||||
match bytes[index] {
|
||||
b'%' => {
|
||||
if index + 2 >= bytes.len() {
|
||||
return None;
|
||||
}
|
||||
let high = hex_value(*bytes.get(index + 1)?)?;
|
||||
let low = hex_value(*bytes.get(index + 2)?)?;
|
||||
out.push(high * 16 + low);
|
||||
index += 3;
|
||||
}
|
||||
b'+' => {
|
||||
out.push(b'+');
|
||||
index += 1;
|
||||
}
|
||||
byte => {
|
||||
out.push(byte);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if out.contains(&0) || out.iter().any(|byte| *byte < 0x20 || *byte == 0x7f) {
|
||||
return None;
|
||||
}
|
||||
String::from_utf8(out).ok()
|
||||
}
|
||||
|
||||
fn hex_value(byte: u8) -> Option<u8> {
|
||||
match byte {
|
||||
b'0'..=b'9' => Some(byte - b'0'),
|
||||
b'a'..=b'f' => Some(byte - b'a' + 10),
|
||||
b'A'..=b'F' => Some(byte - b'A' + 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn escape_html(raw: &str) -> String {
|
||||
let mut out = String::with_capacity(raw.len());
|
||||
for ch in raw.chars() {
|
||||
match ch {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
_ => out.push(ch),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn run_route_matching_is_strict() {
|
||||
assert_eq!(
|
||||
matched_run_route("/api/runs/abc/events", "/events"),
|
||||
Some("abc")
|
||||
);
|
||||
assert_eq!(
|
||||
matched_run_route("/api/runs/abc/cancel", "/cancel"),
|
||||
Some("abc")
|
||||
);
|
||||
assert_eq!(matched_run_route("/api/runs//events", "/events"), None);
|
||||
assert_eq!(matched_run_route("/api/runs/a/b/events", "/events"), None);
|
||||
assert_eq!(matched_run_route("/api/runs/abc/events/", "/events"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn percent_decode_is_single_pass_and_strict() {
|
||||
assert_eq!(percent_decode("a%20b").as_deref(), Some("a b"));
|
||||
assert_eq!(percent_decode("100%25").as_deref(), Some("100%"));
|
||||
assert_eq!(percent_decode("a+b").as_deref(), Some("a+b"));
|
||||
assert!(percent_decode("%zz").is_none());
|
||||
assert!(percent_decode("a%00b").is_none());
|
||||
assert!(percent_decode("%ff").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_mapping_covers_execution_errors() {
|
||||
assert_eq!(
|
||||
status_for(&ViewError::RunBusy {
|
||||
detail: String::new()
|
||||
}),
|
||||
StatusCode(409)
|
||||
);
|
||||
assert_eq!(
|
||||
status_for(&ViewError::RunNotFound {
|
||||
detail: String::new()
|
||||
}),
|
||||
StatusCode(404)
|
||||
);
|
||||
assert_eq!(
|
||||
status_for(&ViewError::RunDenied {
|
||||
detail: String::new()
|
||||
}),
|
||||
StatusCode(403)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
//! Local-session, CSRF, Origin/Host and response-header security.
|
||||
//!
|
||||
//! The Live server is loopback-only but still guards the one execution endpoint
|
||||
//! (RFC-VIEW-0002 §6.8): an HttpOnly `SameSite=Strict` session cookie, a
|
||||
//! per-session CSRF token required as `X-View-CSRF`, an exact same-origin
|
||||
//! `Origin`, a valid loopback `Host`, JSON-only bounded POSTs and a strict CSP.
|
||||
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
use tiny_http::Request;
|
||||
|
||||
pub const SESSION_COOKIE: &str = "mq_view_session";
|
||||
pub const CSRF_HEADER: &str = "X-View-CSRF";
|
||||
pub const MAX_SESSIONS: usize = 64;
|
||||
pub const SESSION_TTL: Duration = Duration::from_secs(12 * 60 * 60);
|
||||
pub const MAX_POST_BODY_BYTES: usize = 64 * 1024;
|
||||
pub const MAX_URL_BYTES: usize = 2048;
|
||||
pub const MAX_QUERY_BYTES: usize = 4096;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SessionView {
|
||||
pub id: String,
|
||||
pub csrf: String,
|
||||
}
|
||||
|
||||
struct Session {
|
||||
csrf: String,
|
||||
last_seen: Instant,
|
||||
}
|
||||
|
||||
pub struct SecurityState {
|
||||
sessions: Mutex<HashMap<String, Session>>,
|
||||
allowed_hosts: Vec<String>,
|
||||
origin: String,
|
||||
}
|
||||
|
||||
impl SecurityState {
|
||||
pub fn new(port: u16) -> Self {
|
||||
let host = format!("127.0.0.1:{port}");
|
||||
Self {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
allowed_hosts: vec![host.clone(), format!("localhost:{port}")],
|
||||
origin: format!("http://{host}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn allowed_hosts(&self) -> &[String] {
|
||||
&self.allowed_hosts
|
||||
}
|
||||
|
||||
/// Validate `Host` for every request (DNS-rebinding defence).
|
||||
pub fn check_host(&self, request: &Request) -> ViewResult<()> {
|
||||
let host = header(request, "Host").ok_or_else(|| ViewError::RunDenied {
|
||||
detail: "missing Host header".to_string(),
|
||||
})?;
|
||||
if self
|
||||
.allowed_hosts
|
||||
.iter()
|
||||
.any(|allowed| allowed.eq_ignore_ascii_case(host.trim()))
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ViewError::RunDenied {
|
||||
detail: "invalid Host header".to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Browser page load: reuse a valid cookie or mint a new session. Returns
|
||||
/// the session plus the `Set-Cookie` value when a new one was created.
|
||||
pub fn page_session(&self, request: &Request) -> (SessionView, Option<String>) {
|
||||
let now = Instant::now();
|
||||
let mut sessions = self
|
||||
.sessions
|
||||
.lock()
|
||||
.unwrap_or_else(|poison| poison.into_inner());
|
||||
sessions.retain(|_, session| now.duration_since(session.last_seen) < SESSION_TTL);
|
||||
if let Some(id) = cookie_value(request, SESSION_COOKIE) {
|
||||
if let Some(session) = sessions.get_mut(&id) {
|
||||
session.last_seen = now;
|
||||
return (
|
||||
SessionView {
|
||||
id,
|
||||
csrf: session.csrf.clone(),
|
||||
},
|
||||
None,
|
||||
);
|
||||
}
|
||||
}
|
||||
let id = random_hex(32);
|
||||
let csrf = random_hex(32);
|
||||
sessions.insert(
|
||||
id.clone(),
|
||||
Session {
|
||||
csrf: csrf.clone(),
|
||||
last_seen: now,
|
||||
},
|
||||
);
|
||||
while sessions.len() > MAX_SESSIONS {
|
||||
let oldest = sessions
|
||||
.iter()
|
||||
.min_by_key(|(_, session)| session.last_seen)
|
||||
.map(|(id, _)| id.clone());
|
||||
match oldest {
|
||||
Some(id) => {
|
||||
sessions.remove(&id);
|
||||
}
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
let cookie =
|
||||
format!("{SESSION_COOKIE}={id}; HttpOnly; SameSite=Strict; Path=/; Max-Age=43200");
|
||||
(SessionView { id, csrf }, Some(cookie))
|
||||
}
|
||||
|
||||
/// Authenticated GET (page/SSE): an existing session cookie is required.
|
||||
pub fn require_session(&self, request: &Request) -> ViewResult<SessionView> {
|
||||
let id =
|
||||
cookie_value(request, SESSION_COOKIE).ok_or_else(|| ViewError::SessionRequired {
|
||||
detail: "缺少本地会话 Cookie;请刷新阅读页面后重试".to_string(),
|
||||
})?;
|
||||
let now = Instant::now();
|
||||
let mut sessions = self
|
||||
.sessions
|
||||
.lock()
|
||||
.unwrap_or_else(|poison| poison.into_inner());
|
||||
let session = sessions
|
||||
.get_mut(&id)
|
||||
.ok_or_else(|| ViewError::SessionRequired {
|
||||
detail: "本地会话已过期;请刷新阅读页面".to_string(),
|
||||
})?;
|
||||
if now.duration_since(session.last_seen) >= SESSION_TTL {
|
||||
sessions.remove(&id);
|
||||
return Err(ViewError::SessionRequired {
|
||||
detail: "本地会话已过期;请刷新阅读页面".to_string(),
|
||||
});
|
||||
}
|
||||
session.last_seen = now;
|
||||
Ok(SessionView {
|
||||
id,
|
||||
csrf: session.csrf.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Authenticated JSON POST (run submission).
|
||||
pub fn authenticate_post(&self, request: &Request) -> ViewResult<SessionView> {
|
||||
self.authenticate_post_impl(request, true)
|
||||
}
|
||||
|
||||
/// Authenticated control POST without a JSON body (cancel is a bare POST).
|
||||
pub fn authenticate_control(&self, request: &Request) -> ViewResult<SessionView> {
|
||||
self.authenticate_post_impl(request, false)
|
||||
}
|
||||
|
||||
fn authenticate_post_impl(
|
||||
&self,
|
||||
request: &Request,
|
||||
require_json: bool,
|
||||
) -> ViewResult<SessionView> {
|
||||
self.check_host(request)?;
|
||||
let origin = header(request, "Origin").ok_or_else(|| ViewError::RunDenied {
|
||||
detail: "缺少 Origin,跨站来源被拒绝".to_string(),
|
||||
})?;
|
||||
if !origin
|
||||
.trim_end_matches('/')
|
||||
.eq_ignore_ascii_case(&self.origin)
|
||||
{
|
||||
return Err(ViewError::RunDenied {
|
||||
detail: "Origin 与本地服务不一致,跨站请求被拒绝".to_string(),
|
||||
});
|
||||
}
|
||||
if let Some(site) = header(request, "Sec-Fetch-Site") {
|
||||
if site.eq_ignore_ascii_case("cross-site") {
|
||||
return Err(ViewError::RunDenied {
|
||||
detail: "Sec-Fetch-Site 表示跨站请求,已拒绝".to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
if require_json
|
||||
&& !header(request, "Content-Type")
|
||||
.map(|value| value.to_ascii_lowercase().starts_with("application/json"))
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err(ViewError::Unsupported {
|
||||
detail: "运行请求必须是 application/json".to_string(),
|
||||
});
|
||||
}
|
||||
let session = self.require_session(request)?;
|
||||
let csrf = header(request, CSRF_HEADER).ok_or_else(|| ViewError::RunDenied {
|
||||
detail: "缺少 X-View-CSRF,运行被拒绝".to_string(),
|
||||
})?;
|
||||
if !constant_time_eq(csrf.as_bytes(), session.csrf.as_bytes()) {
|
||||
return Err(ViewError::RunDenied {
|
||||
detail: "X-View-CSRF 无效,运行被拒绝".to_string(),
|
||||
});
|
||||
}
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// Origin check for read-only JSON APIs (no CSRF needed, no state change).
|
||||
pub fn check_same_origin(&self, request: &Request) -> ViewResult<()> {
|
||||
if let Some(origin) = header(request, "Origin") {
|
||||
if !origin
|
||||
.trim_end_matches('/')
|
||||
.eq_ignore_ascii_case(&self.origin)
|
||||
{
|
||||
return Err(ViewError::RunDenied {
|
||||
detail: "跨站读取被拒绝".to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn header(request: &Request, name: &'static str) -> Option<String> {
|
||||
request
|
||||
.headers()
|
||||
.iter()
|
||||
.find(|header| header.field.equiv(name))
|
||||
.map(|header| header.value.as_str().trim().to_string())
|
||||
}
|
||||
|
||||
pub fn cookie_value(request: &Request, name: &str) -> Option<String> {
|
||||
let raw = header(request, "Cookie")?;
|
||||
for pair in raw.split(';') {
|
||||
let (key, value) = pair.split_once('=')?;
|
||||
if key.trim() == name {
|
||||
let value = value.trim();
|
||||
if !value.is_empty()
|
||||
&& value
|
||||
.chars()
|
||||
.all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_')
|
||||
{
|
||||
return Some(value.to_string());
|
||||
}
|
||||
return None;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
|
||||
if left.len() != right.len() {
|
||||
return false;
|
||||
}
|
||||
let mut diff = 0u8;
|
||||
for (a, b) in left.iter().zip(right.iter()) {
|
||||
diff |= a ^ b;
|
||||
}
|
||||
diff == 0
|
||||
}
|
||||
|
||||
/// Random lowercase hex from `/dev/urandom` (with a non-constant fallback).
|
||||
pub fn random_hex(bytes: usize) -> String {
|
||||
let mut buffer = vec![0u8; bytes];
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::io::Read as _;
|
||||
if let Ok(mut file) = std::fs::File::open("/dev/urandom") {
|
||||
if file.read_exact(&mut buffer).is_ok() {
|
||||
return hex_encode(&buffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
let thread = format!("{:?}", std::thread::current().id());
|
||||
let material = format!(
|
||||
"{}-{}-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|duration| duration.as_nanos())
|
||||
.unwrap_or(0),
|
||||
thread,
|
||||
fallback_counter()
|
||||
);
|
||||
crate::reader::source::sha256_hex(material.as_bytes())[..bytes * 2].to_string()
|
||||
}
|
||||
|
||||
fn fallback_counter() -> u64 {
|
||||
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn hex_encode(bytes: &[u8]) -> String {
|
||||
let mut out = String::with_capacity(bytes.len() * 2);
|
||||
for byte in bytes {
|
||||
use std::fmt::Write as _;
|
||||
let _ = write!(out, "{byte:02x}");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// HTTP security headers for every response (RFC-VIEW-0002 §6.8).
|
||||
pub fn security_headers() -> Vec<(&'static str, &'static str)> {
|
||||
vec![
|
||||
(
|
||||
"Content-Security-Policy",
|
||||
"default-src 'self'; connect-src 'self'; style-src 'self'; script-src 'self'; img-src 'self' data:; font-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'",
|
||||
),
|
||||
("X-Content-Type-Options", "nosniff"),
|
||||
("Referrer-Policy", "no-referrer"),
|
||||
("X-Frame-Options", "DENY"),
|
||||
("Cross-Origin-Resource-Policy", "same-origin"),
|
||||
("Cross-Origin-Opener-Policy", "same-origin"),
|
||||
("Cache-Control", "no-store"),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn constant_time_eq_is_strict() {
|
||||
assert!(constant_time_eq(b"abc", b"abc"));
|
||||
assert!(!constant_time_eq(b"abc", b"abd"));
|
||||
assert!(!constant_time_eq(b"abc", b"ab"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_tokens_are_lower_hex_and_unique() {
|
||||
let a = random_hex(32);
|
||||
let b = random_hex(32);
|
||||
assert_eq!(a.len(), 64);
|
||||
assert_ne!(a, b);
|
||||
assert!(a.chars().all(|ch| ch.is_ascii_hexdigit()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_cookie_is_parsed_from_a_real_request() {
|
||||
let request: tiny_http::Request = tiny_http::TestRequest::new()
|
||||
.with_header(
|
||||
tiny_http::Header::from_bytes(
|
||||
&b"Cookie"[..],
|
||||
&b"a=b; mq_view_session=ok_1; other=x"[..],
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.into();
|
||||
assert_eq!(
|
||||
cookie_value(&request, SESSION_COOKIE).as_deref(),
|
||||
Some("ok_1")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! One-way SSE transport for View-owned run events.
|
||||
//!
|
||||
//! We write the HTTP response directly to the socket (via tiny_http's writer)
|
||||
//! instead of going through its buffered chunked writer: SSE requires each
|
||||
//! frame and heartbeat to be flushed immediately, not when a buffer fills.
|
||||
//! This module only transports already-sequenced events; it never queries the
|
||||
//! Core, starts work or implements a polling loop (RFC-VIEW-0002 §6.4/§6.5).
|
||||
|
||||
use crate::error::ViewResult;
|
||||
use crate::execution::controller::SseSubscription;
|
||||
use crate::execution::events::{HEARTBEAT_FRAME, HEARTBEAT_INTERVAL_SECS};
|
||||
use std::io::Write;
|
||||
use std::sync::mpsc::RecvTimeoutError;
|
||||
use std::time::{Duration, Instant};
|
||||
use tiny_http::Request;
|
||||
|
||||
pub fn heartbeat_interval() -> Duration {
|
||||
// Test/dev override only; production default is the RFC 15 seconds.
|
||||
if let Ok(raw) = std::env::var("MARQDO_VIEW_SSE_HEARTBEAT_SECS") {
|
||||
if let Ok(seconds) = raw.parse::<u64>() {
|
||||
if seconds > 0 {
|
||||
return Duration::from_secs(seconds);
|
||||
}
|
||||
}
|
||||
}
|
||||
Duration::from_secs(HEARTBEAT_INTERVAL_SECS)
|
||||
}
|
||||
|
||||
/// Send a `200 text/event-stream` response and block while the client observes
|
||||
/// it. Each frame is flushed immediately; the stream closes after the single
|
||||
/// terminal event so the browser never re-runs anything.
|
||||
pub fn respond(request: Request, subscription: SseSubscription) -> ViewResult<()> {
|
||||
let run_id = subscription.run_id.clone();
|
||||
let replay = subscription.replay.clone();
|
||||
let terminal = subscription.terminal;
|
||||
let receiver = subscription.receiver;
|
||||
let mut writer = request.into_writer();
|
||||
|
||||
let head = concat!(
|
||||
"HTTP/1.1 200 OK\r\n",
|
||||
"Content-Type: text/event-stream; charset=utf-8\r\n",
|
||||
"Cache-Control: no-store\r\n",
|
||||
"X-Accel-Buffering: no\r\n",
|
||||
"X-Content-Type-Options: nosniff\r\n",
|
||||
"Referrer-Policy: no-referrer\r\n",
|
||||
"Connection: close\r\n",
|
||||
"\r\n"
|
||||
);
|
||||
if write_frame(&mut writer, head.as_bytes()).is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
for frame in &replay {
|
||||
if write_frame(&mut writer, frame.as_bytes()).is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let _ = run_id;
|
||||
if terminal {
|
||||
let _ = writer.flush();
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let heartbeat = heartbeat_interval();
|
||||
let mut next_heartbeat = Instant::now() + heartbeat;
|
||||
loop {
|
||||
let now = Instant::now();
|
||||
let timeout = next_heartbeat.saturating_duration_since(now);
|
||||
match receiver.recv_timeout(timeout) {
|
||||
Ok(event) => {
|
||||
let is_terminal = event.state.is_terminal();
|
||||
let frame = event.to_sse(&subscription.run_id);
|
||||
if write_frame(&mut writer, frame.as_bytes()).is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
if is_terminal {
|
||||
let _ = writer.flush();
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
if write_frame(&mut writer, HEARTBEAT_FRAME.as_bytes()).is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
next_heartbeat = Instant::now() + heartbeat;
|
||||
}
|
||||
Err(RecvTimeoutError::Disconnected) => {
|
||||
let _ = writer.flush();
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if Instant::now() >= next_heartbeat {
|
||||
if write_frame(&mut writer, HEARTBEAT_FRAME.as_bytes()).is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
next_heartbeat = Instant::now() + heartbeat;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_frame(writer: &mut Box<dyn Write + Send + 'static>, frame: &[u8]) -> std::io::Result<()> {
|
||||
writer.write_all(frame)?;
|
||||
writer.flush()
|
||||
}
|
||||
|
||||
/// Kept as a named constant for the transport tests/documentation.
|
||||
pub fn headers() -> [(&'static str, &'static str); 4] {
|
||||
[
|
||||
("Content-Type", "text/event-stream; charset=utf-8"),
|
||||
("Cache-Control", "no-store"),
|
||||
("X-Accel-Buffering", "no"),
|
||||
("X-Content-Type-Options", "nosniff"),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn heartbeat_interval_is_fifteen_seconds_by_default() {
|
||||
std::env::remove_var("MARQDO_VIEW_SSE_HEARTBEAT_SECS");
|
||||
assert_eq!(heartbeat_interval(), Duration::from_secs(15));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headers_are_the_sse_contract() {
|
||||
let headers = headers();
|
||||
assert_eq!(headers[0].1, "text/event-stream; charset=utf-8");
|
||||
assert_eq!(headers[1].1, "no-store");
|
||||
assert_eq!(headers[2].1, "no");
|
||||
}
|
||||
}
|
||||
@@ -166,15 +166,28 @@ function localHostOnly(url) {
|
||||
check("GFM table rendered", (await page.locator(".mq-document table").count()) >= 1);
|
||||
}
|
||||
|
||||
// Simple theme switch (RFC §1.2 MVP SMALL) persists and stays readable.
|
||||
await page.click('.mq-dock-btn[data-action="settings"]');
|
||||
await page.click('#mq-dialog-settings [data-action="theme"]');
|
||||
check("dark theme applied", (await page.getAttribute("body", "data-theme")) === "dark");
|
||||
await page.reload({ waitUntil: "networkidle" });
|
||||
check(
|
||||
"theme preference persisted",
|
||||
(await page.getAttribute("body", "data-theme")) === "dark"
|
||||
);
|
||||
await page.click('.mq-dock-btn[data-action="settings"]');
|
||||
await page.click('#mq-dialog-settings [data-action="theme"]');
|
||||
check("paper theme restored", (await page.getAttribute("body", "data-theme")) === "light");
|
||||
|
||||
// Responsive geometry: no horizontal overflow; dock inside viewport.
|
||||
// RFC-VIEW-0002 §9.3 visual matrix: the source reference is 2048x1133.
|
||||
const widths = [
|
||||
[390, 844],
|
||||
[600, 800],
|
||||
[900, 768],
|
||||
[1280, 800],
|
||||
[2048, 1133],
|
||||
[1664, 920],
|
||||
[1920, 1080],
|
||||
[2560, 1440],
|
||||
[1440, 900],
|
||||
[1024, 768],
|
||||
[768, 1024],
|
||||
[390, 844],
|
||||
];
|
||||
for (const [width, height] of widths) {
|
||||
await page.setViewportSize({ width, height });
|
||||
@@ -206,7 +219,11 @@ function localHostOnly(url) {
|
||||
await nojsPage.goto(base, { waitUntil: "load" });
|
||||
const nojsText = await nojsPage.locator(".mq-document").innerText();
|
||||
check("no-JS document remains readable", nojsText.trim().length > 20);
|
||||
check("no-JS has no fake run panel", (await nojsPage.locator("#mq-run-panel").count()) === 0);
|
||||
check(
|
||||
"no-JS exposes no active run UI",
|
||||
!(await nojsPage.locator("#mq-run-panel").isVisible()) &&
|
||||
(await nojsPage.locator('.mq-dock-btn[data-action="run"]').count()) === 1
|
||||
);
|
||||
await nojs.close();
|
||||
|
||||
// Print hides chrome but keeps prose.
|
||||
@@ -219,31 +236,44 @@ function localHostOnly(url) {
|
||||
|
||||
// Explicit run flow, only against the control-flow example.
|
||||
if (projectName === "control-flow") {
|
||||
const runRequests = [];
|
||||
page.on("request", (request) => {
|
||||
if (request.url().includes("/api/runs")) runRequests.push(request.url());
|
||||
});
|
||||
await page.click('.mq-dock-btn[data-action="run"]');
|
||||
check("run confirm dialog opens", await page.locator("#mq-dialog-run-confirm").isVisible());
|
||||
const dialogText = await page.locator("#mq-dialog-run-confirm").innerText();
|
||||
check("confirm mentions pure mode", dialogText.includes("pure"));
|
||||
check("run dialog opens", await page.locator("#mq-dialog-run").isVisible());
|
||||
const dialogText = await page.locator("#mq-dialog-run").innerText();
|
||||
check("run dialog mentions pure mode", dialogText.includes("pure"));
|
||||
check(
|
||||
"run dialog previews the command",
|
||||
(await page.locator("#mq-run-command").innerText()).includes("marqdo run")
|
||||
);
|
||||
await page.click('[data-action="run-confirm"]');
|
||||
await page.waitForURL(/run=/, { timeout: 30000 });
|
||||
await page.waitForLoadState("networkidle");
|
||||
check("run state succeeded", (await page.getAttribute("body", "data-run-state")) === "succeeded");
|
||||
check("run panel rendered", await page.locator("#mq-run-panel").isVisible());
|
||||
await page.waitForSelector('body[data-run-state="succeeded"]', { timeout: 30000 });
|
||||
// SSE delivered the terminal state without a page reload.
|
||||
check("run state succeeded via SSE", (await page.getAttribute("body", "data-run-state")) === "succeeded");
|
||||
check("run panel visible", await page.locator("#mq-run-panel").isVisible());
|
||||
check("run chips anchored", (await page.locator(".mq-run-chip").count()) > 0);
|
||||
check(
|
||||
"trace event list rendered",
|
||||
(await page.locator(".mq-run-events li").count()) > 0
|
||||
(await page.locator("#mq-run-events li").count()) > 0
|
||||
);
|
||||
check(
|
||||
"stdout rendered escaped",
|
||||
(await page.locator(".mq-stdout").first().innerText()).includes("0")
|
||||
(await page.locator("#mq-run-stdout").innerText()).includes("0")
|
||||
);
|
||||
check(
|
||||
"no polling API was used",
|
||||
runRequests.every((url) => !url.includes("status")),
|
||||
runRequests.join(", ")
|
||||
);
|
||||
if (screenshotDir) {
|
||||
await page.screenshot({ path: path.join(screenshotDir, "control-flow-run.png") });
|
||||
}
|
||||
// Clear run removes the display and the URL marker.
|
||||
await page.click('[data-action="clear-run"]');
|
||||
await page.waitForURL((url) => !url.searchParams.has("run"), { timeout: 15000 });
|
||||
check("clear run removes panel", (await page.locator("#mq-run-panel").count()) === 0);
|
||||
// Clear run hides the display and keeps the project untouched.
|
||||
await page.click('.mq-dock-btn[data-action="clear"]');
|
||||
check("clear hides run panel", !(await page.locator("#mq-run-panel").isVisible()));
|
||||
check("page was never reloaded by the run", (await page.title()).includes("Marqdo"));
|
||||
}
|
||||
|
||||
await browser.close();
|
||||
|
||||
@@ -0,0 +1,419 @@
|
||||
//! Raw HTTP/1.1 test client for the Live server (no extra dependencies).
|
||||
//!
|
||||
//! Provides one-shot requests and a chunked SSE reader, so integration and
|
||||
//! security suites exercise the real server process, real cookies, real
|
||||
//! headers and the real `text/event-stream` transport.
|
||||
|
||||
#![allow(dead_code)]
|
||||
|
||||
use super::{view_bin, FakeCore};
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub struct TestServer {
|
||||
pub child: Child,
|
||||
pub port: u16,
|
||||
pub core: FakeCore,
|
||||
}
|
||||
|
||||
impl Drop for TestServer {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the real `marqdo-view` binary on an OS-chosen loopback port with a
|
||||
/// scripted fake Core. Golden Analysis must match the project's exact source.
|
||||
pub fn start(
|
||||
project: &str,
|
||||
analysis_golden: &str,
|
||||
run_golden: Option<&str>,
|
||||
trace_golden: Option<&str>,
|
||||
) -> TestServer {
|
||||
start_with_env(project, analysis_golden, run_golden, trace_golden, &[])
|
||||
}
|
||||
|
||||
pub fn start_with_env(
|
||||
project: &str,
|
||||
analysis_golden: &str,
|
||||
run_golden: Option<&str>,
|
||||
trace_golden: Option<&str>,
|
||||
envs: &[(&str, &str)],
|
||||
) -> TestServer {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
let seq = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let repo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let core = FakeCore::new(&format!("http-core-{seq}"));
|
||||
let golden = std::fs::read(repo_root.join(analysis_golden)).unwrap();
|
||||
core.set_analysis(std::str::from_utf8(&golden).unwrap());
|
||||
if let Some(run_golden) = run_golden {
|
||||
let run = std::fs::read_to_string(repo_root.join(run_golden)).unwrap();
|
||||
let trace =
|
||||
trace_golden.map(|trace| std::fs::read_to_string(repo_root.join(trace)).unwrap());
|
||||
core.set_run(0, &run, trace.as_deref());
|
||||
}
|
||||
|
||||
let mut command = Command::new(view_bin());
|
||||
command
|
||||
.current_dir(&repo_root)
|
||||
.args([project, "--port", "0", "--no-open", "--marqdo-bin"])
|
||||
.arg(&core.script)
|
||||
.env_remove("MARQDO_BIN")
|
||||
.env_remove("MARQDO_TOOL_PROTOCOL")
|
||||
.env_remove("MARQDO_PROTOCOL_ANALYSIS")
|
||||
.env_remove("MARQDO_PROTOCOL_TRACE")
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::piped());
|
||||
for (key, value) in envs {
|
||||
command.env(key, value);
|
||||
}
|
||||
let mut child = command.spawn().expect("spawn marqdo-view");
|
||||
let stderr = child.stderr.take().expect("piped stderr");
|
||||
let mut reader = BufReader::new(stderr);
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
let mut url: Option<String> = None;
|
||||
while Instant::now() < deadline {
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).unwrap_or(0) == 0 {
|
||||
break;
|
||||
}
|
||||
if let Some(rest) = line.trim().strip_prefix("marqdo view: ") {
|
||||
url = Some(rest.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
let url = url.expect("server printed its URL");
|
||||
let port: u16 = url
|
||||
.trim_end_matches('/')
|
||||
.rsplit(':')
|
||||
.next()
|
||||
.expect("port in url")
|
||||
.parse()
|
||||
.expect("numeric port");
|
||||
let debug = std::env::var("MQ_TEST_DEBUG").is_ok();
|
||||
std::thread::spawn(move || {
|
||||
if debug {
|
||||
for line in reader.lines().map_while(Result::ok) {
|
||||
eprintln!("[server] {line}");
|
||||
}
|
||||
} else {
|
||||
let mut sink = String::new();
|
||||
let _ = reader.read_to_string(&mut sink);
|
||||
}
|
||||
});
|
||||
TestServer { child, port, core }
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct HttpResponse {
|
||||
pub status: u16,
|
||||
pub headers: String,
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
impl HttpResponse {
|
||||
pub fn header(&self, name: &str) -> Option<String> {
|
||||
self.headers.lines().find_map(|line| {
|
||||
let (key, value) = line.split_once(':')?;
|
||||
if key.eq_ignore_ascii_case(name) {
|
||||
Some(value.trim().to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn json(&self) -> serde_json::Value {
|
||||
serde_json::from_str(&self.body)
|
||||
.unwrap_or_else(|err| panic!("json body {err}: {}", self.body))
|
||||
}
|
||||
|
||||
pub fn set_cookie(&self) -> Option<String> {
|
||||
self.header("Set-Cookie")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get(port: u16, path: &str) -> HttpResponse {
|
||||
request(port, "GET", path, &[], None)
|
||||
}
|
||||
|
||||
pub fn get_with_host(port: u16, path: &str, host: &str) -> HttpResponse {
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", port)).expect("connect");
|
||||
let head = format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n");
|
||||
stream.write_all(head.as_bytes()).expect("write request");
|
||||
let mut raw = Vec::new();
|
||||
stream.read_to_end(&mut raw).expect("read response");
|
||||
parse_response(&raw)
|
||||
}
|
||||
|
||||
pub fn post(port: u16, path: &str, headers: &[(&str, String)], body: Option<&str>) -> HttpResponse {
|
||||
request(port, "POST", path, headers, body)
|
||||
}
|
||||
|
||||
pub fn request(
|
||||
port: u16,
|
||||
method: &str,
|
||||
path: &str,
|
||||
headers: &[(&str, String)],
|
||||
body: Option<&str>,
|
||||
) -> HttpResponse {
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", port)).expect("connect");
|
||||
let host = format!("127.0.0.1:{port}");
|
||||
write_request(&mut stream, &host, method, path, headers, body, true);
|
||||
let mut raw = Vec::new();
|
||||
stream.read_to_end(&mut raw).expect("read response");
|
||||
parse_response(&raw)
|
||||
}
|
||||
|
||||
fn parse_response(raw: &[u8]) -> HttpResponse {
|
||||
let text = String::from_utf8_lossy(raw).to_string();
|
||||
let (head, body) = text.split_once("\r\n\r\n").unwrap_or((&text, ""));
|
||||
let status = head
|
||||
.lines()
|
||||
.next()
|
||||
.and_then(|line| line.split_whitespace().nth(1))
|
||||
.and_then(|code| code.parse().ok())
|
||||
.unwrap_or(0);
|
||||
HttpResponse {
|
||||
status,
|
||||
headers: head.to_string(),
|
||||
body: body.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_request(
|
||||
stream: &mut TcpStream,
|
||||
host: &str,
|
||||
method: &str,
|
||||
path: &str,
|
||||
headers: &[(&str, String)],
|
||||
body: Option<&str>,
|
||||
close: bool,
|
||||
) {
|
||||
let mut head = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nAccept: */*\r\n");
|
||||
if close {
|
||||
head.push_str("Connection: close\r\n");
|
||||
}
|
||||
for (name, value) in headers {
|
||||
head.push_str(&format!("{name}: {value}\r\n"));
|
||||
}
|
||||
if let Some(body) = body {
|
||||
head.push_str(&format!("Content-Length: {}\r\n", body.len()));
|
||||
}
|
||||
head.push_str("\r\n");
|
||||
stream.write_all(head.as_bytes()).expect("write headers");
|
||||
if let Some(body) = body {
|
||||
stream.write_all(body.as_bytes()).expect("write body");
|
||||
}
|
||||
stream.flush().expect("flush request");
|
||||
}
|
||||
|
||||
/// One parsed SSE frame (or heartbeat comment).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SseFrame {
|
||||
pub event: String,
|
||||
pub id: Option<u64>,
|
||||
pub data: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
pub struct SseReader {
|
||||
reader: BufReader<TcpStream>,
|
||||
pending: String,
|
||||
pub headers: String,
|
||||
pub status: u16,
|
||||
}
|
||||
|
||||
impl SseReader {
|
||||
pub fn open(port: u16, path: &str, headers: &[(&str, String)]) -> SseReader {
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", port)).expect("connect sse");
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(15)))
|
||||
.expect("read timeout");
|
||||
let host = format!("127.0.0.1:{port}");
|
||||
write_request(&mut stream, &host, "GET", path, headers, None, false);
|
||||
let mut reader = BufReader::new(stream);
|
||||
let mut head = String::new();
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).expect("read sse header");
|
||||
if line == "\r\n" || line == "\n" {
|
||||
break;
|
||||
}
|
||||
head.push_str(&line);
|
||||
}
|
||||
let status = head
|
||||
.lines()
|
||||
.next()
|
||||
.and_then(|line| line.split_whitespace().nth(1))
|
||||
.and_then(|code| code.parse().ok())
|
||||
.unwrap_or(0);
|
||||
SseReader {
|
||||
reader,
|
||||
pending: String::new(),
|
||||
headers: head,
|
||||
status,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn header(&self, name: &str) -> Option<String> {
|
||||
self.headers.lines().find_map(|line| {
|
||||
let (key, value) = line.split_once(':')?;
|
||||
if key.eq_ignore_ascii_case(name) {
|
||||
Some(value.trim().to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Next frame/heartbeat; `None` on stream end or read failure.
|
||||
pub fn next_frame(&mut self) -> Option<SseFrame> {
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
match self.reader.read_line(&mut line) {
|
||||
Ok(0) => return None,
|
||||
Ok(_) => {}
|
||||
Err(_) => return None,
|
||||
}
|
||||
let trimmed = line.trim_end_matches(['\r', '\n']);
|
||||
if trimmed.is_empty() {
|
||||
if self.pending.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let frame = std::mem::take(&mut self.pending);
|
||||
let mut event = "message".to_string();
|
||||
let mut id = None;
|
||||
let mut data_lines: Vec<String> = Vec::new();
|
||||
for line in frame.lines() {
|
||||
if let Some(value) = line.strip_prefix("event: ") {
|
||||
event = value.trim().to_string();
|
||||
} else if let Some(value) = line.strip_prefix("id: ") {
|
||||
id = value.trim().parse::<u64>().ok();
|
||||
} else if let Some(value) = line.strip_prefix("data: ") {
|
||||
data_lines.push(value.to_string());
|
||||
} else if line.starts_with(':') {
|
||||
event = "heartbeat".to_string();
|
||||
}
|
||||
}
|
||||
let data = if data_lines.is_empty() {
|
||||
None
|
||||
} else {
|
||||
serde_json::from_str(&data_lines.join("\n")).ok()
|
||||
};
|
||||
return Some(SseFrame { event, id, data });
|
||||
}
|
||||
self.pending.push_str(&line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One authenticated browser session: cookie + CSRF + current Analysis digest.
|
||||
pub struct Session {
|
||||
pub cookie: String,
|
||||
pub csrf: String,
|
||||
pub digest: String,
|
||||
}
|
||||
|
||||
pub fn open_session(server: &TestServer, path: &str) -> (Session, HttpResponse) {
|
||||
let page = get(server.port, path);
|
||||
assert_eq!(page.status, 200, "body: {}", page.body);
|
||||
let cookie = page
|
||||
.set_cookie()
|
||||
.and_then(|cookie| cookie.split(';').next().map(str::to_string))
|
||||
.expect("Set-Cookie");
|
||||
let csrf = page
|
||||
.body
|
||||
.split("name=\"mq-csrf-token\" content=\"")
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split('"').next())
|
||||
.expect("csrf meta")
|
||||
.to_string();
|
||||
let digest = page
|
||||
.body
|
||||
.split("data-analysis-digest=\"")
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split('"').next())
|
||||
.expect("analysis digest attr")
|
||||
.to_string();
|
||||
(
|
||||
Session {
|
||||
cookie,
|
||||
csrf,
|
||||
digest,
|
||||
},
|
||||
page,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn run_body(
|
||||
document: &str,
|
||||
digest: &str,
|
||||
target: serde_json::Value,
|
||||
client_id: &str,
|
||||
) -> String {
|
||||
serde_json::json!({
|
||||
"document": document,
|
||||
"target": target,
|
||||
"parameters": [],
|
||||
"analysis_digest": digest,
|
||||
"mode": "pure",
|
||||
"grants": {"read": [], "write": []},
|
||||
"client_request_id": client_id,
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
pub fn post_headers(
|
||||
server: &TestServer,
|
||||
session: &Session,
|
||||
json: bool,
|
||||
) -> Vec<(&'static str, String)> {
|
||||
let mut headers = vec![
|
||||
("Cookie", session.cookie.clone()),
|
||||
("Origin", format!("http://127.0.0.1:{}", server.port)),
|
||||
("X-View-CSRF", session.csrf.clone()),
|
||||
];
|
||||
if json {
|
||||
headers.push(("Content-Type", "application/json".to_string()));
|
||||
}
|
||||
headers
|
||||
}
|
||||
|
||||
pub fn submit(server: &TestServer, session: &Session, body: &str) -> HttpResponse {
|
||||
post(
|
||||
server.port,
|
||||
"/api/runs",
|
||||
&post_headers(server, session, true),
|
||||
Some(body),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn collect_until_terminal(reader: &mut SseReader) -> Vec<SseFrame> {
|
||||
let mut frames = Vec::new();
|
||||
let deadline = Instant::now() + Duration::from_secs(20);
|
||||
while Instant::now() < deadline {
|
||||
let Some(frame) = reader.next_frame() else {
|
||||
break;
|
||||
};
|
||||
let terminal = frame
|
||||
.data
|
||||
.as_ref()
|
||||
.and_then(|data| data["state"].as_str())
|
||||
.map(|state| {
|
||||
matches!(
|
||||
state,
|
||||
"succeeded" | "failed" | "cancelled" | "timed_out" | "unavailable"
|
||||
)
|
||||
})
|
||||
.unwrap_or(false);
|
||||
frames.push(frame);
|
||||
if terminal {
|
||||
break;
|
||||
}
|
||||
}
|
||||
frames
|
||||
}
|
||||
+3
-1
@@ -1,4 +1,4 @@
|
||||
//! Shared test helpers for integration tests.
|
||||
//! Shared test helpers for integration and security suites.
|
||||
//!
|
||||
//! Fake cores are real executables (never mocked Rust traits at the process
|
||||
//! boundary) so argv, exit codes, stderr and temp artifacts are all exercised.
|
||||
@@ -236,3 +236,5 @@ pub fn sha256_hex(bytes: &[u8]) -> String {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub mod http;
|
||||
+381
-530
@@ -1,30 +1,30 @@
|
||||
//! Live server tests over a raw TCP HTTP/1.1 client (no extra deps).
|
||||
//! The server is a real child process so startup, URL output, routing, security
|
||||
//! headers, CSRF and the explicit-run flow are exercised end to end.
|
||||
//! Live HTTP/SSE integration tests over a raw HTTP client.
|
||||
//!
|
||||
//! The server is a real child process, the fake Core is a real executable and
|
||||
//! every assertion goes through real cookies, CSRF headers, Origin checks and
|
||||
//! the chunked `text/event-stream` transport.
|
||||
|
||||
use crate::common;
|
||||
|
||||
use common::{run_view, FakeCore};
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use crate::common::http::{
|
||||
self, collect_until_terminal, open_session, post_headers, run_body, submit, SseFrame,
|
||||
TestServer,
|
||||
};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
struct LiveServer {
|
||||
child: Child,
|
||||
port: u16,
|
||||
_core: FakeCore,
|
||||
const RUN_GOLDEN: &str = "tests/golden/trace-v2/control-flow.run.json";
|
||||
const TRACE_GOLDEN: &str = "tests/golden/trace-v2/control-flow.trace.json";
|
||||
const ANALYSIS_GOLDEN: &str = "tests/golden/analysis-v2/control-flow.json";
|
||||
|
||||
fn control_flow() -> TestServer {
|
||||
http::start(
|
||||
"examples/control-flow",
|
||||
ANALYSIS_GOLDEN,
|
||||
Some(RUN_GOLDEN),
|
||||
Some(TRACE_GOLDEN),
|
||||
)
|
||||
}
|
||||
|
||||
impl Drop for LiveServer {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
fn start_server() -> LiveServer {
|
||||
start_server_with(
|
||||
fn welcome() -> TestServer {
|
||||
http::start(
|
||||
"examples/welcome",
|
||||
"tests/golden/analysis-v2/welcome.json",
|
||||
None,
|
||||
@@ -32,558 +32,409 @@ fn start_server() -> LiveServer {
|
||||
)
|
||||
}
|
||||
|
||||
fn start_server_with(
|
||||
project: &str,
|
||||
analysis_golden: &str,
|
||||
run_golden: Option<&str>,
|
||||
trace_golden: Option<&str>,
|
||||
) -> LiveServer {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
let seq = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let repo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let core = FakeCore::new(&format!("live-core-{seq}"));
|
||||
let golden = std::fs::read(repo_root.join(analysis_golden)).unwrap();
|
||||
core.set_analysis(std::str::from_utf8(&golden).unwrap());
|
||||
if let Some(run_golden) = run_golden {
|
||||
let run = std::fs::read_to_string(repo_root.join(run_golden)).unwrap();
|
||||
let trace =
|
||||
trace_golden.map(|trace| std::fs::read_to_string(repo_root.join(trace)).unwrap());
|
||||
core.set_run(0, &run, trace.as_deref());
|
||||
}
|
||||
|
||||
let mut child = Command::new(common::view_bin())
|
||||
.current_dir(&repo_root)
|
||||
.args([project, "--port", "0", "--no-open", "--marqdo-bin"])
|
||||
.arg(&core.script)
|
||||
.env_remove("MARQDO_BIN")
|
||||
.env_remove("MARQDO_TOOL_PROTOCOL")
|
||||
.env_remove("MARQDO_PROTOCOL_ANALYSIS")
|
||||
.env_remove("MARQDO_PROTOCOL_TRACE")
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn marqdo-view");
|
||||
|
||||
let stderr = child.stderr.take().expect("piped stderr");
|
||||
let mut reader = BufReader::new(stderr);
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
let mut url: Option<String> = None;
|
||||
while Instant::now() < deadline {
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).unwrap_or(0) == 0 {
|
||||
break;
|
||||
}
|
||||
if let Some(rest) = line.trim().strip_prefix("marqdo view: ") {
|
||||
url = Some(rest.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
let url = url.expect("server printed its URL");
|
||||
let port: u16 = url
|
||||
.trim_end_matches('/')
|
||||
.rsplit(':')
|
||||
.next()
|
||||
.expect("port in url")
|
||||
.parse()
|
||||
.expect("numeric port");
|
||||
// Keep draining stderr so the child never blocks on a full pipe.
|
||||
std::thread::spawn(move || {
|
||||
let mut sink = String::new();
|
||||
let _ = reader.read_to_string(&mut sink);
|
||||
});
|
||||
|
||||
LiveServer {
|
||||
child,
|
||||
port,
|
||||
_core: core,
|
||||
}
|
||||
}
|
||||
|
||||
struct HttpResponse {
|
||||
status: u16,
|
||||
headers: String,
|
||||
body: String,
|
||||
}
|
||||
|
||||
fn http_get(port: u16, host: Option<&str>, path: &str) -> HttpResponse {
|
||||
http_request(port, host, "GET", path, &[], None)
|
||||
}
|
||||
|
||||
fn http_post(port: u16, path: &str, headers: &[(&str, String)], body: &str) -> HttpResponse {
|
||||
http_request(port, None, "POST", path, headers, Some(body))
|
||||
}
|
||||
|
||||
fn http_request(
|
||||
port: u16,
|
||||
host: Option<&str>,
|
||||
method: &str,
|
||||
path: &str,
|
||||
headers: &[(&str, String)],
|
||||
body: Option<&str>,
|
||||
) -> HttpResponse {
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", port)).expect("connect");
|
||||
let host = host
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| format!("127.0.0.1:{port}"));
|
||||
let mut request =
|
||||
format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nAccept: */*\r\n");
|
||||
for (name, value) in headers {
|
||||
request.push_str(&format!("{name}: {value}\r\n"));
|
||||
}
|
||||
if let Some(body) = body {
|
||||
request.push_str(&format!("Content-Length: {}\r\n", body.len()));
|
||||
}
|
||||
request.push_str("\r\n");
|
||||
if let Some(body) = body {
|
||||
request.push_str(body);
|
||||
}
|
||||
stream.write_all(request.as_bytes()).expect("write request");
|
||||
let mut raw = Vec::new();
|
||||
stream.read_to_end(&mut raw).expect("read response");
|
||||
let text = String::from_utf8_lossy(&raw).to_string();
|
||||
let (head, body) = text.split_once("\r\n\r\n").unwrap_or((&text, ""));
|
||||
let status = head
|
||||
.lines()
|
||||
.next()
|
||||
.and_then(|line| line.split_whitespace().nth(1))
|
||||
.and_then(|code| code.parse().ok())
|
||||
.unwrap_or(0);
|
||||
HttpResponse {
|
||||
status,
|
||||
headers: head.to_string(),
|
||||
body: body.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn csrf_token(page: &str) -> String {
|
||||
page.split("name=\"mq-csrf-token\" content=\"")
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split('"').next())
|
||||
.expect("csrf meta token")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn json_body(page: &str) -> serde_json::Value {
|
||||
serde_json::from_str(page).expect("json body")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_server_serves_pages_assets_and_health() {
|
||||
let server = start_server();
|
||||
let page = http_get(server.port, None, "/");
|
||||
fn pages_issue_a_session_cookie_and_never_execute_the_document() {
|
||||
let server = welcome();
|
||||
let (session, page) = open_session(&server, "/");
|
||||
assert_eq!(page.status, 200);
|
||||
assert!(page.headers.contains("Content-Type: text/html"));
|
||||
assert!(page.headers.contains("Content-Security-Policy"));
|
||||
assert!(page.headers.contains("X-Content-Type-Options: nosniff"));
|
||||
assert!(page.headers.contains("default-src 'self'"));
|
||||
assert!(page.headers.contains("connect-src 'self'"));
|
||||
assert!(page.body.contains("mq-reader"));
|
||||
assert!(page.body.contains("欢迎来到 Marqdo"));
|
||||
assert!(page.body.contains("data-live=\"true\""));
|
||||
assert!(page
|
||||
.body
|
||||
.contains(&format!("data-analysis-digest=\"{}\"", session.digest)));
|
||||
assert!(page.body.contains("mq-csrf-token"));
|
||||
assert!(page.body.contains("data-run-available=\"false\""));
|
||||
assert!(page.body.contains("data-action=\"run\""));
|
||||
assert!(page.body.contains("mq-dialog-run\""));
|
||||
assert!(!page.body.contains("/api/run\""));
|
||||
|
||||
// Repeated page loads with the same cookie must never run the document.
|
||||
for _ in 0..10 {
|
||||
let repeated = http::request(
|
||||
server.port,
|
||||
"GET",
|
||||
"/",
|
||||
&[("Cookie", session.cookie.clone())],
|
||||
None,
|
||||
);
|
||||
assert_eq!(repeated.status, 200);
|
||||
}
|
||||
assert!(!server.core.dir.join("run-was-called").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_only_routes_are_the_target_contract_and_old_routes_are_gone() {
|
||||
let server = welcome();
|
||||
let documents = http::get(server.port, "/api/documents");
|
||||
assert_eq!(documents.status, 200);
|
||||
let body = documents.json();
|
||||
assert_eq!(body["schema"], "marqdo.view-documents");
|
||||
assert_eq!(body["schema_version"], 1);
|
||||
assert!(body["documents"].as_array().unwrap().len() >= 2);
|
||||
assert!(body["note"].as_str().unwrap().contains("never executes"));
|
||||
|
||||
for stale in ["/api/health", "/api/document?path=index.mq.md", "/api/run"] {
|
||||
let response = http::get(server.port, stale);
|
||||
assert_eq!(response.status, 404, "{stale} must be gone");
|
||||
}
|
||||
let run_get = http::get(server.port, "/api/runs/deadbeef/events");
|
||||
assert_eq!(run_get.status, 401, "SSE requires a session");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assets_are_immutable_and_carry_strict_headers() {
|
||||
let server = welcome();
|
||||
let (_, page) = open_session(&server, "/");
|
||||
let css_path = page
|
||||
.body
|
||||
.split("href=\"/assets/")
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split('"').next())
|
||||
.expect("css link");
|
||||
let css = http_get(server.port, None, &format!("/assets/{css_path}"));
|
||||
let css = http::get(server.port, &format!("/assets/{css_path}"));
|
||||
assert_eq!(css.status, 200);
|
||||
assert!(css.headers.contains("text/css"));
|
||||
assert!(css.body.contains("@layer tokens"));
|
||||
assert!(css.headers.contains("immutable"));
|
||||
assert!(css.headers.contains("X-Content-Type-Options: nosniff"));
|
||||
|
||||
let health = http_get(server.port, None, "/api/health");
|
||||
assert_eq!(health.status, 200);
|
||||
let health = json_body(&health.body);
|
||||
assert_eq!(health["schema"], "marqdo.view-health");
|
||||
assert_eq!(health["protocols"]["analysis"], 2);
|
||||
assert_eq!(health["run_api"], true);
|
||||
|
||||
let document = http_get(server.port, None, "/file?path=guide.mq.md");
|
||||
assert_eq!(document.status, 200);
|
||||
assert!(document.body.contains("阅读指南"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_server_rejects_dns_rebinding_and_path_escape() {
|
||||
let server = start_server();
|
||||
let bad_host = http_get(server.port, Some("attacker.example"), "/");
|
||||
assert_eq!(bad_host.status, 400);
|
||||
|
||||
for path in [
|
||||
"/file?path=../secret.mq.md",
|
||||
"/file?path=%2e%2e%2fsecret.mq.md",
|
||||
"/file?path=/etc/passwd",
|
||||
"/file?path=..%2f..%2fetc%2fpasswd",
|
||||
] {
|
||||
let response = http_get(server.port, None, path);
|
||||
assert!(
|
||||
response.status == 403 || response.status == 404,
|
||||
"path {path} returned {}",
|
||||
response.status
|
||||
);
|
||||
}
|
||||
|
||||
let missing = http_get(server.port, None, "/file?path=missing.mq.md");
|
||||
let missing = http::get(server.port, "/assets/nope.css");
|
||||
assert_eq!(missing.status, 404);
|
||||
let unknown = http_get(server.port, None, "/api/run");
|
||||
assert_eq!(unknown.status, 404);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_server_rejects_unknown_methods_and_bad_assets() {
|
||||
let server = start_server();
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", server.port)).expect("connect");
|
||||
let request = format!(
|
||||
"PUT /api/run HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}",
|
||||
server.port
|
||||
fn explicit_run_streams_sse_accepted_running_and_terminal_with_verified_trace() {
|
||||
let server = control_flow();
|
||||
let (session, _) = open_session(&server, "/");
|
||||
let body = run_body(
|
||||
"index.mq.md",
|
||||
&session.digest,
|
||||
serde_json::json!({"kind": "entry"}),
|
||||
"req-sse",
|
||||
);
|
||||
stream.write_all(request.as_bytes()).unwrap();
|
||||
let mut raw = Vec::new();
|
||||
stream.read_to_end(&mut raw).unwrap();
|
||||
let text = String::from_utf8_lossy(&raw);
|
||||
assert!(text.starts_with("HTTP/1.1 405"), "{text}");
|
||||
let accepted = submit(&server, &session, &body);
|
||||
assert_eq!(accepted.status, 202, "body: {}", accepted.body);
|
||||
let accepted = accepted.json();
|
||||
let run_id = accepted["run_id"].as_str().expect("run id").to_string();
|
||||
assert_eq!(accepted["state"], "accepted");
|
||||
assert_eq!(accepted["events_url"], format!("/api/runs/{run_id}/events"));
|
||||
assert_eq!(accepted["cancel_url"], format!("/api/runs/{run_id}/cancel"));
|
||||
assert_eq!(accepted["reused"], false);
|
||||
|
||||
let bad_asset = http_get(server.port, None, "/assets/../../etc/passwd");
|
||||
assert_eq!(bad_asset.status, 404);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_and_refreshing_never_runs_the_document() {
|
||||
// R-01: ten page loads must produce zero Core `run` invocations.
|
||||
let server = start_server_with(
|
||||
"examples/control-flow",
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
Some("tests/golden/trace-v2/control-flow.run.json"),
|
||||
Some("tests/golden/trace-v2/control-flow.trace.json"),
|
||||
let mut reader = http::SseReader::open(
|
||||
server.port,
|
||||
&format!("/api/runs/{run_id}/events"),
|
||||
&[("Cookie", session.cookie.clone())],
|
||||
);
|
||||
for _ in 0..10 {
|
||||
let page = http_get(server.port, None, "/");
|
||||
assert_eq!(page.status, 200);
|
||||
assert!(page.body.contains("data-run-state=\"not-run\""));
|
||||
assert!(!page.body.contains("mq-run-panel"));
|
||||
}
|
||||
let args = server._core.argv_lines();
|
||||
let run_calls = args
|
||||
assert_eq!(reader.status, 200);
|
||||
assert!(reader
|
||||
.header("Content-Type")
|
||||
.unwrap()
|
||||
.contains("text/event-stream"));
|
||||
assert!(reader.header("Cache-Control").unwrap().contains("no-store"));
|
||||
let frames = collect_until_terminal(&mut reader);
|
||||
assert!(!frames.is_empty());
|
||||
let mut ids = frames
|
||||
.iter()
|
||||
.filter(|line| line.as_str() == "arg=run")
|
||||
.count();
|
||||
assert_eq!(run_calls, 0, "page loads must never call Core run");
|
||||
}
|
||||
|
||||
fn run_and_get_page(server: &LiveServer) -> (String, String) {
|
||||
let page = http_get(server.port, None, "/");
|
||||
let token = csrf_token(&page.body);
|
||||
let response = http_post(
|
||||
server.port,
|
||||
"/api/run",
|
||||
&[
|
||||
("Content-Type", "application/json".to_string()),
|
||||
("X-MQ-CSRF", token.clone()),
|
||||
],
|
||||
r#"{"path":"index.mq.md","mode":"pure","confirm":true}"#,
|
||||
);
|
||||
assert_eq!(response.status, 200, "body: {}", response.body);
|
||||
let json = json_body(&response.body);
|
||||
assert_eq!(json["ok"], true);
|
||||
let redirect = json["redirect"].as_str().expect("redirect").to_string();
|
||||
let run_page = http_get(server.port, None, &redirect);
|
||||
assert_eq!(run_page.status, 200);
|
||||
(token, run_page.body)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_run_requires_csrf_and_confirm_then_renders_real_trace() {
|
||||
let server = start_server_with(
|
||||
"examples/control-flow",
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
Some("tests/golden/trace-v2/control-flow.run.json"),
|
||||
Some("tests/golden/trace-v2/control-flow.trace.json"),
|
||||
);
|
||||
let (_, page) = run_and_get_page(&server);
|
||||
assert!(page.contains("mq-run-panel"));
|
||||
assert!(page.contains("data-run-state=\"succeeded\""));
|
||||
assert!(page.contains("真实 Trace v2 事件"));
|
||||
assert!(page.contains("mq-run-chip"), "inline run chips expected");
|
||||
assert!(
|
||||
page.contains("0\n0\n2"),
|
||||
"Core stdout must be shown escaped"
|
||||
);
|
||||
// Public JSON final value is allowed; per-statement values are not claimed.
|
||||
assert!(page.contains("Core 本次返回值"));
|
||||
assert!(page.contains("<code>3</code>"));
|
||||
assert!(
|
||||
!page.contains("变量值"),
|
||||
"must not claim per-assignment values"
|
||||
);
|
||||
|
||||
let args = server._core.argv_lines();
|
||||
let run_calls = args
|
||||
.filter_map(|frame| frame.id)
|
||||
.collect::<Vec<_>>();
|
||||
assert!(ids.windows(2).all(|pair| pair[0] < pair[1]), "ids: {ids:?}");
|
||||
ids.dedup();
|
||||
let terminal = frames.last().expect("terminal frame");
|
||||
let data = terminal.data.as_ref().expect("terminal data");
|
||||
assert_eq!(data["schema"], "marqdo.view-run-events");
|
||||
assert_eq!(data["schema_version"], 1);
|
||||
assert_eq!(data["run_id"], run_id.as_str());
|
||||
assert_eq!(data["state"], "succeeded");
|
||||
assert_eq!(data["result"]["success"], true);
|
||||
assert_eq!(data["trace"]["status"], "verified");
|
||||
assert!(!data["trace"]["events"].as_array().unwrap().is_empty());
|
||||
let states: Vec<_> = frames
|
||||
.iter()
|
||||
.filter(|line| line.as_str() == "arg=run")
|
||||
.count();
|
||||
assert_eq!(run_calls, 1, "exactly one explicit run expected");
|
||||
assert!(args.iter().any(|line| line == "arg=pure"));
|
||||
assert!(args.iter().any(|line| line == "arg=--trace-file"));
|
||||
.filter_map(|frame| frame.data.as_ref().and_then(|data| data["state"].as_str()))
|
||||
.collect();
|
||||
assert!(frame_state(&frames, "accepted"), "states: {states:?}");
|
||||
assert!(frame_state(&frames, "running"), "states: {states:?}");
|
||||
assert!(server.core.dir.join("run-was-called").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_api_rejects_missing_token_wrong_origin_and_bad_requests() {
|
||||
let server = start_server_with(
|
||||
"examples/control-flow",
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
Some("tests/golden/trace-v2/control-flow.run.json"),
|
||||
Some("tests/golden/trace-v2/control-flow.trace.json"),
|
||||
);
|
||||
let body = r#"{"path":"index.mq.md","mode":"pure","confirm":true}"#;
|
||||
|
||||
let no_token = http_post(
|
||||
server.port,
|
||||
"/api/run",
|
||||
&[("Content-Type", "application/json".to_string())],
|
||||
body,
|
||||
);
|
||||
assert_eq!(no_token.status, 403);
|
||||
assert!(no_token.body.contains("view.run_denied"));
|
||||
|
||||
let page = http_get(server.port, None, "/");
|
||||
let token = csrf_token(&page.body);
|
||||
let wrong_origin = http_post(
|
||||
server.port,
|
||||
"/api/run",
|
||||
&[
|
||||
("Content-Type", "application/json".to_string()),
|
||||
("X-MQ-CSRF", token.clone()),
|
||||
("Origin", "https://attacker.example".to_string()),
|
||||
],
|
||||
body,
|
||||
);
|
||||
assert_eq!(wrong_origin.status, 403);
|
||||
|
||||
let no_confirm = http_post(
|
||||
server.port,
|
||||
"/api/run",
|
||||
&[
|
||||
("Content-Type", "application/json".to_string()),
|
||||
("X-MQ-CSRF", token.clone()),
|
||||
],
|
||||
r#"{"path":"index.mq.md","mode":"pure","confirm":false}"#,
|
||||
);
|
||||
assert_eq!(no_confirm.status, 400);
|
||||
|
||||
let project_mode = http_post(
|
||||
server.port,
|
||||
"/api/run",
|
||||
&[
|
||||
("Content-Type", "application/json".to_string()),
|
||||
("X-MQ-CSRF", token.clone()),
|
||||
],
|
||||
r#"{"path":"index.mq.md","mode":"project","confirm":true}"#,
|
||||
);
|
||||
assert_eq!(project_mode.status, 403);
|
||||
assert!(project_mode.body.contains("view.run_denied"));
|
||||
// Public errors never leak absolute paths or raw subprocess text.
|
||||
assert!(
|
||||
!project_mode.body.contains("/root/"),
|
||||
"{}",
|
||||
project_mode.body
|
||||
);
|
||||
|
||||
let args = server._core.argv_lines();
|
||||
let run_calls = args
|
||||
fn frame_state(frames: &[SseFrame], wanted: &str) -> bool {
|
||||
frames
|
||||
.iter()
|
||||
.filter(|line| line.as_str() == "arg=run")
|
||||
.any(|frame| frame.data.as_ref().and_then(|data| data["state"].as_str()) == Some(wanted))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_event_id_replays_only_newer_events_and_old_cursor_gets_snapshot() {
|
||||
let server = control_flow();
|
||||
let (session, _) = open_session(&server, "/");
|
||||
let body = run_body(
|
||||
"index.mq.md",
|
||||
&session.digest,
|
||||
serde_json::json!({"kind": "entry"}),
|
||||
"req-replay",
|
||||
);
|
||||
let accepted = submit(&server, &session, &body).json();
|
||||
let run_id = accepted["run_id"].as_str().unwrap().to_string();
|
||||
let mut reader = http::SseReader::open(
|
||||
server.port,
|
||||
&format!("/api/runs/{run_id}/events"),
|
||||
&[("Cookie", session.cookie.clone())],
|
||||
);
|
||||
let frames = collect_until_terminal(&mut reader);
|
||||
let first_seq = frames.first().and_then(|frame| frame.id).unwrap_or(0);
|
||||
assert!(first_seq >= 1);
|
||||
|
||||
// Reconnect with a valid cursor inside the buffer: only newer events.
|
||||
let mut reader = http::SseReader::open(
|
||||
server.port,
|
||||
&format!("/api/runs/{run_id}/events"),
|
||||
&[
|
||||
("Cookie", session.cookie.clone()),
|
||||
("Last-Event-ID", first_seq.to_string()),
|
||||
],
|
||||
);
|
||||
let replay = collect_until_terminal(&mut reader);
|
||||
assert!(replay.iter().all(|frame| frame.id.unwrap_or(0) > first_seq));
|
||||
assert_eq!(
|
||||
replay.last().unwrap().data.as_ref().unwrap()["state"],
|
||||
"succeeded"
|
||||
);
|
||||
|
||||
// A forged/too-new cursor gets an authoritative snapshot, never fake history.
|
||||
let mut reader = http::SseReader::open(
|
||||
server.port,
|
||||
&format!("/api/runs/{run_id}/events"),
|
||||
&[
|
||||
("Cookie", session.cookie.clone()),
|
||||
("Last-Event-ID", "999999".to_string()),
|
||||
],
|
||||
);
|
||||
let snapshot = reader.next_frame().expect("snapshot frame");
|
||||
assert_eq!(snapshot.event, "run.snapshot");
|
||||
let data = snapshot.data.as_ref().unwrap();
|
||||
assert_eq!(data["run_id"], run_id.as_str());
|
||||
assert!(data["seq"].as_u64().unwrap() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_request_id_is_idempotent_and_busy_or_conflict_never_starts_a_second_process() {
|
||||
let server = control_flow();
|
||||
server.core.set_sleep_seconds(2);
|
||||
let (session, _) = open_session(&server, "/");
|
||||
let body = run_body(
|
||||
"index.mq.md",
|
||||
&session.digest,
|
||||
serde_json::json!({"kind": "entry"}),
|
||||
"req-dedupe-http",
|
||||
);
|
||||
let first = submit(&server, &session, &body).json();
|
||||
let second = submit(&server, &session, &body).json();
|
||||
assert_eq!(first["run_id"], second["run_id"]);
|
||||
assert_eq!(second["reused"], true);
|
||||
|
||||
let other = run_body(
|
||||
"index.mq.md",
|
||||
&session.digest,
|
||||
serde_json::json!({"kind": "entry"}),
|
||||
"req-busy-http",
|
||||
);
|
||||
let busy = submit(&server, &session, &other);
|
||||
assert_eq!(busy.status, 409);
|
||||
assert_eq!(busy.json()["code"], "view.run_busy");
|
||||
|
||||
let mut changed: serde_json::Value = serde_json::from_str(&body).unwrap();
|
||||
changed["mode"] = serde_json::json!("project");
|
||||
let conflict = submit(&server, &session, changed.to_string().as_str());
|
||||
assert_eq!(conflict.status, 409);
|
||||
assert_eq!(conflict.json()["code"], "view.run_conflict");
|
||||
|
||||
// Cancel the active job so the test process does not leave a child behind.
|
||||
let cancel = http::post(
|
||||
server.port,
|
||||
first["cancel_url"].as_str().unwrap(),
|
||||
&post_headers(&server, &session, false),
|
||||
None,
|
||||
);
|
||||
assert_eq!(cancel.status, 200);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_is_idempotent_and_yields_one_terminal_state() {
|
||||
let server = http::start_with_env(
|
||||
"examples/control-flow",
|
||||
ANALYSIS_GOLDEN,
|
||||
Some(RUN_GOLDEN),
|
||||
Some(TRACE_GOLDEN),
|
||||
&[("MARQDO_VIEW_SSE_HEARTBEAT_SECS", "1")],
|
||||
);
|
||||
server.core.set_sleep_seconds(10);
|
||||
let (session, _) = open_session(&server, "/");
|
||||
let body = run_body(
|
||||
"index.mq.md",
|
||||
&session.digest,
|
||||
serde_json::json!({"kind": "entry"}),
|
||||
"req-cancel-http",
|
||||
);
|
||||
let accepted = submit(&server, &session, &body).json();
|
||||
let run_id = accepted["run_id"].as_str().unwrap().to_string();
|
||||
let mut reader = http::SseReader::open(
|
||||
server.port,
|
||||
&format!("/api/runs/{run_id}/events"),
|
||||
&[("Cookie", session.cookie.clone())],
|
||||
);
|
||||
// Read at least one state so the job is observed as running or accepted.
|
||||
let first = reader.next_frame().expect("first frame");
|
||||
assert!(first.data.is_some());
|
||||
|
||||
let started = Instant::now();
|
||||
let cancel = http::post(
|
||||
server.port,
|
||||
&format!("/api/runs/{run_id}/cancel"),
|
||||
&post_headers(&server, &session, false),
|
||||
None,
|
||||
);
|
||||
eprintln!(
|
||||
"CANCEL_DEBUG first={:?} cancel={:?} elapsed={:?}",
|
||||
first,
|
||||
cancel.json(),
|
||||
started.elapsed()
|
||||
);
|
||||
assert_eq!(cancel.status, 200);
|
||||
let repeat = http::post(
|
||||
server.port,
|
||||
&format!("/api/runs/{run_id}/cancel"),
|
||||
&post_headers(&server, &session, false),
|
||||
None,
|
||||
);
|
||||
assert_eq!(repeat.status, 200);
|
||||
|
||||
let frames = collect_until_terminal(&mut reader);
|
||||
let terminal_count = frames
|
||||
.iter()
|
||||
.filter(|frame| {
|
||||
frame
|
||||
.data
|
||||
.as_ref()
|
||||
.and_then(|data| data["state"].as_str())
|
||||
.map(|state| {
|
||||
matches!(
|
||||
state,
|
||||
"succeeded" | "failed" | "cancelled" | "timed_out" | "unavailable"
|
||||
)
|
||||
})
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.count();
|
||||
assert_eq!(run_calls, 0, "rejected requests must never spawn a run");
|
||||
assert_eq!(terminal_count, 1);
|
||||
assert_eq!(
|
||||
frames.last().unwrap().data.as_ref().unwrap()["state"],
|
||||
"cancelled"
|
||||
);
|
||||
assert!(started.elapsed() < Duration::from_secs(8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_cache_can_be_cleared_and_stales_after_source_change() {
|
||||
// Use a temporary copy so the test never mutates committed examples while
|
||||
// other test binaries read them.
|
||||
let repo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let project = common::TempProject::new("stale-run-project");
|
||||
project.write(
|
||||
"marqdo.yaml",
|
||||
"project:\n name: control-flow\n version: 0.1.0\n",
|
||||
fn sse_heartbeats_keep_a_slow_job_connected() {
|
||||
let server = http::start_with_env(
|
||||
"examples/control-flow",
|
||||
ANALYSIS_GOLDEN,
|
||||
Some(RUN_GOLDEN),
|
||||
Some(TRACE_GOLDEN),
|
||||
&[("MARQDO_VIEW_SSE_HEARTBEAT_SECS", "1")],
|
||||
);
|
||||
let source =
|
||||
std::fs::read_to_string(repo_root.join("examples/control-flow/index.mq.md")).unwrap();
|
||||
let source_path = project.write("index.mq.md", &source);
|
||||
let project_path = project.dir.to_str().unwrap().to_string();
|
||||
let server = start_server_with(
|
||||
&project_path,
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
Some("tests/golden/trace-v2/control-flow.run.json"),
|
||||
Some("tests/golden/trace-v2/control-flow.trace.json"),
|
||||
server.core.set_sleep_seconds(3);
|
||||
let (session, _) = open_session(&server, "/");
|
||||
let body = run_body(
|
||||
"index.mq.md",
|
||||
&session.digest,
|
||||
serde_json::json!({"kind": "entry"}),
|
||||
"req-heartbeat",
|
||||
);
|
||||
|
||||
let page = http_get(server.port, None, "/");
|
||||
let token = csrf_token(&page.body);
|
||||
let response = http_post(
|
||||
let accepted = submit(&server, &session, &body).json();
|
||||
let run_id = accepted["run_id"].as_str().unwrap().to_string();
|
||||
let mut reader = http::SseReader::open(
|
||||
server.port,
|
||||
"/api/run",
|
||||
&[
|
||||
("Content-Type", "application/json".to_string()),
|
||||
("X-MQ-CSRF", token.clone()),
|
||||
],
|
||||
r#"{"path":"index.mq.md","mode":"pure","confirm":true}"#,
|
||||
&format!("/api/runs/{run_id}/events"),
|
||||
&[("Cookie", session.cookie.clone())],
|
||||
);
|
||||
let json = json_body(&response.body);
|
||||
let run_id = json["run_id"].as_str().unwrap().to_string();
|
||||
let redirect = json["redirect"].as_str().unwrap().to_string();
|
||||
let run_page = http_get(server.port, None, &redirect);
|
||||
assert!(run_page.body.contains("mq-run-panel"));
|
||||
|
||||
let clear = http_post(
|
||||
server.port,
|
||||
"/api/clear-run",
|
||||
&[
|
||||
("Content-Type", "application/json".to_string()),
|
||||
("X-MQ-CSRF", token.clone()),
|
||||
],
|
||||
&format!(r#"{{"run_id":"{run_id}"}}"#),
|
||||
);
|
||||
assert_eq!(clear.status, 200);
|
||||
let after_clear = http_get(server.port, None, &redirect);
|
||||
assert!(!after_clear.body.contains("mq-run-panel"));
|
||||
|
||||
// Run again, then change the source bytes.
|
||||
let rerun = http_post(
|
||||
server.port,
|
||||
"/api/run",
|
||||
&[
|
||||
("Content-Type", "application/json".to_string()),
|
||||
("X-MQ-CSRF", token),
|
||||
],
|
||||
r#"{"path":"index.mq.md","mode":"pure","confirm":true}"#,
|
||||
);
|
||||
let rerun_json = json_body(&rerun.body);
|
||||
let stale_redirect = rerun_json["redirect"].as_str().unwrap().to_string();
|
||||
std::fs::write(
|
||||
&source_path,
|
||||
format!("{source}\n<!-- changed after run -->\n"),
|
||||
)
|
||||
.unwrap();
|
||||
let stale_page = http_get(server.port, None, &stale_redirect);
|
||||
assert_eq!(stale_page.status, 200);
|
||||
let frames = collect_until_terminal(&mut reader);
|
||||
assert!(
|
||||
stale_page.body.contains("data-run-state=\"stale\"")
|
||||
|| stale_page
|
||||
.body
|
||||
.contains("data-source-status=\"source-mismatch\""),
|
||||
"expected stale/source-mismatch marker"
|
||||
);
|
||||
assert!(!stale_page.body.contains("mq-run-chip"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_trace_is_marked_not_claimed_complete() {
|
||||
let server = start_server_with(
|
||||
"examples/control-flow",
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
Some("tests/golden/trace-v2/control-flow.truncated.run.json"),
|
||||
Some("tests/golden/trace-v2/control-flow.truncated.trace.json"),
|
||||
);
|
||||
let (_, page) = run_and_get_page(&server);
|
||||
assert!(page.contains("data-run-state=\"truncated\""));
|
||||
assert!(page.contains("Trace 被截断"));
|
||||
assert!(!page.contains("data-run-state=\"succeeded\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_run_reports_core_error_code_without_fake_success() {
|
||||
let server = start_server_with(
|
||||
"examples/mixed-modes",
|
||||
"tests/golden/analysis-v2/mixed-modes.json",
|
||||
Some("tests/golden/trace-v2/mixed-modes.arity.run.json"),
|
||||
Some("tests/golden/trace-v2/mixed-modes.arity.trace.json"),
|
||||
);
|
||||
// The fake core exits 0 for run, but the run JSON reports failure with the
|
||||
// Core error code; View must surface that instead of a success state.
|
||||
let (_, page) = run_and_get_page(&server);
|
||||
assert!(page.contains("data-run-state=\"failed\""));
|
||||
assert!(page.contains("call.arity"));
|
||||
assert!(!page.contains("data-run-state=\"succeeded\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn program_stdout_is_escaped_not_injected_as_markup() {
|
||||
let tmp = std::path::PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!(
|
||||
"hostile-stdout-{}-{}.json",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0)
|
||||
));
|
||||
std::fs::write(
|
||||
&tmp,
|
||||
r#"{"command":"run","success":true,"stdout":"<script>alert(1)</script>","stderr":"<img src=x onerror=alert(2)>","trace":[],"value":{"type":"int","decimal":"3"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let server = start_server_with(
|
||||
"examples/control-flow",
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
Some(tmp.to_str().unwrap()),
|
||||
Some("tests/golden/trace-v2/control-flow.trace.json"),
|
||||
);
|
||||
let (_, page) = run_and_get_page(&server);
|
||||
assert!(page.contains("<script>alert(1)</script>"));
|
||||
assert!(!page.contains("<script>alert(1)"));
|
||||
assert!(!page.contains("onerror=\""));
|
||||
assert!(!page.contains("<img src=x"));
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_verify_output_contract_still_holds_for_installed_style_invocation() {
|
||||
// Regression guard: `view verify` must remain a pure static check.
|
||||
let repo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let core = FakeCore::new("verify-core-contract");
|
||||
let golden = std::fs::read(repo_root.join("tests/golden/analysis-v2/welcome.json")).unwrap();
|
||||
core.set_analysis(std::str::from_utf8(&golden).unwrap());
|
||||
let output = run_view(
|
||||
&[
|
||||
"verify",
|
||||
"examples/welcome/00-welcome.mq.md",
|
||||
"--json",
|
||||
"--marqdo-bin",
|
||||
core.script.to_str().unwrap(),
|
||||
],
|
||||
&repo_root,
|
||||
&[("MARQDO_BIN", None)],
|
||||
frames.iter().any(|frame| frame.event == "heartbeat"),
|
||||
"frames: {frames:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
output.status.code(),
|
||||
Some(0),
|
||||
"stderr: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
frames.last().unwrap().data.as_ref().unwrap()["state"],
|
||||
"succeeded"
|
||||
);
|
||||
let json: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
|
||||
assert_eq!(json["result"], "PASS");
|
||||
assert_eq!(json["executed"], false);
|
||||
assert_eq!(json["analysis"]["schema_version"], 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn documents_api_is_a_read_only_structure_and_old_route_is_gone() {
|
||||
let server = start_server();
|
||||
let response = http_get(server.port, None, "/api/documents");
|
||||
assert_eq!(response.status, 200);
|
||||
let body = json_body(&response.body);
|
||||
assert_eq!(body["schema"], "marqdo.view-documents");
|
||||
assert_eq!(body["schema_version"], 1);
|
||||
assert!(body["documents"].is_array());
|
||||
assert!(body["documents"].as_array().unwrap().len() >= 2);
|
||||
assert!(body["current"]["relative_path"].is_string());
|
||||
assert!(body["current"]["outline"].is_array());
|
||||
assert!(body["current"]["note"].is_null() || body["current"]["note"].is_string());
|
||||
assert!(body["note"].as_str().unwrap().contains("never executes"));
|
||||
fn document_without_main_is_rejected_without_running_another_function() {
|
||||
let server = http::start(
|
||||
"examples/tables-math",
|
||||
"tests/golden/analysis-v2/tables-math.json",
|
||||
None,
|
||||
None,
|
||||
);
|
||||
let (session, _) = open_session(&server, "/");
|
||||
let body = run_body(
|
||||
"index.mq.md",
|
||||
&session.digest,
|
||||
serde_json::json!({"kind": "entry"}),
|
||||
"req-no-main",
|
||||
);
|
||||
let response = submit(&server, &session, &body);
|
||||
assert_eq!(response.status, 400);
|
||||
assert_eq!(response.json()["code"], "view.no_entry_function");
|
||||
assert!(!server.core.dir.join("run-was-called").exists());
|
||||
}
|
||||
|
||||
// The old singular route is not part of the target API surface.
|
||||
let old = http_get(server.port, None, "/api/document?path=index.mq.md");
|
||||
assert_eq!(old.status, 404);
|
||||
#[test]
|
||||
fn at_most_two_sse_observers_per_run() {
|
||||
let server = http::start_with_env(
|
||||
"examples/control-flow",
|
||||
ANALYSIS_GOLDEN,
|
||||
Some(RUN_GOLDEN),
|
||||
Some(TRACE_GOLDEN),
|
||||
&[("MARQDO_VIEW_SSE_HEARTBEAT_SECS", "1")],
|
||||
);
|
||||
server.core.set_sleep_seconds(5);
|
||||
let (session, _) = open_session(&server, "/");
|
||||
let body = run_body(
|
||||
"index.mq.md",
|
||||
&session.digest,
|
||||
serde_json::json!({"kind": "entry"}),
|
||||
"req-sse-limit",
|
||||
);
|
||||
let accepted = submit(&server, &session, &body).json();
|
||||
let run_id = accepted["run_id"].as_str().unwrap().to_string();
|
||||
let events_path = format!("/api/runs/{run_id}/events");
|
||||
let first = http::SseReader::open(
|
||||
server.port,
|
||||
&events_path,
|
||||
&[("Cookie", session.cookie.clone())],
|
||||
);
|
||||
assert_eq!(first.status, 200);
|
||||
let second = http::SseReader::open(
|
||||
server.port,
|
||||
&events_path,
|
||||
&[("Cookie", session.cookie.clone())],
|
||||
);
|
||||
assert_eq!(second.status, 200);
|
||||
let third = http::SseReader::open(
|
||||
server.port,
|
||||
&events_path,
|
||||
&[("Cookie", session.cookie.clone())],
|
||||
);
|
||||
assert_eq!(third.status, 429);
|
||||
let cancel = http::post(
|
||||
server.port,
|
||||
&format!("/api/runs/{run_id}/cancel"),
|
||||
&post_headers(&server, &session, false),
|
||||
None,
|
||||
);
|
||||
assert_eq!(cancel.status, 200);
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
//! Security suite: execution endpoint authentication/CSRF, cross-session SSE
|
||||
//! isolation, path containment, adversarial Markdown and response hardening.
|
||||
//!
|
||||
//! Every test runs against the real server child process and a real fake Core
|
||||
//! executable, so headers, cookies, process boundaries and the SSE transport
|
||||
//! are exercised as deployed (RFC-VIEW-0002 §6.8 / §9.2).
|
||||
|
||||
#[path = "../common/mod.rs"]
|
||||
mod common;
|
||||
|
||||
use crate::common::http::{
|
||||
self, collect_until_terminal, open_session, post_headers, run_body, submit, TestServer,
|
||||
};
|
||||
|
||||
fn control_flow() -> TestServer {
|
||||
http::start(
|
||||
"examples/control-flow",
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
Some("tests/golden/trace-v2/control-flow.run.json"),
|
||||
Some("tests/golden/trace-v2/control-flow.trace.json"),
|
||||
)
|
||||
}
|
||||
|
||||
fn welcome() -> TestServer {
|
||||
http::start(
|
||||
"examples/welcome",
|
||||
"tests/golden/analysis-v2/welcome.json",
|
||||
None,
|
||||
None,
|
||||
)
|
||||
}
|
||||
use crate::common::TempProject;
|
||||
|
||||
#[test]
|
||||
fn host_origin_session_csrf_and_json_are_all_required_before_execution() {
|
||||
let server = control_flow();
|
||||
let (session, _) = open_session(&server, "/");
|
||||
let body = run_body(
|
||||
"index.mq.md",
|
||||
&session.digest,
|
||||
serde_json::json!({"kind": "entry"}),
|
||||
"req-sec",
|
||||
);
|
||||
|
||||
// Missing CSRF.
|
||||
let mut headers = post_headers(&server, &session, true);
|
||||
headers.retain(|(name, _)| *name != "X-View-CSRF");
|
||||
let missing_csrf = http::post(server.port, "/api/runs", &headers, Some(&body));
|
||||
assert_eq!(missing_csrf.status, 403);
|
||||
|
||||
// Wrong Origin.
|
||||
let mut headers = post_headers(&server, &session, true);
|
||||
for (name, value) in headers.iter_mut() {
|
||||
if *name == "Origin" {
|
||||
*value = "http://evil.example".to_string();
|
||||
}
|
||||
}
|
||||
let wrong_origin = http::post(server.port, "/api/runs", &headers, Some(&body));
|
||||
assert_eq!(wrong_origin.status, 403);
|
||||
|
||||
// Missing session cookie.
|
||||
let mut headers = post_headers(&server, &session, true);
|
||||
headers.retain(|(name, _)| *name != "Cookie");
|
||||
let no_session = http::post(server.port, "/api/runs", &headers, Some(&body));
|
||||
assert_eq!(no_session.status, 401);
|
||||
|
||||
// Wrong content type.
|
||||
let mut headers = post_headers(&server, &session, true);
|
||||
for (name, value) in headers.iter_mut() {
|
||||
if *name == "Content-Type" {
|
||||
*value = "text/plain".to_string();
|
||||
}
|
||||
}
|
||||
let wrong_type = http::post(server.port, "/api/runs", &headers, Some(&body));
|
||||
assert_eq!(wrong_type.status, 415);
|
||||
|
||||
// Malformed Host.
|
||||
let bad_host = http::get_with_host(server.port, "/", "evil.example");
|
||||
assert_eq!(bad_host.status, 400);
|
||||
|
||||
assert!(!server.core.dir.join("run-was-called").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sse_and_cancel_are_scoped_to_the_owning_session() {
|
||||
let server = control_flow();
|
||||
let (session_a, _) = open_session(&server, "/");
|
||||
let (session_b, _) = open_session(&server, "/");
|
||||
let body = run_body(
|
||||
"index.mq.md",
|
||||
&session_a.digest,
|
||||
serde_json::json!({"kind": "entry"}),
|
||||
"req-owner",
|
||||
);
|
||||
let accepted = submit(&server, &session_a, &body).json();
|
||||
let run_id = accepted["run_id"].as_str().unwrap().to_string();
|
||||
|
||||
let reader = http::SseReader::open(
|
||||
server.port,
|
||||
&format!("/api/runs/{run_id}/events"),
|
||||
&[("Cookie", session_b.cookie.clone())],
|
||||
);
|
||||
assert_eq!(reader.status, 404);
|
||||
let cancel = http::post(
|
||||
server.port,
|
||||
&format!("/api/runs/{run_id}/cancel"),
|
||||
&post_headers(&server, &session_b, false),
|
||||
None,
|
||||
);
|
||||
assert_eq!(cancel.status, 404);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_traversal_is_rejected_and_the_old_document_route_is_gone() {
|
||||
let server = welcome();
|
||||
for path in [
|
||||
"/file?path=../marqdo.yaml",
|
||||
"/file?path=%2e%2e%2fmarqdo.yaml",
|
||||
"/file?path=/etc/passwd",
|
||||
"/file?path=..%5c..%5cetc%5cpasswd",
|
||||
] {
|
||||
let response = http::get(server.port, path);
|
||||
assert!(
|
||||
response.status == 403 || response.status == 400,
|
||||
"{path} -> {}",
|
||||
response.status
|
||||
);
|
||||
}
|
||||
let missing = http::get(server.port, "/api/document?path=index.mq.md");
|
||||
assert_eq!(missing.status, 404);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_and_unknown_fields_are_rejected_before_execution() {
|
||||
let server = control_flow();
|
||||
let (session, _) = open_session(&server, "/");
|
||||
let mut payload: serde_json::Value = serde_json::from_str(&run_body(
|
||||
"index.mq.md",
|
||||
&session.digest,
|
||||
serde_json::json!({"kind": "entry"}),
|
||||
"req-unknown",
|
||||
))
|
||||
.unwrap();
|
||||
payload["cwd"] = serde_json::json!("/tmp/elsewhere");
|
||||
let response = submit(&server, &session, &payload.to_string());
|
||||
assert_eq!(response.status, 400);
|
||||
|
||||
let huge = "x".repeat(70 * 1024);
|
||||
let response = http::post(
|
||||
server.port,
|
||||
"/api/runs",
|
||||
&post_headers(&server, &session, true),
|
||||
Some(&huge),
|
||||
);
|
||||
assert_eq!(response.status, 413);
|
||||
assert!(!server.core.dir.join("run-was-called").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_cookie_and_headers_are_hardened() {
|
||||
let server = http::start(
|
||||
"examples/welcome",
|
||||
"tests/golden/analysis-v2/welcome.json",
|
||||
None,
|
||||
None,
|
||||
);
|
||||
let page = http::get(server.port, "/");
|
||||
assert_eq!(page.status, 200);
|
||||
let cookie = page.set_cookie().expect("session cookie");
|
||||
assert!(cookie.contains("HttpOnly"), "cookie: {cookie}");
|
||||
assert!(cookie.contains("SameSite=Strict"), "cookie: {cookie}");
|
||||
assert!(cookie.contains("Path=/"), "cookie: {cookie}");
|
||||
assert!(
|
||||
!cookie.contains("Secure"),
|
||||
"loopback HTTP must not fake HTTPS"
|
||||
);
|
||||
|
||||
let csp = page.header("Content-Security-Policy").expect("csp");
|
||||
assert!(csp.contains("default-src 'self'"));
|
||||
assert!(csp.contains("connect-src 'self'"));
|
||||
assert!(csp.contains("frame-ancestors 'none'"));
|
||||
assert!(!csp.contains("unsafe-inline"));
|
||||
assert!(!csp.contains("unsafe-eval"));
|
||||
assert_eq!(page.header("X-Frame-Options").as_deref(), Some("DENY"));
|
||||
assert_eq!(
|
||||
page.header("X-Content-Type-Options").as_deref(),
|
||||
Some("nosniff")
|
||||
);
|
||||
assert_eq!(
|
||||
page.header("Cross-Origin-Resource-Policy").as_deref(),
|
||||
Some("same-origin")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sec_fetch_site_cross_site_is_rejected_even_with_a_valid_token() {
|
||||
let server = http::start(
|
||||
"examples/control-flow",
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
Some("tests/golden/trace-v2/control-flow.run.json"),
|
||||
Some("tests/golden/trace-v2/control-flow.trace.json"),
|
||||
);
|
||||
let (session, _) = open_session(&server, "/");
|
||||
let body = run_body(
|
||||
"index.mq.md",
|
||||
&session.digest,
|
||||
serde_json::json!({"kind": "entry"}),
|
||||
"req-sec-fetch",
|
||||
);
|
||||
let mut headers = post_headers(&server, &session, true);
|
||||
headers.push(("Sec-Fetch-Site", "cross-site".to_string()));
|
||||
let response = http::post(server.port, "/api/runs", &headers, Some(&body));
|
||||
assert_eq!(response.status, 403);
|
||||
assert!(!server.core.dir.join("run-was-called").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlink_escape_outside_the_project_root_is_rejected() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let project = TempProject::new("security-symlink");
|
||||
project.marqdo_project("普通正文。\n");
|
||||
let outside = TempProject::new("security-outside");
|
||||
outside.write("secret.txt", "TOP SECRET");
|
||||
symlink(&outside.dir, project.dir.join("link")).expect("create symlink");
|
||||
let server = http::start(
|
||||
project.dir.to_str().expect("utf8 path"),
|
||||
"tests/golden/analysis-v2/welcome.json",
|
||||
None,
|
||||
None,
|
||||
);
|
||||
for path in [
|
||||
"/file?path=link/secret.txt",
|
||||
"/file?path=../security-outside/secret.txt",
|
||||
] {
|
||||
let response = http::get(server.port, path);
|
||||
assert!(
|
||||
response.status == 403 || response.status == 404,
|
||||
"{path} -> {}",
|
||||
response.status
|
||||
);
|
||||
assert!(!response.body.contains("TOP SECRET"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adversarial_markdown_never_injects_markup_or_handlers() {
|
||||
let server = http::start(
|
||||
"tests/fixtures/security-project",
|
||||
"tests/golden/analysis-v2/welcome.json",
|
||||
None,
|
||||
None,
|
||||
);
|
||||
let page = http::get(server.port, "/");
|
||||
assert_eq!(page.status, 200);
|
||||
assert!(!page.body.contains("<script>alert"), "script injected");
|
||||
assert!(
|
||||
!page.body.contains("<img src=x"),
|
||||
"event-handler markup injected"
|
||||
);
|
||||
assert!(!page.body.contains("href=\"javascript:alert"));
|
||||
assert!(page.body.contains("mq-raw-omitted") || page.body.contains("普通正文"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sse_requires_a_session_and_only_the_owning_session_can_read_or_cancel() {
|
||||
let server = http::start(
|
||||
"examples/control-flow",
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
Some("tests/golden/trace-v2/control-flow.run.json"),
|
||||
Some("tests/golden/trace-v2/control-flow.trace.json"),
|
||||
);
|
||||
let (owner, _) = open_session(&server, "/");
|
||||
let (other, _) = open_session(&server, "/");
|
||||
let body = run_body(
|
||||
"index.mq.md",
|
||||
&owner.digest,
|
||||
serde_json::json!({"kind": "entry"}),
|
||||
"req-security-owner",
|
||||
);
|
||||
let accepted = http::post(
|
||||
server.port,
|
||||
"/api/runs",
|
||||
&post_headers(&server, &owner, true),
|
||||
Some(&body),
|
||||
)
|
||||
.json();
|
||||
let run_id = accepted["run_id"].as_str().unwrap().to_string();
|
||||
|
||||
let anonymous = http::SseReader::open(server.port, &format!("/api/runs/{run_id}/events"), &[]);
|
||||
assert_eq!(anonymous.status, 401);
|
||||
|
||||
let foreign = http::SseReader::open(
|
||||
server.port,
|
||||
&format!("/api/runs/{run_id}/events"),
|
||||
&[("Cookie", other.cookie.clone())],
|
||||
);
|
||||
assert_eq!(foreign.status, 404);
|
||||
let foreign_cancel = http::post(
|
||||
server.port,
|
||||
&format!("/api/runs/{run_id}/cancel"),
|
||||
&post_headers(&server, &other, false),
|
||||
None,
|
||||
);
|
||||
assert_eq!(foreign_cancel.status, 404);
|
||||
|
||||
// The owner can still cancel; one terminal state is produced.
|
||||
let cancel = http::post(
|
||||
server.port,
|
||||
&format!("/api/runs/{run_id}/cancel"),
|
||||
&post_headers(&server, &owner, false),
|
||||
None,
|
||||
);
|
||||
assert!(cancel.status == 200 || cancel.status == 409);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aggressive_markdown_links_cannot_become_a_file_read_api() {
|
||||
let server = http::start(
|
||||
"examples/welcome",
|
||||
"tests/golden/analysis-v2/welcome.json",
|
||||
None,
|
||||
None,
|
||||
);
|
||||
let page = http::get(server.port, "/");
|
||||
assert_eq!(page.status, 200);
|
||||
for href in ["file:///etc/passwd", "/etc/passwd"] {
|
||||
assert!(
|
||||
!page.body.contains(&format!("href=\"{href}\"")),
|
||||
"unsafe href rendered: {href}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_cannot_be_replayed_to_start_a_new_process() {
|
||||
let server = http::start(
|
||||
"examples/control-flow",
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
Some("tests/golden/trace-v2/control-flow.run.json"),
|
||||
Some("tests/golden/trace-v2/control-flow.trace.json"),
|
||||
);
|
||||
let (session, _) = open_session(&server, "/");
|
||||
let body = run_body(
|
||||
"index.mq.md",
|
||||
&session.digest,
|
||||
serde_json::json!({"kind": "entry"}),
|
||||
"req-security-cancel-replay",
|
||||
);
|
||||
let accepted = http::post(
|
||||
server.port,
|
||||
"/api/runs",
|
||||
&post_headers(&server, &session, true),
|
||||
Some(&body),
|
||||
)
|
||||
.json();
|
||||
let run_id = accepted["run_id"].as_str().unwrap().to_string();
|
||||
let url = format!("/api/runs/{run_id}/cancel");
|
||||
let first = http::post(
|
||||
server.port,
|
||||
&url,
|
||||
&post_headers(&server, &session, false),
|
||||
None,
|
||||
);
|
||||
assert_eq!(first.status, 200);
|
||||
let second = http::post(
|
||||
server.port,
|
||||
&url,
|
||||
&post_headers(&server, &session, false),
|
||||
None,
|
||||
);
|
||||
assert_eq!(second.status, 200);
|
||||
// Unknown/forged ids are 404, never a new execution.
|
||||
let forged = http::post(
|
||||
server.port,
|
||||
"/api/runs/00000000000000000000000000000000/cancel",
|
||||
&post_headers(&server, &session, false),
|
||||
None,
|
||||
);
|
||||
assert_eq!(forged.status, 404);
|
||||
let _ = collect_until_terminal;
|
||||
}
|
||||
Reference in new issue
Block a user