diff --git a/CHANGELOG.md b/CHANGELOG.md index b3b784d..a381762 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Security + +- Require `url` 2.5.9 or later to avoid nested `blob:` URL origin stack overflow + (RUSTSEC-2026-0592). + ### Added +- Rust decoded email body extraction with clean/full views, omission spans, + conservative quote/signature removal and shared extraction budgets. + - Runnable examples for every surface, run in CI: Rust `documents`, `convert` (DOCX/XLSX/PDF or your own files), `main_content` and `limits`; Python `examples/python/`, Node.js `examples/node/` and WASM `examples/wasm/`, diff --git a/Cargo.lock b/Cargo.lock index 9dd7c68..2653b36 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -745,9 +745,9 @@ dependencies = [ [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -3274,9 +3274,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", diff --git a/Cargo.toml b/Cargo.toml index 2473509..e0fb2b5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,7 +44,7 @@ clap = { version = "4", default-features = false, features = ["derive", "std", " reqwest = { version = "0.13", default-features = false, features = ["rustls", "json"] } # HTML parsing -url = "2" +url = "2.5.9" # RUSTSEC-2026-0592: bound nested blob URL origin handling. scraper = "0.29" ego-tree = "0.11" schemars = "1" diff --git a/README.md b/README.md index 3cdf0a6..4a0efdf 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,13 @@ packages ship with all formats, OCR and URL fetching. The WASM package covers HTML, PDF text and layout, DOCX, spreadsheets, Markdown, CSV/TSV, notebooks and text, without URL fetching or OCR. +Rust callers with already-decoded email alternatives can use +[`email::extract_body`](https://docs.rs/markkit/latest/markkit/email/fn.extract_body.html) +with the `email` feature. It returns clean/full views and byte spans for omitted +trailing quotes or mobile signatures, preserving forwarded and interleaved replies. +Text stays plain text; HTML fallback requires `html` and becomes Markdown. Treat +both views as untrusted content. See the runnable [email example](examples/email_body.rs). + ## Quick start ### Rust diff --git a/crates/markkit/Cargo.toml b/crates/markkit/Cargo.toml index 2fd8f9a..f8f52db 100644 --- a/crates/markkit/Cargo.toml +++ b/crates/markkit/Cargo.toml @@ -164,3 +164,8 @@ required-features = ["docx", "spreadsheet", "pdf"] [[bench]] name = "extraction" harness = false + +[[example]] +name = "email_body" +path = "../../examples/email_body.rs" +required-features = ["email"] diff --git a/crates/markkit/fuzz/Cargo.lock b/crates/markkit/fuzz/Cargo.lock index f3caaa8..95670b6 100644 --- a/crates/markkit/fuzz/Cargo.lock +++ b/crates/markkit/fuzz/Cargo.lock @@ -45,17 +45,11 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" -[[package]] -name = "bytes" -version = "1.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" - [[package]] name = "calamine" -version = "0.37.0" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9ca341b94bc4b29e08970b1a03914fad2dfe177e2ecb67fcd6de9046004aafb" +checksum = "f431b67cba6122a1f7d26b7adafc71bbdf07026095fe811f5efc025d8748e1d8" dependencies = [ "atoi_simd", "byteorder", @@ -91,6 +85,17 @@ dependencies = [ "web-time", ] +[[package]] +name = "cfb" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fef29b910ef2b9dbecc60168d1568d643c633b0518af970c17e83bd5f6e2c94f" +dependencies = [ + "fnv", + "uuid", + "web-time", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -147,7 +152,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a" dependencies = [ "quote", - "syn 3.0.9", + "syn 2.0.119", ] [[package]] @@ -275,9 +280,9 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -559,10 +564,10 @@ checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" [[package]] name = "markkit" -version = "0.1.1" +version = "0.3.1" dependencies = [ "calamine", - "cfb", + "cfb 0.16.0", "ego-tree", "hayro-syntax", "html5ever", @@ -573,7 +578,6 @@ dependencies = [ "serde", "serde_json", "thiserror", - "tokio", "url", "zip", ] @@ -583,7 +587,7 @@ name = "markkit-fuzz" version = "0.0.0" dependencies = [ "arbitrary", - "cfb", + "cfb 0.15.0", "libfuzzer-sys", "markkit", "miniz_oxide", @@ -1058,16 +1062,6 @@ dependencies = [ "zerovec", ] -[[package]] -name = "tokio" -version = "1.54.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" -dependencies = [ - "bytes", - "pin-project-lite", -] - [[package]] name = "typed-path" version = "0.13.0" @@ -1094,9 +1088,9 @@ checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", diff --git a/crates/markkit/src/email.rs b/crates/markkit/src/email.rs new file mode 100644 index 0000000..142131a --- /dev/null +++ b/crates/markkit/src/email.rs @@ -0,0 +1,303 @@ +//! Conservative, reversible views of decoded email bodies. +//! +//! Cleanup is presentation, never a relevance or security verdict. Only a +//! trailing quoted block is hidden; inline replies and forwarded mail remain +//! whole. Hosts retain MIME originals and enforce their own access policy. +//! +//! With the `email` feature enabled: +//! ``` +//! use markkit::{email::{extract_body, EmailBody}, Limits}; +//! let view = extract_body(EmailBody { +//! text: Some("Yes, please.\n\n> Previous request"), +//! html: None, +//! }, Limits::default())?; +//! assert_eq!(view.clean, "Yes, please."); +//! assert!(view.full.contains("Previous request")); +//! # Ok::<(), markkit::Error>(()) +//! ``` + +use crate::{DocumentHint, Limits, Markkit, Result}; +use serde::{Deserialize, Serialize}; + +/// Alternatives decoded by a MIME parser or an inbox provider. +#[derive(Default)] +pub struct EmailBody<'a> { + pub text: Option<&'a str>, + pub html: Option<&'a str>, +} + +/// Derived content is still untrusted. Text input stays plain text; HTML input +/// becomes Markdown. Render text as text, never as raw HTML or trusted Markdown. +/// Omission offsets are UTF-8 byte boundaries in `full`. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct EmailView { + pub clean: String, + pub full: String, + pub source: String, + pub omitted: Vec, + pub warnings: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct EmailOmission { + pub start: usize, + pub end: usize, + pub reason: String, +} + +/// Extract one alternative with bounded work and reversible quote removal. +/// Text is preferred because HTML quote containers can swallow inline answers. +/// No URLs or attachments are fetched. Empty text falls back to HTML. +/// HTML fallback requires the `html` feature; otherwise it fails explicitly. +pub fn extract_body(body: EmailBody<'_>, limits: Limits) -> Result { + limits.check_input( + body.text + .map_or(0, str::len) + .saturating_add(body.html.map_or(0, str::len)), + )?; + let budget = crate::limits::Budget::new(&limits); + budget.check_time()?; + let engine = Markkit::builder() + .limits(limits.clone()) + .preserve_images(false) + .build(); + let (full, source) = if let Some(text) = body.text.filter(|s| !s.trim().is_empty()) { + // Preserve line boundaries for reply detection; plain text is data, + // not Markdown or HTML to execute. Controls are normalized first. + let normalized = crate::text::decode(text.as_bytes()).text; + if normalized.len() > limits.max_output_size { + return Err(crate::Error::ResourceLimit(crate::LimitExceeded::new( + crate::LimitKind::MaxOutputSize, + "email output limit", + ))); + } + (normalized, "text") + } else if let Some(html) = body.html { + ( + engine + .extract_document_sync(html.as_bytes(), DocumentHint::content_type("text/html"))? + .markdown, + "html", + ) + } else { + (String::new(), "text") + }; + let mut view = EmailView { + clean: full.clone(), + full, + source: source.into(), + omitted: vec![], + warnings: vec![], + }; + let mut lines = Vec::new(); + let mut offset = 0; + for line in view.full.split_inclusive('\n') { + budget.check_time()?; + budget.add_nodes(1)?; + lines.push((offset, line.trim())); + offset += line.len(); + } + // Charge every line before a preservation shortcut. Forwarded content must + // obey the same node/time limits, including the empty-body deadline check. + let lower = view.full.to_ascii_lowercase(); + budget.check_time()?; + if lower.contains("forwarded message") + || lower.contains("begin forwarded") + || lower.contains("original message") + { + view.warnings.push("forwarded_content_preserved".into()); + budget.check_time()?; + return Ok(view); + } + let mut end = lines.len(); + while end > 0 && lines[end - 1].1.is_empty() { + end -= 1; + } + // Exact mobile signatures only. Never cut at an arbitrary disclaimer. + if end > 0 + && matches!( + lines[end - 1].1, + "Sent from my iPhone" + | "Sent from my iPad" + | "Get Outlook for iOS" + | "Get Outlook for Android" + ) + { + end -= 1; + view.omitted.push(EmailOmission { + start: lines[end].0, + end: view.full.len(), + reason: "mobile_signature".into(), + }); + } + let tail = end; + while end > 0 && (lines[end - 1].1.is_empty() || lines[end - 1].1.starts_with('>')) { + end -= 1; + } + if lines[end..tail].iter().any(|(_, s)| s.starts_with('>')) { + if end > 0 && lines[end - 1].1.starts_with("On ") && lines[end - 1].1.ends_with("wrote:") { + end -= 1; + } + // If any earlier quote exists, this is an inline reply: retain context. + if lines[..end].iter().any(|(_, s)| s.starts_with('>')) { + view.warnings.push("inline_reply_preserved".into()); + } else { + view.omitted.push(EmailOmission { + start: lines[end].0, + end: lines.get(tail).map_or(view.full.len(), |l| l.0), + reason: "quoted_history".into(), + }); + } + } + let cut = view + .omitted + .iter() + .map(|o| o.start) + .min() + .unwrap_or(view.full.len()); + view.clean = view.full[..cut].trim_end().to_string(); + if view.clean.is_empty() && !view.full.trim().is_empty() { + view.clean.clone_from(&view.full); + view.omitted.clear(); + view.warnings.push("empty_extraction_preserved".into()); + } + budget.check_time()?; + Ok(view) +} + +#[cfg(test)] +mod tests { + use super::*; + fn view(text: &str) -> EmailView { + extract_body( + EmailBody { + text: Some(text), + html: None, + }, + Limits::default(), + ) + .unwrap() + } + #[test] + fn trailing_history_is_reversible() { + let v = view("Yes, please.\n\nOn Monday Alice wrote:\n> Old request\n"); + assert_eq!(v.clean, "Yes, please."); + assert_eq!(v.omitted.len(), 1); + assert!(v.full[v.omitted[0].start..v.omitted[0].end].contains("Old request")); + } + #[test] + fn inline_forwarded_and_signatures_are_conservative() { + for text in [ + "> Question?\nAnswer\n> Another?\n", + "Please handle:\n--- Forwarded message ---\n> Request", + "Hello\n--\nJane, Support\n", + "Our confidentiality notice needs updating\nHere is the actual request", + ] { + assert_eq!(view(text).clean.trim(), text.trim()); + } + assert_eq!(view("Thanks\nSent from my iPhone").clean, "Thanks"); + assert!(!view("> only quoted request").clean.is_empty()); + } + #[test] + fn alternatives_and_unicode_are_bounded() { + let v = extract_body( + EmailBody { + text: Some("Привіт\n\n> old"), + html: Some("

