Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pkgs/id/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions pkgs/id/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ web = [
"dep:futures",
"dep:rmp-serde",
"dep:comrak",
"dep:url",
"dep:urlencoding",
"dep:aes-gcm",
"dep:hkdf",
Expand Down Expand Up @@ -137,6 +138,7 @@ mime_guess = { version = "2", optional = true }
futures = { version = "0.3.32", optional = true }
rmp-serde = { version = "1", optional = true }
comrak = { version = "0.56", default-features = false, optional = true }
url = { version = "2", optional = true }
urlencoding = { version = "2", optional = true }
aes-gcm = { version = "0.11", default-features = false, features = [
"aes",
Expand Down
99 changes: 99 additions & 0 deletions pkgs/id/src/web/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,34 @@ use comrak::nodes::{AstNode, ListDelimType, ListType, NodeValue};
use comrak::{Arena, Options, format_commonmark, parse_document};
use serde_json::{Value, json};

/// Whether a URL is safe to preserve as an imported link.
///
/// Scheme-less references (including protocol-relative URLs) are allowed.
/// Explicit schemes are limited to HTTP, HTTPS, and mailto. The probe mirrors
/// browser URL handling by trimming leading C0/space characters and removing
/// ASCII tabs/newlines before checking the scheme, without changing the URL we
/// preserve when it is allowed.
fn is_safe_link_url(url: &str) -> bool {
let probe: String = url
.trim_start_matches(|character: char| character <= ' ')
.chars()
.filter(|character| !matches!(character, '\t' | '\n' | '\r'))
.collect();
let Some(colon) = probe.find(':') else {
return true;
};
let first_reference_delimiter = probe
.find(|character| matches!(character, '/' | '?' | '#'))
.unwrap_or(probe.len());
if colon > first_reference_delimiter {
return true;
}
let scheme = &probe[..colon];
["http", "https", "mailto"]
.iter()
.any(|allowed| scheme.eq_ignore_ascii_case(allowed))
Comment on lines +61 to +63

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the repository's native reference URL scheme

When importing Markdown containing the repository's supported reference format, this allowlist rejects id://{hash} and id://{hash}@{revision}, which Reference::to_markdown explicitly emits in pkgs/id/src/references.rs:130–145. The link conversion consequently replaces those targets with about:invalid. Since Markdown is imported through this converter (collab.rs:151) and saved from the converted document (routes.rs:2595–2599), opening and saving such a document permanently discards its reference targets. Preserve validated native reference URLs rather than treating them as executable schemes.

Useful? React with 👍 / 👎.

}

/// Error type for markdown conversion.
#[derive(Debug)]
pub enum ConversionError {
Expand Down Expand Up @@ -2989,6 +3017,10 @@ fn convert_node<'a>(node: &'a AstNode<'a>, active_marks: &[Mark]) -> Value {
if !link.title.is_empty() {
attrs["title"] = json!(link.title);
}
// Reject executable/unknown schemes to prevent XSS via imported Markdown.
if !is_safe_link_url(link.url) {
attrs["href"] = json!("about:invalid");
Comment on lines +3021 to +3022

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restore protected newlines before validating link schemes

For a safe destination containing a leading newline or a newline within its HTTPS scheme, such as [x](<https\n://example.com>), the existing protect_newline_destinations pass replaces the newline with a placeholder before conversion. This check therefore sees httpsidweb-newline-0-token: rather than https: and replaces the destination with about:invalid. restore_attr_newlines runs only after conversion (markdown.rs:167–180), when the original target has already been discarded. Validate the restored destination instead of the placeholder-bearing string so the codec's supported newline-preserving links remain intact while executable schemes are still rejected.

Useful? React with 👍 / 👎.

}
marks.push(Mark {
mark_type: "link",
attrs: Some(attrs),
Expand Down Expand Up @@ -3446,6 +3478,10 @@ fn linked_image_sequence<'a>(children: &[&'a AstNode<'a>]) -> Option<(Value, usi
}
let (href, link_title) = parse_anchor_tag(&html_inline_literal(children[0])?)?;
let img = parse_img_tag(&html_inline_literal(children[1])?)?;
// Reject executable/unknown schemes in linked-image hrefs.
if !is_safe_link_url(&href) {
return None; // Drop the linked-image sequence to avoid storing an unsafe linkHref.
}
let consumed = if children.len() >= 3
&& html_inline_literal(children[2]).is_some_and(|h| h.trim().eq_ignore_ascii_case("</a>"))
{
Expand Down Expand Up @@ -3897,6 +3933,10 @@ fn parse_img_tag(html: &str) -> Option<Value> {
let attr = |name: &str| parsed.get(name).map(String::as_str);

let src = attr("src")?; // src is required
// Reject executable/unknown schemes in image src.
if !is_safe_link_url(src) {
return None;
Comment on lines +3937 to +3938

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve embedded raster images across resize and reopen

For an embedded PNG such as ![pixel](data:image/png;base64,...), the normal Markdown image arm still preserves the source and the editor displays it. Resizing commits dimensions (web/src/image-node-view.ts:225), causing the serializer to emit an HTML <img> instead of Markdown (markdown.rs:4998–5020). On reopening, this new check rejects the same image's data: source, and the HTML fallback displays literal markup instead of the image. Use image-specific source validation that permits safe embedded raster formats, so resizing an otherwise supported image does not break its save/reopen round trip.

Useful? React with 👍 / 👎.

}
let mut attrs = json!({"src": src});

if let Some(alt) = attr("alt") {
Expand Down Expand Up @@ -3943,13 +3983,21 @@ fn parse_anchor_tag(html: &str) -> Option<(String, Option<String>)> {
if href.is_empty() {
return None;
}
// Reject executable/unknown schemes in raw HTML anchors.
if !is_safe_link_url(href) {
return None;
}
let title = parsed.get("title").filter(|t| !t.is_empty()).cloned();
Some((href.clone(), title))
}

/// Attach a wrapping anchor's link to an image node (#880/#893), in the
/// same `linkHref`/`linkTitle` attrs the markdown `Image` arm produces.
fn image_with_link(mut img: Value, href: &str, link_title: Option<&str>) -> Value {
// Reject executable/unknown schemes in linked-image linkHref.
if !is_safe_link_url(href) {
return img; // Drop the linkHref to avoid storing an unsafe URL.
}
img["attrs"]["linkHref"] = json!(href);
if let Some(title) = link_title {
img["attrs"]["linkTitle"] = json!(title);
Expand Down Expand Up @@ -5670,6 +5718,57 @@ pub fn raw_text_to_prosemirror(text: &str) -> Value {
mod tests {
use super::*;

#[test]
fn test_markdown_url_scheme_allowlist() {
// Regression for #5745: executable schemes must be neutralized in imported Markdown.
for bad in ["javascript:alert(1)", "data:text/html,<script>alert(1)</script>", "vbscript:msgbox(1)"] {
let doc = markdown_to_prosemirror(&format!("Click [here]({bad})"));
let link = &doc["content"][0]["content"][0];
assert_eq!(link["type"], "text");
let marks = link["marks"].as_array().unwrap();
Comment on lines +5726 to +5728

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Select the linked nodes in the new regression tests

Both new tests fail before validating the intended behavior. Here, child zero is the unmarked Click text, so accessing its marks with as_array().unwrap() panics. In the linked-image test, content[1] is the separating space rather than the linked image, so its image assertion also fails. Select the marked text and linked image explicitly, as the existing test_link does. After correcting selection, also reconcile the linked-image expectation: the implementation copies the sanitized about:invalid into linkHref, whereas the new test requires that attribute to be absent.

Useful? React with 👍 / 👎.

let link_mark = marks.iter().find(|m| m["type"] == "link").unwrap();
assert_eq!(link_mark["attrs"]["href"], "about:invalid");
}
// Safe schemes must remain unchanged.
for good in ["https://example.com", "http://example.com", "mailto:test@example.com"] {
let doc = markdown_to_prosemirror(&format!("Click [here]({good})"));
let link = &doc["content"][0]["content"][0];
assert_eq!(link["type"], "text");
let marks = link["marks"].as_array().unwrap();
let link_mark = marks.iter().find(|m| m["type"] == "link").unwrap();
assert_eq!(link_mark["attrs"]["href"], good);
}
// Relative/internal links must remain unchanged.
for rel in ["/path", "#section", "../parent"] {
let doc = markdown_to_prosemirror(&format!("Click [here]({rel})"));
let link = &doc["content"][0]["content"][0];
assert_eq!(link["type"], "text");
let marks = link["marks"].as_array().unwrap();
let link_mark = marks.iter().find(|m| m["type"] == "link").unwrap();
assert_eq!(link_mark["attrs"]["href"], rel);
}
}

#[test]
fn test_markdown_linked_image_url_scheme_allowlist() {
// Regression for #5745: linked images must also neutralize unsafe schemes.
for bad in ["javascript:alert(1)", "data:image/svg+xml,<script>alert(1)</script>"] {
let doc = markdown_to_prosemirror(&format!("![alt](img.png) [![alt](img.png)]({bad})"));
let content = doc["content"][0]["content"].as_array().unwrap();
let img = &content[1];
assert_eq!(img["type"], "image");
assert!(img["attrs"].get("linkHref").is_none());
}
// Safe schemes must remain unchanged.
for good in ["https://example.com", "http://example.com"] {
let doc = markdown_to_prosemirror(&format!("![alt](img.png) [![alt](img.png)]({good})"));
let content = doc["content"][0]["content"].as_array().unwrap();
let img = &content[1];
assert_eq!(img["type"], "image");
assert_eq!(img["attrs"]["linkHref"], good);
}
}

#[test]
fn test_empty_document() {
let doc = markdown_to_prosemirror("");
Expand Down
Loading