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
@@ -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");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user