other

"), + }, + Limits::default(), + ) + .unwrap(); + assert_eq!(v.source, "text"); + assert_eq!(v.clean, "Привіт"); + assert!( + extract_body( + EmailBody { + text: Some("long"), + html: Some("also") + }, + Limits::default().max_input_size(7) + ) + .is_err() + ); + assert!( + extract_body( + EmailBody { + text: Some("long"), + html: None + }, + Limits::default().max_output_size(2) + ) + .is_err() + ); + } + #[test] + fn security_limits_cover_forwarded_and_empty_bodies() { + for text in ["Forwarded message\nrequest", "ordinary\nrequest"] { + let error = extract_body( + EmailBody { + text: Some(text), + html: None, + }, + Limits::default().max_nodes(1), + ) + .unwrap_err(); + assert!( + matches!(error, crate::Error::ResourceLimit(e) if e.kind == crate::LimitKind::MaxNodes) + ); + } + for text in ["", "Forwarded message\nrequest", "ordinary"] { + let error = extract_body( + EmailBody { + text: Some(text), + html: None, + }, + Limits::default().timeout(std::time::Duration::ZERO), + ) + .unwrap_err(); + assert!( + matches!(error, crate::Error::ResourceLimit(e) if e.kind == crate::LimitKind::Timeout) + ); + } + } + #[test] + fn security_plain_text_remains_data_and_spans_are_utf8_boundaries() { + let v = + view("Привіт \r\n\0\u{7f}\n> історія\nSent from my iPhone"); + assert_eq!(v.clean, "Привіт "); + assert!(!v.full.contains(['\0', '\r', '\u{7f}'])); + assert_eq!(v.omitted.len(), 2); + for omission in &v.omitted { + assert!(v.full.get(omission.start..omission.end).is_some()); + } + assert!(v.full.contains("історія")); + } + #[cfg(not(feature = "html"))] + #[test] + fn html_requires_explicit_support() { + assert!( + extract_body( + EmailBody { + text: None, + html: Some("

