fix: close release-gate defects in platform cfg, strict launch, and semantics
WHY - macOS/Windows failed to compile because `cfg!` left `linux::probe()` in the type-checked branch (E0433). - GitHub-hosted Linux can pass the strict probe and then fail the real launch with EAGAIN; the CLI test treated the inspect snapshot as a permanent promise. - The security matrix shared process-id-based scratch paths, so parallel `cargo test --workspace` made its own tests clobber each other. - Condition paragraphs silently ignored executable `Strong`/`Emph`, and condition parse spans included the code-span backticks. - The corpus had no native power/control-flow/inert fixtures and no independent generic Tool consumers. WHAT - Dispatch strict detection through `#[cfg]` functions; add a non-Linux compile/fail-closed regression test. - Split `linux::run` into an injectable probe/spawn seam; test probe-OK -> launch-EAGAIN returns LaunchFailed and never executes unrestricted. - Make the Linux CLI contract accept only (a) successful isolated run or (b) non-zero, diagnosed, fail-closed refusal with no project stdout. - Give each security test a unique project/outside path and compile the helper once. - Reject executable roles in a condition paragraph; map condition expressions from the literal bytes inside the backticks. - Add 10 AST, 8 semantic, 4 compile-negative and 2 runtime-negative fixtures for power, branch/loop conditions, source spans, inert prose/code fences and error boundaries. - Add `sample-view`/`sample-knowledge`/`sample-proof` independent Tool v1 packages and an end-to-end Analysis/Trace consumer test. - Add a locked path-dependency content-tamper test. TESTS - cargo fmt --all -- --check - cargo clippy --workspace --all-targets -- -D warnings - cargo test --workspace --locked - G-C VM lane (separate evidence commit/run) CI_URL - none from this host: the checkout has a Gitee remote and no GitHub credentials. Windows/macOS CI remains UNVERIFIED. BREAKING_CHANGE - An executable node in a list-item condition paragraph is now a hard `markdown.invalid_construct` error instead of being silently ignored. SECURITY_SCOPE - strict remains fail-closed; no downgrade, no new capability, L2 still rejected. G-C still requires the dedicated self-hosted lane for CI-signed evidence.
This commit is contained in:
1 parent
c9f01aa8fb
commit
d05f36fd26
65 files changed
+2134
-87
No files matched your search
@@ -350,21 +350,77 @@ fn strict_mode_enforces_isolation_or_refuses_closed() {
|
||||
let hello = root.join("examples").join("hello.mq.md");
|
||||
let output = cli(&root, &["run", hello.to_str().unwrap(), "--mode", "strict"]);
|
||||
if strict_is_available(&root) {
|
||||
assert_exit(&output, 0, "strict mode must succeed when the gate passes");
|
||||
assert_eq!(stdout_text(&output), "你好,Marqdo\n");
|
||||
// External execution surfaces are rejected at the strict L1 boundary.
|
||||
let foreign = cli(
|
||||
&root,
|
||||
&[
|
||||
"run",
|
||||
hello.to_str().unwrap(),
|
||||
"--mode",
|
||||
"strict",
|
||||
"--allow-foreign",
|
||||
],
|
||||
if output.status.success() {
|
||||
assert_eq!(stdout_text(&output), "你好,Marqdo\n");
|
||||
// External execution surfaces are rejected at the strict L1 boundary.
|
||||
let foreign = cli(
|
||||
&root,
|
||||
&[
|
||||
"run",
|
||||
hello.to_str().unwrap(),
|
||||
"--mode",
|
||||
"strict",
|
||||
"--allow-foreign",
|
||||
],
|
||||
);
|
||||
assert_exit(&foreign, 2, "strict must reject foreign grants");
|
||||
assert!(stderr_text(&foreign).contains("strict mode currently supports"));
|
||||
return;
|
||||
}
|
||||
|
||||
// The snapshot from `inspect --platform` is not a permanent promise:
|
||||
// the host can lose namespace capability or resources between the
|
||||
// probe and the real launch. GitHub-hosted runners have produced
|
||||
// `bwrap: Creating new namespace failed: Resource temporarily
|
||||
// unavailable` here. The only acceptable outcome is a fail-closed
|
||||
// refusal: non-zero exit, diagnostic, and no project output.
|
||||
assert_exit(
|
||||
&output,
|
||||
1,
|
||||
"strict launch failure must fail closed, not fall back",
|
||||
);
|
||||
assert_exit(&foreign, 2, "strict must reject foreign grants");
|
||||
assert!(stderr_text(&foreign).contains("strict mode currently supports"));
|
||||
let stderr = stderr_text(&output);
|
||||
assert!(!stderr.is_empty(), "strict failure had no diagnostic");
|
||||
assert!(
|
||||
stderr.contains("strict isolation failed")
|
||||
|| stderr.contains("refusing to run in strict mode")
|
||||
|| stderr.contains("bubblewrap")
|
||||
|| stderr.contains("bwrap"),
|
||||
"strict failure diagnostic does not identify isolation: {stderr}"
|
||||
);
|
||||
assert!(
|
||||
stderr.contains("namespace")
|
||||
|| stderr.contains("Resource temporarily unavailable")
|
||||
|| stderr.contains("os error 11"),
|
||||
"strict failure diagnostic does not identify the launch failure: {stderr}"
|
||||
);
|
||||
assert!(
|
||||
stdout_text(&output).is_empty(),
|
||||
"project output appeared although strict launch failed: {}",
|
||||
stdout_text(&output)
|
||||
);
|
||||
|
||||
let json = cli(
|
||||
&root,
|
||||
&["run", hello.to_str().unwrap(), "--mode", "strict", "--json"],
|
||||
);
|
||||
if json.status.success() {
|
||||
let value = json_stdout(&json);
|
||||
assert_eq!(value["success"], true);
|
||||
assert_eq!(value["value"]["type"], "none");
|
||||
} else {
|
||||
assert_exit(
|
||||
&json,
|
||||
1,
|
||||
"strict launch failure keeps exit code 1 in JSON mode",
|
||||
);
|
||||
let value = json_stdout(&json);
|
||||
assert_eq!(value["success"], false);
|
||||
assert!(value["error"]
|
||||
.as_str()
|
||||
.expect("error string")
|
||||
.contains("strict"));
|
||||
}
|
||||
return;
|
||||
}
|
||||
assert_exit(
|
||||
@@ -989,3 +1045,61 @@ fn check_never_spawns_a_foreign_kernel() {
|
||||
"run did not execute the provider; the no-execution assertion is vacuous"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn power_branch_loop_and_inert_code_end_to_end() {
|
||||
let dir = TempDir::new("power");
|
||||
dir.write(
|
||||
"branch.mq.md",
|
||||
"## main\n\n**n = 2**\n\n1. `n ** 2 == 4`,正确分支。\n\n > print(\"乘方正确\")\n\n2. `n ** 2 != 4`,另一分支。\n\n > print(\"乘方错误\")\n",
|
||||
);
|
||||
let branch = cli(dir.path(), &["run", "branch.mq.md", "--json"]);
|
||||
assert_exit(&branch, 0, "power branch run");
|
||||
let value = json_stdout(&branch);
|
||||
assert_eq!(value["success"], true);
|
||||
assert_eq!(value["stdout"], "乘方正确\n");
|
||||
assert_eq!(value["value"]["type"], "unit");
|
||||
|
||||
dir.write(
|
||||
"loop.mq.md",
|
||||
"## main\n\n**n = 0**\n\n**limit = 100**\n\n- `n ** 2 < limit`\n\n **n = n + 1**\n\n*n*\n",
|
||||
);
|
||||
let looped = cli(dir.path(), &["run", "loop.mq.md", "--json"]);
|
||||
assert_exit(&looped, 0, "power loop run");
|
||||
let value = json_stdout(&looped);
|
||||
assert_eq!(value["value"]["type"], "int");
|
||||
assert_eq!(value["value"]["decimal"], "10");
|
||||
|
||||
// A code fence containing power syntax is an inert value: it produces no
|
||||
// diagnostics and never changes the returned value.
|
||||
dir.write(
|
||||
"inert.mq.md",
|
||||
"## main\n\n```text\n**n = 2 ** 3**\n```\n\n正文里的 `2 ** 3` 不执行。\n\n**x = 1**\n\n*x*\n",
|
||||
);
|
||||
let inert = cli(dir.path(), &["run", "inert.mq.md", "--json"]);
|
||||
assert_exit(&inert, 0, "inert code run");
|
||||
let value = json_stdout(&inert);
|
||||
assert_eq!(value["value"]["decimal"], "1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn condition_parse_diagnostic_points_inside_the_code_span() {
|
||||
let dir = TempDir::new("condition-span");
|
||||
let source = "## main\n\n**n = 2**\n\n1. `n ** 2 ==`\n\n > print(1)\n";
|
||||
dir.write("bad.mq.md", source);
|
||||
let output = cli(dir.path(), &["check", "bad.mq.md", "--json"]);
|
||||
assert_exit(&output, 1, "condition parse error");
|
||||
let value = json_stdout(&output);
|
||||
let diagnostic = value["diagnostics"]
|
||||
.as_array()
|
||||
.expect("diagnostics array")
|
||||
.iter()
|
||||
.find(|diagnostic| diagnostic["code"] == "expr.parse")
|
||||
.expect("expr.parse diagnostic");
|
||||
assert_eq!(diagnostic["line"], 5);
|
||||
// 1-based column 14 is the closing backtick: the empty end-of-input span
|
||||
// must not be shifted by the delimiter.
|
||||
assert_eq!(diagnostic["column"], 14);
|
||||
let line = source.lines().nth(4).expect("line 5");
|
||||
assert_eq!(&line[13..14], "`");
|
||||
}
|
||||
@@ -349,3 +349,61 @@ fn deleted_lock_edge_fails_check_and_run() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tampered_path_dependency_content_is_rejected_by_locked_sync() {
|
||||
let dir = TempDir::new("path-tamper");
|
||||
let root = dir.path();
|
||||
write(
|
||||
&root.join("marqdo.yaml"),
|
||||
"project:\n name: root\n version: 0.1.0\ndependencies:\n dep:\n path: ./dep\n",
|
||||
);
|
||||
write(
|
||||
&root.join("dep/marqdo.yaml"),
|
||||
"project:\n name: dep\n version: 0.1.0\n",
|
||||
);
|
||||
write(&root.join("dep/index.mq.md"), "## value\n\n*1*\n");
|
||||
write(
|
||||
&root.join("index.mq.md"),
|
||||
"---\nimport:\n dep: \"@dep\"\n---\n\n## main\n\n*1*\n",
|
||||
);
|
||||
assert_eq!(cli(root, &["lock"]).status.code(), Some(0));
|
||||
let lock_before = std::fs::read(root.join("marqdo.lock")).unwrap();
|
||||
assert_eq!(cli(root, &["sync", "--locked"]).status.code(), Some(0));
|
||||
let env_before = std::fs::read(root.join(".marqdo/env/env.json")).unwrap();
|
||||
|
||||
// Content change after the lock is a tamper/staleness signal. `run` and
|
||||
// `check` must never silently accept it, re-lock, or materialize a new
|
||||
// environment.
|
||||
write(&root.join("dep/index.mq.md"), "## value\n\n*2*\n");
|
||||
for args in [
|
||||
vec!["sync", "--locked"],
|
||||
vec!["run", "index.mq.md"],
|
||||
vec!["check", "index.mq.md"],
|
||||
] {
|
||||
let output = cli(root, &args);
|
||||
assert_eq!(
|
||||
output.status.code(),
|
||||
Some(1),
|
||||
"{args:?}: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(
|
||||
stderr.contains("out of date")
|
||||
|| stderr.contains("digest")
|
||||
|| stderr.contains("integrity"),
|
||||
"{args:?}: {stderr}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
std::fs::read(root.join("marqdo.lock")).unwrap(),
|
||||
lock_before,
|
||||
"a failed locked operation must not rewrite the lock"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(root.join(".marqdo/env/env.json")).unwrap(),
|
||||
env_before,
|
||||
"a failed locked operation must not replace the materialized environment"
|
||||
);
|
||||
}
|
||||
@@ -110,6 +110,134 @@ fn stdout(output: &Output) -> String {
|
||||
String::from_utf8_lossy(&output.stdout).to_string()
|
||||
}
|
||||
|
||||
fn repo_root() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.parent()
|
||||
.expect("crates/cli has a parent")
|
||||
.parent()
|
||||
.expect("crates has a parent")
|
||||
.to_path_buf()
|
||||
}
|
||||
|
||||
/// Compile one of the checked-in independent consumer samples and package it
|
||||
/// as a Tool Protocol v1 bundle. Sources live in `examples/tool-samples/` so
|
||||
/// they are reviewable software, not hidden test strings.
|
||||
fn write_sample_from_source(dir: &Path, command: &str) -> PathBuf {
|
||||
let root = repo_root();
|
||||
let source = root.join(format!("examples/tool-samples/{command}/src/main.rs"));
|
||||
let package = dir.join(format!("{command}-pkg"));
|
||||
std::fs::create_dir_all(package.join("bin")).unwrap();
|
||||
let entry = package
|
||||
.join("bin")
|
||||
.join(format!("{command}{}", std::env::consts::EXE_SUFFIX));
|
||||
let status = Command::new("rustc")
|
||||
.args(["--edition", "2021", "-o"])
|
||||
.arg(&entry)
|
||||
.arg(&source)
|
||||
.status()
|
||||
.expect("run rustc for the sample tool");
|
||||
assert!(status.success(), "rustc failed for {command}");
|
||||
let entrypoint = format!("bin/{command}{}", std::env::consts::EXE_SUFFIX);
|
||||
let manifest = package.join("tool.json");
|
||||
std::fs::write(
|
||||
&manifest,
|
||||
format!(
|
||||
r#"{{"schema":"marqdo.cli-tool","schema_version":1,"name":"demo.{command}","version":"0.1.0","command":"{command}","entrypoint":"{entrypoint}","compatibility":{{"marqdo":">=0.1,<1","analysis":[2],"trace":[2]}}}}"#
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
manifest
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn independent_sample_tools_consume_public_analysis_and_trace() {
|
||||
let dir = TempDir::new("samples");
|
||||
let home = dir.path().join("home");
|
||||
let analysis = dir.path().join("analysis.json");
|
||||
let trace = dir.path().join("trace.json");
|
||||
let root = repo_root();
|
||||
|
||||
let check = Command::new(binary())
|
||||
.args([
|
||||
"check",
|
||||
"examples/multi-module/index.mq.md",
|
||||
"--refs",
|
||||
"--emit",
|
||||
])
|
||||
.arg(&analysis)
|
||||
.current_dir(&root)
|
||||
.output()
|
||||
.expect("run check");
|
||||
assert!(check.status.success(), "check failed: {}", stderr(&check));
|
||||
let run = Command::new(binary())
|
||||
.args(["run", "examples/multi-module/index.mq.md", "--trace-file"])
|
||||
.arg(&trace)
|
||||
.current_dir(&root)
|
||||
.output()
|
||||
.expect("run");
|
||||
assert!(run.status.success(), "run failed: {}", stderr(&run));
|
||||
|
||||
// None of these names exists in the CLI: dispatch must come from the
|
||||
// installed generic tool registry.
|
||||
for command in ["sample-view", "sample-knowledge", "sample-proof"] {
|
||||
let unknown = cli(&home, &[command]);
|
||||
assert_eq!(unknown.status.code(), Some(2), "{command} must be unknown");
|
||||
assert!(stderr(&unknown).contains("unknown command"));
|
||||
let manifest = write_sample_from_source(dir.path(), command);
|
||||
let install = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
|
||||
assert_eq!(
|
||||
install.status.code(),
|
||||
Some(0),
|
||||
"{command}: {}",
|
||||
stderr(&install)
|
||||
);
|
||||
}
|
||||
|
||||
let view = cli(
|
||||
&home,
|
||||
&["sample-view", "--analysis", analysis.to_str().unwrap()],
|
||||
);
|
||||
assert_eq!(view.status.code(), Some(0), "{}", stderr(&view));
|
||||
let text = stdout(&view);
|
||||
assert!(
|
||||
text.contains("sample-view schema=marqdo.analysis version=2"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(text.contains("modules="), "{text}");
|
||||
|
||||
let knowledge = cli(
|
||||
&home,
|
||||
&["sample-knowledge", "--trace", trace.to_str().unwrap()],
|
||||
);
|
||||
assert_eq!(knowledge.status.code(), Some(0), "{}", stderr(&knowledge));
|
||||
let text = stdout(&knowledge);
|
||||
assert!(
|
||||
text.contains("sample-knowledge schema=marqdo.trace version=2"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(text.contains("status=ok"), "{text}");
|
||||
|
||||
let proof = cli(
|
||||
&home,
|
||||
&[
|
||||
"sample-proof",
|
||||
"--analysis",
|
||||
analysis.to_str().unwrap(),
|
||||
"--trace",
|
||||
trace.to_str().unwrap(),
|
||||
],
|
||||
);
|
||||
assert_eq!(proof.status.code(), Some(0), "{}", stderr(&proof));
|
||||
let text = stdout(&proof);
|
||||
assert!(text.contains("sample-proof bound=true"), "{text}");
|
||||
assert!(text.contains("digest=sha256:"), "{text}");
|
||||
|
||||
for command in ["sample-view", "sample-knowledge", "sample-proof"] {
|
||||
let removed = cli(&home, &["tool", "remove", command]);
|
||||
assert_eq!(removed.status.code(), Some(0), "{}", stderr(&removed));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_dispatch_list_remove_without_core_knowledge_of_the_name() {
|
||||
let dir = TempDir::new("roundtrip");
|
||||
|
||||
@@ -294,8 +294,37 @@ impl<'a> Mapper<'a> {
|
||||
);
|
||||
return None;
|
||||
}
|
||||
// The remainder of the condition paragraph is description only. The
|
||||
// semantic mapper does not descend into it, so an executable `Strong`
|
||||
// or `Emph` there would otherwise be silently swallowed. Reject it as
|
||||
// a hard shape error instead of guessing the author's intent.
|
||||
for tail in first.children.iter().skip(1) {
|
||||
if matches!(tail.kind, MdKind::Strong | MdKind::Emph) {
|
||||
self.error_with_hint(
|
||||
codes::MARKDOWN_INVALID_CONSTRUCT,
|
||||
Some(tail.span),
|
||||
format!(
|
||||
"`{}` inside a list-item condition paragraph is not executed and cannot be silently ignored",
|
||||
tail.kind.tag()
|
||||
),
|
||||
"put executable statements in their own paragraph after the condition line",
|
||||
);
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let literal = condition_node.literal.clone().unwrap_or_default();
|
||||
let segments = PayloadSegments::single(&literal, condition_node.span);
|
||||
// `condition_node.span` includes the backtick delimiters. The payload
|
||||
// map must start at the first literal byte so parse diagnostics and
|
||||
// expression spans point at the expression, not at a delimiter.
|
||||
let ticks = match condition_node.kind {
|
||||
MdKind::Code { ticks } => ticks,
|
||||
_ => 0,
|
||||
};
|
||||
let literal_span = Span::new(
|
||||
condition_node.span.start.saturating_add(ticks),
|
||||
condition_node.span.end.saturating_sub(ticks),
|
||||
);
|
||||
let segments = PayloadSegments::single(&literal, literal_span);
|
||||
match parse_expression(&literal) {
|
||||
Ok(mut expr) => {
|
||||
segments.rewrite_expr(&mut expr);
|
||||
|
||||
@@ -259,3 +259,100 @@ mod tests {
|
||||
assert!(error.reason.contains("emph"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod extra_span_tests {
|
||||
use super::*;
|
||||
use marqdo_markdown::parse;
|
||||
|
||||
fn first_strong(source: &str) -> MdNode {
|
||||
let doc = parse(source);
|
||||
let mut found = None;
|
||||
doc.root.walk(&mut |node| {
|
||||
if found.is_none() && node.kind == MdKind::Strong {
|
||||
found = Some(node.clone());
|
||||
}
|
||||
});
|
||||
found.expect("strong node")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_backtick_code_span_maps_inside_both_delimiters() {
|
||||
let source = "**``n = 2 ** 3``**";
|
||||
let node = first_strong(source);
|
||||
let (payload, segments) = PayloadSegments::of(&node).unwrap();
|
||||
assert_eq!(payload, "n = 2 ** 3");
|
||||
let two = payload.find('2').expect("literal 2");
|
||||
let span = segments.map_span(Span::new(two, two + 1));
|
||||
assert_eq!(&source[span.start..span.end], "2");
|
||||
assert_eq!(&source[2..4], "``");
|
||||
assert_eq!(&source[span.start..span.start + 6], "2 ** 3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf8_prefix_and_multiline_payload_map_to_original_bytes() {
|
||||
let source = "**中文 = `2 ** 3`**";
|
||||
let node = first_strong(source);
|
||||
let (payload, segments) = PayloadSegments::of(&node).unwrap();
|
||||
assert_eq!(payload, "中文 = 2 ** 3");
|
||||
let chinese = payload.find("中文").expect("chinese");
|
||||
let span = segments.map_span(Span::new(chinese, chinese + "中文".len()));
|
||||
assert_eq!(&source[span.start..span.end], "中文");
|
||||
let power = payload.find("2 ** 3").expect("power");
|
||||
let span = segments.map_span(Span::new(power, power + "2 ** 3".len()));
|
||||
assert_eq!(&source[span.start..span.end], "2 ** 3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn condition_literal_span_excludes_backticks_for_one_and_two_ticks() {
|
||||
for source in ["## f\n\n1. `n ** 2 ==`\n", "## f\n\n1. ``n ** 2 ==``\n"] {
|
||||
let result = crate::analyze_source("index.mq.md", source);
|
||||
let diagnostic = result
|
||||
.diagnostics
|
||||
.iter()
|
||||
.find(|diagnostic| diagnostic.code == marqdo_value::codes::EXPR_PARSE)
|
||||
.unwrap_or_else(|| panic!("no expr.parse diagnostic for {source:?}"));
|
||||
let span = diagnostic
|
||||
.span
|
||||
.expect("condition parse error has a source span");
|
||||
assert_eq!(
|
||||
source.as_bytes()[span.start],
|
||||
b'`',
|
||||
"span must stop before the closing backtick: {span:?} in {source:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
&source[span.start.saturating_sub(2)..span.start],
|
||||
"==",
|
||||
"span must point at the missing operand"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn condition_description_rejects_executable_roles() {
|
||||
for tail in ["**print(1)**", "*1*"] {
|
||||
let source = format!("## f\n\n1. `n > 0` {tail}\n\n > print(1)\n");
|
||||
let result = crate::analyze_source("index.mq.md", &source);
|
||||
assert!(
|
||||
result
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|diagnostic| diagnostic.code
|
||||
== marqdo_value::codes::MARKDOWN_INVALID_CONSTRUCT),
|
||||
"executable tail `{tail}` was not rejected: {:#?}",
|
||||
result.diagnostics
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn condition_description_allows_inert_inline_content() {
|
||||
let source = "## f\n\n**n = 1**\n\n1. `n > 0` 普通说明、`惰性代码` 与 [链接](#f)。\n\n > print(1)\n";
|
||||
let result = crate::analyze_source("index.mq.md", source);
|
||||
assert!(
|
||||
!result.has_errors(),
|
||||
"inert description was rejected: {:#?}",
|
||||
result.diagnostics
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -111,34 +111,55 @@ impl PlatformCapabilities {
|
||||
/// security contract. The isolated worker transport is implemented, but a
|
||||
/// plain child process is not an OS sandbox.
|
||||
pub fn detect() -> Self {
|
||||
let strict = if cfg!(target_os = "linux") {
|
||||
match linux::probe() {
|
||||
Ok(mechanism) => StrictIsolation::Available { mechanism },
|
||||
Err(reason) => StrictIsolation::Unavailable { reason },
|
||||
}
|
||||
} else if cfg!(target_os = "macos") {
|
||||
StrictIsolation::Unavailable {
|
||||
reason: "no verified macOS sandbox adapter is implemented in this build"
|
||||
.to_string(),
|
||||
}
|
||||
} else if cfg!(target_os = "windows") {
|
||||
StrictIsolation::Unavailable {
|
||||
reason: "no verified Windows job-object/appcontainer adapter is implemented in this build".to_string(),
|
||||
}
|
||||
} else {
|
||||
StrictIsolation::Unavailable {
|
||||
reason: "platform isolation is not implemented for this target".to_string(),
|
||||
}
|
||||
};
|
||||
Self {
|
||||
os: std::env::consts::OS.to_string(),
|
||||
arch: std::env::consts::ARCH.to_string(),
|
||||
strict,
|
||||
strict: detect_strict(),
|
||||
worker_processes: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Detect strict isolation using only code that is compiled for the current
|
||||
/// platform.
|
||||
///
|
||||
/// `cfg!` is a boolean constant and does **not** remove the other branch from
|
||||
/// type checking. Using it around `linux::probe()` made macOS/Windows builds
|
||||
/// reference a module that is not compiled there (`E0433`). The platform
|
||||
/// dispatch therefore lives in dedicated `#[cfg]` functions.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn detect_strict() -> StrictIsolation {
|
||||
match linux::probe() {
|
||||
Ok(mechanism) => StrictIsolation::Available { mechanism },
|
||||
Err(reason) => StrictIsolation::Unavailable { reason },
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn detect_strict() -> StrictIsolation {
|
||||
StrictIsolation::Unavailable {
|
||||
reason: "no verified macOS sandbox adapter is implemented in this build".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn detect_strict() -> StrictIsolation {
|
||||
StrictIsolation::Unavailable {
|
||||
reason: "no verified Windows job-object/appcontainer adapter is implemented in this build"
|
||||
.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
|
||||
fn detect_strict() -> StrictIsolation {
|
||||
StrictIsolation::Unavailable {
|
||||
reason: format!(
|
||||
"platform isolation is not implemented for `{}`",
|
||||
std::env::consts::OS
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Failure to apply the requested sandbox mode.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum SandboxError {
|
||||
@@ -263,4 +284,20 @@ mod tests {
|
||||
assert!(enforce(SandboxMode::Pure, &platform).is_ok());
|
||||
assert!(enforce(SandboxMode::Project, &platform).is_ok());
|
||||
}
|
||||
|
||||
/// macOS and Windows must compile without the Linux-only `linux` module,
|
||||
/// report strict as unavailable, and still refuse strict execution. This
|
||||
/// is the regression guard for the `E0433` platform-detection defect.
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
#[test]
|
||||
fn non_linux_detection_is_compiled_and_fails_closed() {
|
||||
let platform = PlatformCapabilities::detect();
|
||||
assert!(matches!(
|
||||
platform.strict,
|
||||
StrictIsolation::Unavailable { .. }
|
||||
));
|
||||
let error = enforce(SandboxMode::Strict, &platform).expect_err("strict must refuse");
|
||||
assert!(matches!(error, SandboxError::StrictUnavailable { .. }));
|
||||
assert!(!platform.strict.describe().contains("available via"));
|
||||
}
|
||||
}
|
||||
@@ -254,7 +254,28 @@ fn finish(outcome: StrictOutcome) -> Result<i32, SandboxError> {
|
||||
Err(SandboxError::LaunchFailed { message })
|
||||
}
|
||||
|
||||
/// Probe function used by [`run`]. A function pointer keeps the production
|
||||
/// path free of runtime hooks while allowing a unit test to model
|
||||
/// `probe succeeds → launch fails`.
|
||||
type ProbeFn = fn() -> Result<String, String>;
|
||||
|
||||
/// Supervisor spawn function used by [`run`]. See [`ProbeFn`].
|
||||
type SpawnFn = fn(&Path, &[OsString], Stdio, Stdio, u64, u64) -> io::Result<Child>;
|
||||
|
||||
fn run(command: &StrictHostCommand<'_>) -> Result<StrictOutcome, SandboxError> {
|
||||
run_with(command, probe, spawn_supervisor)
|
||||
}
|
||||
|
||||
/// Run one supervised command with injectable probe/spawn steps.
|
||||
///
|
||||
/// The separation is a test seam, not a bypass: any spawn error after a
|
||||
/// successful probe is returned as [`SandboxError::LaunchFailed`] and the
|
||||
/// caller never executes the project without the supervisor.
|
||||
fn run_with(
|
||||
command: &StrictHostCommand<'_>,
|
||||
probe_fn: ProbeFn,
|
||||
spawn_fn: SpawnFn,
|
||||
) -> Result<StrictOutcome, SandboxError> {
|
||||
if command.project_root == Path::new("/") {
|
||||
return Err(SandboxError::LaunchFailed {
|
||||
message: "strict mode refuses to expose the host root as the project".to_string(),
|
||||
@@ -290,7 +311,7 @@ fn run(command: &StrictHostCommand<'_>) -> Result<StrictOutcome, SandboxError> {
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
probe().map_err(|reason| SandboxError::LaunchFailed { message: reason })?;
|
||||
probe_fn().map_err(|reason| SandboxError::LaunchFailed { message: reason })?;
|
||||
let bwrap = bwrap_path().ok_or_else(|| SandboxError::LaunchFailed {
|
||||
message: "bubblewrap disappeared after the probe".to_string(),
|
||||
})?;
|
||||
@@ -336,34 +357,17 @@ fn run(command: &StrictHostCommand<'_>) -> Result<StrictOutcome, SandboxError> {
|
||||
let limit = command.output_limit.max(1024) as u64;
|
||||
let timeout = command.timeout;
|
||||
let cpu_limit = timeout.as_secs().saturating_add(2).max(1);
|
||||
let mut supervisor = Command::new(&bwrap);
|
||||
supervisor
|
||||
.args(&args)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::from(stdout.reopen()?))
|
||||
.stderr(Stdio::from(stderr.reopen()?));
|
||||
// SAFETY: the closure only calls async-signal-safe libc functions
|
||||
// (`setpgid`, `setrlimit`) between fork and exec.
|
||||
unsafe {
|
||||
supervisor.pre_exec(move || {
|
||||
if libc::setpgid(0, 0) != 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
set_limit(libc::RLIMIT_CPU, cpu_limit, cpu_limit)?;
|
||||
set_limit(libc::RLIMIT_AS, MAX_ADDRESS_SPACE, MAX_ADDRESS_SPACE)?;
|
||||
set_limit(libc::RLIMIT_NOFILE, MAX_OPEN_FILES, MAX_OPEN_FILES)?;
|
||||
set_limit(libc::RLIMIT_NPROC, MAX_PROCESSES, MAX_PROCESSES)?;
|
||||
set_limit(libc::RLIMIT_FSIZE, limit, limit)?;
|
||||
set_limit(libc::RLIMIT_STACK, MAX_STACK_BYTES, MAX_STACK_BYTES)?;
|
||||
set_limit(libc::RLIMIT_CORE, 0, 0)?;
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let mut child = supervisor
|
||||
.spawn()
|
||||
.map_err(|error| SandboxError::LaunchFailed {
|
||||
message: format!("cannot start the strict supervisor: {error}"),
|
||||
})?;
|
||||
let mut child = spawn_fn(
|
||||
&bwrap,
|
||||
&args,
|
||||
Stdio::from(stdout.reopen()?),
|
||||
Stdio::from(stderr.reopen()?),
|
||||
limit,
|
||||
cpu_limit,
|
||||
)
|
||||
.map_err(|error| SandboxError::LaunchFailed {
|
||||
message: format!("cannot start the strict supervisor: {error}"),
|
||||
})?;
|
||||
|
||||
let status = match wait_with_deadline(&mut child, timeout) {
|
||||
Ok(status) => status,
|
||||
@@ -385,6 +389,42 @@ fn run(command: &StrictHostCommand<'_>) -> Result<StrictOutcome, SandboxError> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Spawn Bubblewrap with the supervisor's rlimits installed in the child
|
||||
/// before `exec`.
|
||||
fn spawn_supervisor(
|
||||
bwrap: &Path,
|
||||
args: &[OsString],
|
||||
stdout: Stdio,
|
||||
stderr: Stdio,
|
||||
fsize_limit: u64,
|
||||
cpu_limit: u64,
|
||||
) -> io::Result<Child> {
|
||||
let mut supervisor = Command::new(bwrap);
|
||||
supervisor
|
||||
.args(args)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(stdout)
|
||||
.stderr(stderr);
|
||||
// SAFETY: the closure only calls async-signal-safe libc functions
|
||||
// (`setpgid`, `setrlimit`) between fork and exec.
|
||||
unsafe {
|
||||
supervisor.pre_exec(move || {
|
||||
if libc::setpgid(0, 0) != 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
set_limit(libc::RLIMIT_CPU, cpu_limit, cpu_limit)?;
|
||||
set_limit(libc::RLIMIT_AS, MAX_ADDRESS_SPACE, MAX_ADDRESS_SPACE)?;
|
||||
set_limit(libc::RLIMIT_NOFILE, MAX_OPEN_FILES, MAX_OPEN_FILES)?;
|
||||
set_limit(libc::RLIMIT_NPROC, MAX_PROCESSES, MAX_PROCESSES)?;
|
||||
set_limit(libc::RLIMIT_FSIZE, fsize_limit, fsize_limit)?;
|
||||
set_limit(libc::RLIMIT_STACK, MAX_STACK_BYTES, MAX_STACK_BYTES)?;
|
||||
set_limit(libc::RLIMIT_CORE, 0, 0)?;
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
supervisor.spawn()
|
||||
}
|
||||
|
||||
fn set_limit(resource: libc::__rlimit_resource_t, soft: u64, hard: u64) -> io::Result<()> {
|
||||
let limit = libc::rlimit {
|
||||
rlim_cur: soft as libc::rlim_t,
|
||||
@@ -475,3 +515,84 @@ impl Drop for CaptureFile {
|
||||
let _ = fs::remove_file(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Model the GitHub-hosted Linux runner failure: the first probe reports
|
||||
/// that Bubblewrap works, but the real supervisor spawn immediately fails
|
||||
/// with `EAGAIN` (resource/namespace pressure). The contract is fail-closed:
|
||||
/// propagate `LaunchFailed`, never execute the project without isolation.
|
||||
#[test]
|
||||
fn probe_success_then_launch_eagain_is_fail_closed() {
|
||||
if bwrap_path().is_none() {
|
||||
// The seam is about the launch path after a successful probe; a
|
||||
// host without bwrap is covered by the ordinary refusal tests.
|
||||
eprintln!("skipping launch seam test: bubblewrap is not installed");
|
||||
return;
|
||||
}
|
||||
let nanos = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|duration| duration.as_nanos())
|
||||
.unwrap_or(0);
|
||||
let project =
|
||||
std::env::temp_dir().join(format!("marqdo-launch-seam-{}-{nanos}", std::process::id()));
|
||||
fs::create_dir_all(&project).expect("create seam project");
|
||||
|
||||
let command = StrictHostCommand {
|
||||
program: Path::new("/bin/true"),
|
||||
args: &[],
|
||||
project_root: &project,
|
||||
document: None,
|
||||
original_document: None,
|
||||
output_limit: 4096,
|
||||
timeout: Duration::from_secs(1),
|
||||
};
|
||||
let error = run_with(
|
||||
&command,
|
||||
|| Ok("test probe succeeded".to_string()),
|
||||
|_, _, _, _, _, _| Err(io::Error::from_raw_os_error(libc::EAGAIN)),
|
||||
)
|
||||
.expect_err("a spawn failure after a successful probe must not run the project");
|
||||
let _ = fs::remove_dir_all(&project);
|
||||
|
||||
match &error {
|
||||
SandboxError::LaunchFailed { message } => {
|
||||
assert!(
|
||||
message.contains("cannot start the strict supervisor"),
|
||||
"unexpected launch diagnostic: {message}"
|
||||
);
|
||||
assert!(
|
||||
message.contains("Resource temporarily unavailable")
|
||||
|| message.contains("os error 11"),
|
||||
"EAGAIN was not preserved in the diagnostic: {message}"
|
||||
);
|
||||
}
|
||||
other => panic!("expected LaunchFailed, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every non-zero/abnormal child termination is surfaced, never converted
|
||||
/// into a successful unrestricted run.
|
||||
#[test]
|
||||
fn launch_failure_never_falls_back_to_unrestricted_execution() {
|
||||
let command = StrictHostCommand {
|
||||
program: Path::new("/bin/true"),
|
||||
args: &[],
|
||||
project_root: Path::new("/"),
|
||||
document: None,
|
||||
original_document: None,
|
||||
output_limit: 4096,
|
||||
timeout: Duration::from_secs(1),
|
||||
};
|
||||
let error = run_with(
|
||||
&command,
|
||||
|| Ok("probe".into()),
|
||||
|_, _, _, _, _, _| unreachable!("host root must be rejected before spawning"),
|
||||
)
|
||||
.expect_err("host root must be rejected");
|
||||
assert!(matches!(error, SandboxError::LaunchFailed { .. }));
|
||||
assert!(error.to_string().contains("host root"));
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,8 @@ use std::ffi::OsString;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::OnceLock;
|
||||
use std::time::Duration;
|
||||
|
||||
use marqdo_sandbox::{launch_strict_capture, probe, StrictHostCommand, StrictOutcome};
|
||||
@@ -30,28 +32,36 @@ fn required() -> bool {
|
||||
== Some("1")
|
||||
}
|
||||
|
||||
/// Compile the escape helper exactly once even when the test binary runs its
|
||||
/// tests in parallel.
|
||||
fn helper() -> Option<PathBuf> {
|
||||
if let Ok(path) = std::env::var("MARQDO_SECURITY_HELPER") {
|
||||
let path = PathBuf::from(path);
|
||||
assert!(path.is_file(), "MARQDO_SECURITY_HELPER does not exist");
|
||||
return Some(path);
|
||||
}
|
||||
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/security/escape_helper.c");
|
||||
let output = std::env::temp_dir().join(format!(
|
||||
"marqdo-escape-helper-{}{}",
|
||||
std::process::id(),
|
||||
std::env::consts::EXE_SUFFIX
|
||||
));
|
||||
let status = Command::new("cc")
|
||||
.args(["-O2", "-o"])
|
||||
.arg(&output)
|
||||
.arg(&source)
|
||||
.status()
|
||||
.ok()?;
|
||||
if !status.success() {
|
||||
return None;
|
||||
}
|
||||
Some(output)
|
||||
static HELPER: OnceLock<Option<PathBuf>> = OnceLock::new();
|
||||
HELPER
|
||||
.get_or_init(|| {
|
||||
if let Ok(path) = std::env::var("MARQDO_SECURITY_HELPER") {
|
||||
let path = PathBuf::from(path);
|
||||
assert!(path.is_file(), "MARQDO_SECURITY_HELPER does not exist");
|
||||
return Some(path);
|
||||
}
|
||||
let source =
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/security/escape_helper.c");
|
||||
let output = std::env::temp_dir().join(format!(
|
||||
"marqdo-escape-helper-{}{}",
|
||||
std::process::id(),
|
||||
std::env::consts::EXE_SUFFIX
|
||||
));
|
||||
let status = Command::new("cc")
|
||||
.args(["-O2", "-o"])
|
||||
.arg(&output)
|
||||
.arg(&source)
|
||||
.status()
|
||||
.ok()?;
|
||||
if !status.success() {
|
||||
return None;
|
||||
}
|
||||
Some(output)
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
fn setup() -> Option<(PathBuf, PathBuf, PathBuf)> {
|
||||
@@ -72,7 +82,12 @@ fn setup() -> Option<(PathBuf, PathBuf, PathBuf)> {
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let project = std::env::temp_dir().join(format!("marqdo-security-{}", std::process::id()));
|
||||
// `cargo test` runs these tests in parallel. The project and outside
|
||||
// paths must be unique per test or two tests can remove each other's
|
||||
// project between the supervisor mount and the assertion.
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let id = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let project = std::env::temp_dir().join(format!("marqdo-security-{}-{id}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&project);
|
||||
fs::create_dir_all(&project).expect("create security project");
|
||||
fs::write(project.join("allowed.txt"), "allowed\n").expect("write allowed file");
|
||||
@@ -81,7 +96,7 @@ fn setup() -> Option<(PathBuf, PathBuf, PathBuf)> {
|
||||
let home = std::env::var_os("HOME")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from("/home"));
|
||||
let outside = home.join(format!("marqdo-escape-{}", std::process::id()));
|
||||
let outside = home.join(format!("marqdo-escape-{}-{id}", std::process::id()));
|
||||
let _ = fs::remove_file(&outside);
|
||||
Some((helper, project, outside))
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user