Skip to content

Commit df95582

Browse files
authored
feat(markdown): 内嵌 SVG 按白名单保留绘图元素,脚本、外部引用和 style 仍被剥离 (#32)
markdown.render 的 Ammonia 过滤器放行 SVG 的图形、文字、use、image、渐变、图案、裁剪、蒙版、标记和不加载外部资源的滤镜,以及它们的几何与展示属性;script、foreignObject、style 元素、动画元素、feImage 和 style 属性仍被剥离,use/textPath 只能引用本文档的 #id。共享 fixture markdown-render-v1.json 增加内嵌 SVG 用例,Core 新增测试跑完整份 fixture。
1 parent 62b8a08 commit df95582

3 files changed

Lines changed: 259 additions & 1 deletion

File tree

‎rust/contracts/rust-core-api.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5452,7 +5452,12 @@ these attributes and the original decoded code text.
54525452

54535453
Raw formatting HTML can survive, but scripts, executable attributes, embeds,
54545454
arbitrary inline styles and unsafe URL schemes are removed in Core before
5455-
embedding. Windows asynchronously requests this existing command via its
5455+
embedding. Inline `<svg>` keeps its drawing elements (shapes, text, `use`,
5456+
`image`, gradients, patterns, clips, masks, markers and the non-loading filter
5457+
primitives) with their geometry and presentation attributes; `script`,
5458+
`foreignObject`, `style`, the animation elements, `feImage` and the `style`
5459+
attribute are removed, and `use`/`textPath` may only reference `#id` in the
5460+
same document. Windows asynchronously requests this existing command via its
54565461
central dispatcher, discards obsolete responses and falls back to the sanitized
54575462
fragment if syntax coloring fails. Render failures are shown as localized text;
54585463
there is no frontend Markdown parser fallback. This does not promise Windows

‎rust/crates/project/src/markdown.rs‎

Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,182 @@
33
use ammonia::Builder;
44
use comrak::{markdown_to_html, Options};
55
use serde::{Deserialize, Serialize};
6+
use std::borrow::Cow;
67
use std::collections::HashSet;
78

9+
/// SVG elements that only draw. Inline `<svg>` in a README is a picture: shapes,
10+
/// text, gradients, clips, masks, markers and filters survive, while elements that
11+
/// run or embed something else do not (`script`, `foreignObject`, `style`, the
12+
/// animation elements, `feImage`). Names are the case html5ever gives SVG elements.
13+
const SVG_TAGS: &[&str] = &[
14+
"svg",
15+
"g",
16+
"defs",
17+
"symbol",
18+
"use",
19+
"title",
20+
"desc",
21+
"path",
22+
"rect",
23+
"circle",
24+
"ellipse",
25+
"line",
26+
"polyline",
27+
"polygon",
28+
"text",
29+
"tspan",
30+
"textPath",
31+
"image",
32+
"linearGradient",
33+
"radialGradient",
34+
"stop",
35+
"pattern",
36+
"clipPath",
37+
"mask",
38+
"marker",
39+
"filter",
40+
"feBlend",
41+
"feColorMatrix",
42+
"feComponentTransfer",
43+
"feComposite",
44+
"feDropShadow",
45+
"feFlood",
46+
"feFuncA",
47+
"feFuncB",
48+
"feFuncG",
49+
"feFuncR",
50+
"feGaussianBlur",
51+
"feMerge",
52+
"feMergeNode",
53+
"feMorphology",
54+
"feOffset",
55+
];
56+
57+
/// Geometry and presentation attributes of the SVG elements above. `style` stays
58+
/// out, as it does for HTML; presentation attributes carry the same paint.
59+
const SVG_ATTRIBUTES: &[&str] = &[
60+
"viewBox",
61+
"preserveAspectRatio",
62+
"width",
63+
"height",
64+
"x",
65+
"y",
66+
"x1",
67+
"y1",
68+
"x2",
69+
"y2",
70+
"cx",
71+
"cy",
72+
"r",
73+
"rx",
74+
"ry",
75+
"fx",
76+
"fy",
77+
"d",
78+
"points",
79+
"pathLength",
80+
"transform",
81+
"fill",
82+
"fill-opacity",
83+
"fill-rule",
84+
"stroke",
85+
"stroke-width",
86+
"stroke-linecap",
87+
"stroke-linejoin",
88+
"stroke-miterlimit",
89+
"stroke-dasharray",
90+
"stroke-dashoffset",
91+
"stroke-opacity",
92+
"opacity",
93+
"color",
94+
"display",
95+
"visibility",
96+
"vector-effect",
97+
"shape-rendering",
98+
"text-rendering",
99+
"paint-order",
100+
"clip-path",
101+
"clip-rule",
102+
"clipPathUnits",
103+
"mask",
104+
"maskUnits",
105+
"maskContentUnits",
106+
"filter",
107+
"filterUnits",
108+
"primitiveUnits",
109+
"marker-start",
110+
"marker-mid",
111+
"marker-end",
112+
"markerWidth",
113+
"markerHeight",
114+
"markerUnits",
115+
"refX",
116+
"refY",
117+
"orient",
118+
"offset",
119+
"stop-color",
120+
"stop-opacity",
121+
"gradientUnits",
122+
"gradientTransform",
123+
"spreadMethod",
124+
"patternUnits",
125+
"patternContentUnits",
126+
"patternTransform",
127+
"dx",
128+
"dy",
129+
"rotate",
130+
"textLength",
131+
"lengthAdjust",
132+
"startOffset",
133+
"text-anchor",
134+
"dominant-baseline",
135+
"alignment-baseline",
136+
"baseline-shift",
137+
"font-family",
138+
"font-size",
139+
"font-weight",
140+
"font-style",
141+
"letter-spacing",
142+
"word-spacing",
143+
"text-decoration",
144+
"in",
145+
"in2",
146+
"result",
147+
"mode",
148+
"type",
149+
"values",
150+
"operator",
151+
"k1",
152+
"k2",
153+
"k3",
154+
"k4",
155+
"stdDeviation",
156+
"flood-color",
157+
"flood-opacity",
158+
"radius",
159+
"tableValues",
160+
"slope",
161+
"intercept",
162+
"amplitude",
163+
"exponent",
164+
];
165+
166+
/// Keeps a `use` or `textPath` reference inside the document (`#id`): an
167+
/// external reference would load another file's drawing into this one.
168+
fn svg_reference_filter<'u>(
169+
element: &str,
170+
attribute: &str,
171+
value: &'u str,
172+
) -> Option<Cow<'u, str>> {
173+
if attribute == "href"
174+
&& matches!(element, "use" | "textPath")
175+
&& !value.trim_start().starts_with('#')
176+
{
177+
return None;
178+
}
179+
Some(Cow::Borrowed(value))
180+
}
181+
8182
#[derive(Debug, Deserialize)]
9183
#[serde(rename_all = "camelCase")]
10184
/// Markdown source to render with the shared dialect.
@@ -90,6 +264,18 @@ pub fn render(request: MarkdownRenderRequest) -> MarkdownRenderResponse {
90264
sanitizer.add_tag_attributes(tag, &["align"]);
91265
}
92266