Hello

") + }, + Limits::default() + ) + .is_err() + ); + } + #[cfg(feature = "html")] + #[test] + fn html_fallback_drops_active_content() { + let v = extract_body( + EmailBody { + text: Some(" "), + html: Some("

Hello

"), + }, + Limits::default(), + ) + .unwrap(); + assert!(v.clean.contains("Hello")); + assert!(!v.clean.contains("steal")); + } +} diff --git a/crates/markkit/src/lib.rs b/crates/markkit/src/lib.rs index 959f67e..b3cbfa2 100644 --- a/crates/markkit/src/lib.rs +++ b/crates/markkit/src/lib.rs @@ -164,6 +164,8 @@ mod csv; #[cfg(feature = "docx")] mod docx; #[cfg(feature = "email")] +pub mod email; +#[cfg(feature = "email")] mod eml; #[cfg(feature = "epub")] mod epub; diff --git a/examples/README.md b/examples/README.md index 96e0a1e..c823e4a 100644 --- a/examples/README.md +++ b/examples/README.md @@ -19,6 +19,7 @@ Run from the repository root: |---|---|---| | [`basic.rs`](basic.rs) | `cargo run -p markkit --example basic` | HTML to Markdown with defaults | | [`documents.rs`](documents.rs) | `cargo run -p markkit --example documents` | `extract_document_sync`: format detection, title, metadata, stats, warnings, unsupported formats | +| [`email_body.rs`](email_body.rs) | `cargo run -p markkit --features email --example email_body` | Decoded email clean/full views and reversible omission spans | | [`convert.rs`](convert.rs) | `cargo run -p markkit --features all_formats --example convert [-- FILE...]` | Convert DOCX, XLSX, PDF (or your own files) | | [`main_content.rs`](main_content.rs) | `cargo run -p markkit --example main_content` | Article detection, `base_url`, selectors | | [`custom_selectors.rs`](custom_selectors.rs) | `cargo run -p markkit --example custom_selectors` | CSS include / exclude selectors | diff --git a/examples/email_body.rs b/examples/email_body.rs new file mode 100644 index 0000000..419ad18 --- /dev/null +++ b/examples/email_body.rs @@ -0,0 +1,25 @@ +//! Provider-decoded mail: show a concise preview while keeping quoted context. +use markkit::{ + Limits, + email::{EmailBody, extract_body}, +}; + +fn main() -> markkit::Result<()> { + let view = extract_body( + EmailBody { + text: Some("Yes, please.\n\nOn Monday Alice wrote:\n> Should we reschedule?\n"), + html: None, + }, + Limits::default().max_input_size(64 * 1024), + )?; + assert_eq!(view.clean, "Yes, please."); + println!("Clean: {}", view.clean); + for omitted in &view.omitted { + println!( + "Preserved {}: {}", + omitted.reason, + &view.full[omitted.start..omitted.end] + ); + } + Ok(()) +} diff --git a/knowledge/formats/format-support.md b/knowledge/formats/format-support.md index ee5ca0a..43dceb1 100644 --- a/knowledge/formats/format-support.md +++ b/knowledge/formats/format-support.md @@ -465,3 +465,19 @@ decoded in the pre-scan, and separately the total content interpreted, form reus - [HTML Extraction](html-extraction.md), the Tier 1 path - [IR Specification](../foundations/ir.md), the shared output of every parser - [Threat Model](../security/threat-model.md), T6 malicious office documents, T7 text and Markdown, T8 malicious PDFs + +## Decoded email body views + +The Rust `email::extract_body` API accepts provider-decoded text and HTML without +requiring callers to synthesize MIME. It prefers text, otherwise extracts HTML +without remote image loading. It returns both a full normalized representation +and a clean view with omission spans. Only conservative trailing quotes and exact +mobile signatures are removed; forwarded and interleaved content is retained. +Text stays plain text and must be displayed as text; HTML fallback requires `html` +and returns Markdown. Omission offsets are UTF-8 byte boundaries in the full view. +Combined input, output, node and time budgets apply, including forwarded and empty +bodies. This is deterministic noise +reduction, not authentication, a relevance judge or a prompt-injection defense. +See [implementation](../../crates/markkit/src/email.rs). Provider/raw MIME storage +and progressive disclosure belong to the caller; bindings retain their existing +EML APIs. diff --git a/knowledge/log.md b/knowledge/log.md index e83929d..7a69eb2 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -1,5 +1,11 @@ # Markkit Knowledge Update Log +## 2026-11-25 + +- [Threat Model](security/threat-model.md): require `url` 2.5.9 for RUSTSEC-2026-0592; shipping audit rejects the prior locked version. + +- [Format Support](formats/format-support.md): bounded decoded email clean/full views with conservative omission spans; no model or network. [Threat Model](security/threat-model.md) records plain-text rendering responsibility and limit checks on forwarded/empty bodies; runnable example covers the new Rust API. + ## 2026-11-03 * **Registries in sync**: `release.yml` now dispatches the PyPI, npm and npm WASM publishers (real publish) alongside crates.io from the release tag. 0.2.1 and 0.3.0 had reached crates.io only. See [Release Process](operations/release-process.md). diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index 75ad81f..dca9bef 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -180,6 +180,10 @@ without parsing the message. ### T3: Server-Side Request Forgery (SSRF) +The URL parser requires `url` >= 2.5.9 (RUSTSEC-2026-0592), which prevents +recursive origin evaluation of nested `blob:` URLs. This dependency floor also +applies to downstream library consumers rather than only this workspace lockfile. + **Description**: Attacker provides URL pointing to internal services or private networks. **Impact**: High -- access to internal infrastructure. @@ -365,6 +369,12 @@ raw HTML (`