267+
// Inline SVG draws; Ammonia checks that an element only switches into the
268+
// SVG namespace through <svg> and that every href passes the URL schemes.
269+
sanitizer.add_tags(SVG_TAGS);
270+
for tag in SVG_TAGS {
271+
sanitizer.add_tag_attributes(tag, SVG_ATTRIBUTES);
272+
}
273+
sanitizer
274+
.add_tag_attributes("use", &["href"])
275+
.add_tag_attributes("textPath", &["href"])
276+
.add_tag_attributes("image", &["href"])
277+
.attribute_filter(svg_reference_filter);
278+
93279
MarkdownRenderResponse {
94280
html: sanitizer.clean(&rendered).to_string(),
95281
}
@@ -106,6 +292,45 @@ mod tests {
106292
.html
107293
}
108294

295+
#[test]
296+
fn satisfies_shared_render_fixture() {
297+
let fixture: serde_json::Value = serde_json::from_str(include_str!(
298+
"../../../fixtures/editor/markdown-render-v1.json"
299+
))
300+
.expect("Markdown render fixture should decode");
301+
for case in fixture["cases"].as_array().expect("fixture cases") {
302+
let name = case["name"].as_str().expect("case name");
303+
let output = html(case["source"].as_str().expect("case source"));
304+
for want in case["contains"].as_array().expect("contains") {
305+
let want = want.as_str().expect("contains entry");
306+
assert!(output.contains(want), "{name}: lacks {want:?} in {output}");
307+
}
308+
for bad in case["absent"].as_array().expect("absent") {
309+
let bad = bad.as_str().expect("absent entry");
310+
assert!(!output.contains(bad), "{name}: has {bad:?} in {output}");
311+
}
312+
}
313+
}
314+
315+
#[test]
316+
fn inline_svg_keeps_drawing_and_drops_what_runs_or_embeds() {
317+
let output = html(
318+
"<svg viewBox=\"0 0 10 10\"><g transform=\"scale(2)\"><textPath href=\"https://example.com/p\">t</textPath><textPath href=\"#curve\">u</textPath><image href=\"logo.png\" width=\"4\" height=\"4\"/><image href=\"javascript:bad()\"/><filter id=\"f\"><feImage href=\"https://example.com/x.png\"/><feGaussianBlur stdDeviation=\"2\"/></filter><set attributeName=\"fill\" to=\"red\"/><style>rect{fill:red}</style></g></svg>\n",
319+
);
320+
321+
assert!(output.contains("<g transform=\"scale(2)\""));
322+
assert!(output.contains("<textPath href=\"#curve\""));
323+
assert!(!output.contains("example.com/p"));
324+
assert!(output.contains("<image href=\"logo.png\""));
325+
assert!(!output.contains("javascript:"));
326+
assert!(output.contains("<feGaussianBlur stdDeviation=\"2\""));
327+
assert!(!output.contains("feImage"));
328+
assert!(!output.contains("example.com/x.png"));
329+
assert!(!output.contains("<set"));
330+
assert!(!output.contains("<style"));
331+
assert!(!output.contains("fill:red"));
332+
}
333+
109334
#[test]
110335
fn renders_gfm_footnotes_alerts_math_and_shortcodes() {
111336
let output = html(

‎rust/fixtures/editor/markdown-render-v1.json‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,34 @@
104104
"a\n\nb\n"
105105
],
106106
"absent": []
107+
},
108+
{
109+
"name": "inline SVG draws without scripts or external references",
110+
"source": "<p align=\"center\">\n<svg width=\"120\" height=\"40\" viewBox=\"0 0 120 40\" onload=\"bad()\" style=\"position: fixed\">\n<title>Logo</title>\n<defs><linearGradient id=\"fade\" x1=\"0\" x2=\"1\"><stop offset=\"0\" stop-color=\"#36c\"/><stop offset=\"1\" stop-color=\"#9cf\"/></linearGradient></defs>\n<rect x=\"1\" y=\"1\" width=\"118\" height=\"38\" rx=\"6\" fill=\"url(#fade)\" stroke=\"#124\" stroke-width=\"2\"/>\n<path d=\"M10 20 L40 20\" stroke=\"white\" stroke-linecap=\"round\"/>\n<text x=\"60\" y=\"25\" text-anchor=\"middle\" font-size=\"14\" fill=\"white\">Lithe</text>\n<use href=\"#fade-shape\"/>\n<use href=\"https://example.com/sprite.svg#icon\"/>\n<script>bad()</script>\n<foreignObject><div>embedded</div></foreignObject>\n<animate attributeName=\"href\" to=\"javascript:bad()\"/>\n<a href=\"javascript:bad()\"><circle cx=\"5\" cy=\"5\" r=\"3\"/></a>\n</svg>\n</p>\n",
111+
"contains": [
112+
"<svg",
113+
"viewBox=\"0 0 120 40\"",
114+
"<linearGradient id=\"fade\"",
115+
"stop-color=\"#36c\"",
116+
"fill=\"url(#fade)\"",
117+
"stroke-linecap=\"round\"",
118+
"text-anchor=\"middle\"",
119+
">Lithe</text>",
120+
"<title>Logo</title>",
121+
"<use href=\"#fade-shape\"",
122+
"<circle"
123+
],
124+
"absent": [
125+
"onload",
126+
"style=",
127+
"<script",
128+
"bad()",
129+
"foreignObject",
130+
"embedded",
131+
"<animate",
132+
"example.com/sprite.svg",
133+
"javascript:"
134+
]
107135
}
108136
]
109137
}

0 commit comments

Comments
 (0)