lobzique 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +5 -0
  3. data/Cargo.lock +520 -0
  4. data/Cargo.toml +11 -0
  5. data/LICENSE-NOKOGIRI.md +15 -0
  6. data/LICENSE.txt +21 -0
  7. data/README.md +144 -0
  8. data/crates/lobzique-core/Cargo.toml +14 -0
  9. data/crates/lobzique-core/src/css/mod.rs +127 -0
  10. data/crates/lobzique-core/src/css/parser.rs +805 -0
  11. data/crates/lobzique-core/src/css/tables.rs +282 -0
  12. data/crates/lobzique-core/src/css/tests.rs +476 -0
  13. data/crates/lobzique-core/src/css/tokenizer.rs +215 -0
  14. data/crates/lobzique-core/src/css/translate.rs +806 -0
  15. data/crates/lobzique-core/src/css/write.rs +370 -0
  16. data/crates/lobzique-core/src/dom/attribute.rs +144 -0
  17. data/crates/lobzique-core/src/dom/check.rs +160 -0
  18. data/crates/lobzique-core/src/dom/copy.rs +229 -0
  19. data/crates/lobzique-core/src/dom/mod.rs +298 -0
  20. data/crates/lobzique-core/src/dom/namespace.rs +134 -0
  21. data/crates/lobzique-core/src/dom/node.rs +129 -0
  22. data/crates/lobzique-core/src/dom/path.rs +116 -0
  23. data/crates/lobzique-core/src/dom/reparent.rs +308 -0
  24. data/crates/lobzique-core/src/dom/tests.rs +1057 -0
  25. data/crates/lobzique-core/src/dom/text.rs +159 -0
  26. data/crates/lobzique-core/src/dom/tree.rs +446 -0
  27. data/crates/lobzique-core/src/html5/mod.rs +28 -0
  28. data/crates/lobzique-core/src/html5/parse.rs +838 -0
  29. data/crates/lobzique-core/src/html5/serialize.rs +181 -0
  30. data/crates/lobzique-core/src/html5/tests.rs +548 -0
  31. data/crates/lobzique-core/src/lib.rs +12 -0
  32. data/crates/lobzique-core/src/work.rs +26 -0
  33. data/crates/lobzique-core/src/xml/mod.rs +8 -0
  34. data/crates/lobzique-core/src/xml/serialize.rs +681 -0
  35. data/crates/lobzique-core/src/xml/tests.rs +174 -0
  36. data/crates/lobzique-core/src/xpath/ast.rs +415 -0
  37. data/crates/lobzique-core/src/xpath/chars.rs +139 -0
  38. data/crates/lobzique-core/src/xpath/eval.rs +1305 -0
  39. data/crates/lobzique-core/src/xpath/mod.rs +118 -0
  40. data/crates/lobzique-core/src/xpath/parse.rs +729 -0
  41. data/crates/lobzique-core/src/xpath/tests.rs +921 -0
  42. data/ext/lobzique/Cargo.toml +22 -0
  43. data/ext/lobzique/build.rs +5 -0
  44. data/ext/lobzique/clippy.toml +15 -0
  45. data/ext/lobzique/extconf.rb +6 -0
  46. data/ext/lobzique/src/css/mod.rs +9 -0
  47. data/ext/lobzique/src/css/parser.rs +44 -0
  48. data/ext/lobzique/src/css/selector.rs +101 -0
  49. data/ext/lobzique/src/html4/document.rs +31 -0
  50. data/ext/lobzique/src/html4/mod.rs +7 -0
  51. data/ext/lobzique/src/html5/mod.rs +16 -0
  52. data/ext/lobzique/src/html5ever.rs +278 -0
  53. data/ext/lobzique/src/lib.rs +45 -0
  54. data/ext/lobzique/src/support.rs +156 -0
  55. data/ext/lobzique/src/xml/attr.rs +27 -0
  56. data/ext/lobzique/src/xml/cdata.rs +33 -0
  57. data/ext/lobzique/src/xml/comment.rs +34 -0
  58. data/ext/lobzique/src/xml/document.rs +199 -0
  59. data/ext/lobzique/src/xml/document_fragment.rs +27 -0
  60. data/ext/lobzique/src/xml/dtd.rs +37 -0
  61. data/ext/lobzique/src/xml/mod.rs +44 -0
  62. data/ext/lobzique/src/xml/namespace.rs +56 -0
  63. data/ext/lobzique/src/xml/node.rs +944 -0
  64. data/ext/lobzique/src/xml/node_set.rs +20 -0
  65. data/ext/lobzique/src/xml/syntax_error.rs +33 -0
  66. data/ext/lobzique/src/xml/text.rs +44 -0
  67. data/ext/lobzique/src/xml/xpath_context.rs +305 -0
  68. data/lib/lobzique/action_text.rb +29 -0
  69. data/lib/lobzique/class_resolver.rb +33 -0
  70. data/lib/lobzique/css/selector_cache.rb +36 -0
  71. data/lib/lobzique/css/syntax_error.rb +12 -0
  72. data/lib/lobzique/css/xpath_visitor.rb +60 -0
  73. data/lib/lobzique/css.rb +57 -0
  74. data/lib/lobzique/extension.rb +31 -0
  75. data/lib/lobzique/html.rb +14 -0
  76. data/lib/lobzique/html4/document.rb +235 -0
  77. data/lib/lobzique/html4/document_fragment.rb +75 -0
  78. data/lib/lobzique/html4/encoding_reader.rb +374 -0
  79. data/lib/lobzique/html4.rb +35 -0
  80. data/lib/lobzique/html5/document.rb +106 -0
  81. data/lib/lobzique/html5/document_fragment.rb +113 -0
  82. data/lib/lobzique/html5/node.rb +66 -0
  83. data/lib/lobzique/html5.rb +92 -0
  84. data/lib/lobzique/html5ever.rb +14 -0
  85. data/lib/lobzique/rails_dom_testing.rb +95 -0
  86. data/lib/lobzique/sanitizer/concerns.rb +110 -0
  87. data/lib/lobzique/sanitizer/document.rb +14 -0
  88. data/lib/lobzique/sanitizer/document_fragment.rb +12 -0
  89. data/lib/lobzique/sanitizer/escape_raw_text_in_select.rb +31 -0
  90. data/lib/lobzique/sanitizer/scrubbers.rb +46 -0
  91. data/lib/lobzique/sanitizer.rb +96 -0
  92. data/lib/lobzique/syntax_error.rb +8 -0
  93. data/lib/lobzique/version.rb +6 -0
  94. data/lib/lobzique/xml/attr.rb +23 -0
  95. data/lib/lobzique/xml/cdata.rb +13 -0
  96. data/lib/lobzique/xml/character_data.rb +11 -0
  97. data/lib/lobzique/xml/document.rb +149 -0
  98. data/lib/lobzique/xml/document_fragment.rb +109 -0
  99. data/lib/lobzique/xml/dtd.rb +28 -0
  100. data/lib/lobzique/xml/namespace.rb +19 -0
  101. data/lib/lobzique/xml/node/save_options.rb +52 -0
  102. data/lib/lobzique/xml/node.rb +629 -0
  103. data/lib/lobzique/xml/node_set.rb +329 -0
  104. data/lib/lobzique/xml/parse_options.rb +89 -0
  105. data/lib/lobzique/xml/pp/character_data.rb +22 -0
  106. data/lib/lobzique/xml/pp/node.rb +73 -0
  107. data/lib/lobzique/xml/pp.rb +6 -0
  108. data/lib/lobzique/xml/searchable.rb +123 -0
  109. data/lib/lobzique/xml/syntax_error.rb +77 -0
  110. data/lib/lobzique/xml/text.rb +14 -0
  111. data/lib/lobzique/xml/xpath/syntax_error.rb +20 -0
  112. data/lib/lobzique/xml/xpath.rb +16 -0
  113. data/lib/lobzique/xml/xpath_context.rb +27 -0
  114. data/lib/lobzique/xml.rb +22 -0
  115. data/lib/lobzique.rb +15 -0
  116. metadata +177 -0
@@ -0,0 +1,548 @@
1
+ use super::*;
2
+ use crate::dom::{Document, DocumentKind, NamespaceRef, NodeId, NodeKind};
3
+
4
+ fn parse(input: &str) -> Document {
5
+ let (document, _) = parse_document(input.as_bytes(), &Options::default()).unwrap();
6
+ document.check_invariants().unwrap();
7
+ document
8
+ }
9
+
10
+ fn html(document: &Document, id: NodeId) -> String {
11
+ String::from_utf8(serialize(document, id, false, false)).unwrap()
12
+ }
13
+
14
+ fn fragment(input: &str, context: &Context) -> (Document, NodeId) {
15
+ let mut document = Document::new(DocumentKind::Html);
16
+ let fragment = document.create_fragment();
17
+ parse_fragment(
18
+ &mut document,
19
+ fragment,
20
+ input.as_bytes(),
21
+ context,
22
+ &Options::default(),
23
+ )
24
+ .unwrap();
25
+ document.check_invariants().unwrap();
26
+ (document, fragment)
27
+ }
28
+
29
+ fn find(document: &Document, local: &str) -> NodeId {
30
+ document
31
+ .descendants(NodeId::DOCUMENT)
32
+ .find(
33
+ |&id| matches!(document.node_kind(id), NodeKind::Element(e) if &*e.name.local == local),
34
+ )
35
+ .unwrap()
36
+ }
37
+
38
+ #[test]
39
+ fn documents_round_trip() {
40
+ let input = "<!DOCTYPE html><html><head><title>t</title></head>\
41
+ <body><p class=\"a\">x &amp; y<br>z</p></body></html>";
42
+ assert_eq!(html(&parse(input), NodeId::DOCUMENT), input);
43
+ }
44
+
45
+ #[test]
46
+ fn the_doctype_is_the_first_child_wherever_it_was() {
47
+ let document = parse("<!--c--><!DOCTYPE html>");
48
+ assert_eq!(
49
+ html(&document, NodeId::DOCUMENT),
50
+ "<!DOCTYPE html><!--c--><html><head></head><body></body></html>"
51
+ );
52
+ }
53
+
54
+ #[test]
55
+ fn adjacent_text_is_one_node() {
56
+ let document = parse("<table>a<tr>b</tr>c</table>");
57
+ let body = find(&document, "body");
58
+ let first = document.first_child(body).unwrap();
59
+ assert!(matches!(document.node_kind(first), NodeKind::Text(t) if t == b"abc"));
60
+ }
61
+
62
+ #[test]
63
+ fn template_contents_are_its_children() {
64
+ let document = parse("<template><p>x</p></template>");
65
+ let template = find(&document, "template");
66
+ assert_eq!(html(&document, template), "<template><p>x</p></template>");
67
+ }
68
+
69
+ #[test]
70
+ fn foreign_elements_have_gumbos_prefixes() {
71
+ let document = parse("<svg xlink:href=x xmlns:xlink=y><foreignObject/></svg><math></math>");
72
+ let svg = find(&document, "svg");
73
+ assert_eq!(
74
+ document.namespace(svg),
75
+ Some(NamespaceRef {
76
+ prefix: Some("svg"),
77
+ href: "http://www.w3.org/2000/svg"
78
+ })
79
+ );
80
+ let prefixes: Vec<_> = document
81
+ .attributes(svg)
82
+ .iter()
83
+ .map(|&a| document.namespace(a).unwrap().prefix)
84
+ .collect();
85
+ assert_eq!(prefixes, [Some("xlink"), Some("xmlns")]);
86
+ assert_eq!(
87
+ document.namespace(find(&document, "math")).unwrap().prefix,
88
+ Some("math")
89
+ );
90
+ assert_eq!(document.namespace(find(&document, "body")), None);
91
+ assert_eq!(
92
+ html(&document, svg),
93
+ "<svg xlink:href=\"x\" xmlns:xlink=\"y\"><foreignObject></foreignObject></svg>"
94
+ );
95
+ }
96
+
97
+ #[test]
98
+ fn escaping_follows_nokogiri() {
99
+ let document = parse("<p title='\"&<>\u{a0}'>&lt;&gt;&amp;\"\u{a0}</p><script>a<b</script>");
100
+ let body = find(&document, "body");
101
+ assert_eq!(
102
+ html(&document, body),
103
+ "<body><p title=\"&quot;&amp;&lt;&gt;&nbsp;\">&lt;&gt;&amp;\"&nbsp;</p><script>a<b</script></body>"
104
+ );
105
+ }
106
+
107
+ #[test]
108
+ fn preserve_newline_doubles_a_leading_newline() {
109
+ let document = parse("<pre>\n\nx</pre>");
110
+ let pre = find(&document, "pre");
111
+ assert!(prepend_newline(&document, pre));
112
+ assert_eq!(html(&document, pre), "<pre>\nx</pre>");
113
+ assert_eq!(serialize(&document, pre, true, false), b"<pre>\n\nx</pre>");
114
+ }
115
+
116
+ #[test]
117
+ fn noscript_is_markup_unless_asked() {
118
+ let document = parse("<body><noscript><p>x</p></noscript>");
119
+ assert!(matches!(
120
+ document.node_kind(document.first_child(find(&document, "noscript")).unwrap()),
121
+ NodeKind::Element(_)
122
+ ));
123
+ }
124
+
125
+ #[test]
126
+ fn noscript_text_is_escaped_unless_scripting_is_enabled() {
127
+ let options = Options {
128
+ parse_noscript_content_as_text: true,
129
+ ..Options::default()
130
+ };
131
+ let input = b"<body><noscript><p>&lt;</p></noscript>";
132
+ let (document, _) = parse_document(input, &options).unwrap();
133
+ let noscript = find(&document, "noscript");
134
+ assert_eq!(
135
+ serialize(&document, noscript, false, true),
136
+ b"<noscript><p>&lt;</p></noscript>"
137
+ );
138
+ assert_eq!(
139
+ serialize(&document, noscript, false, false),
140
+ b"<noscript>&lt;p&gt;&amp;lt;&lt;/p&gt;</noscript>"
141
+ );
142
+ }
143
+
144
+ #[test]
145
+ fn a_leading_bom_is_dropped_unless_kept() {
146
+ let input = "\u{FEFF}\u{FEFF}x";
147
+ let body = |document: &Document| html(document, find(document, "body"));
148
+ assert_eq!(body(&parse(input)), "<body>\u{FEFF}x</body>");
149
+ let options = Options {
150
+ keep_bom: true,
151
+ ..Options::default()
152
+ };
153
+ let (document, _) = parse_document(input.as_bytes(), &options).unwrap();
154
+ assert_eq!(body(&document), "<body>\u{FEFF}\u{FEFF}x</body>");
155
+
156
+ let context = Context::new(ContextNamespace::Html, "body");
157
+ let (document, root) = fragment(input, &context);
158
+ assert_eq!(html(&document, root), "\u{FEFF}x");
159
+ let mut document = Document::new(DocumentKind::Html);
160
+ let root = document.create_fragment();
161
+ parse_fragment(&mut document, root, input.as_bytes(), &context, &options).unwrap();
162
+ assert_eq!(html(&document, root), input);
163
+ }
164
+
165
+ #[test]
166
+ fn fragments_parse_in_their_context() {
167
+ let (document, root) = fragment("<td>x</td>", &Context::new(ContextNamespace::Html, "TR"));
168
+ assert_eq!(html(&document, root), "<td>x</td>");
169
+ let (document, root) = fragment("<td>x</td>", &Context::new(ContextNamespace::Html, "body"));
170
+ assert_eq!(html(&document, root), "x");
171
+ let (document, root) = fragment("<p>x", &Context::new(ContextNamespace::Svg, "svg"));
172
+ assert_eq!(
173
+ document.namespace(document.first_child(root).unwrap()),
174
+ None
175
+ );
176
+ assert_eq!(html(&document, root), "<p>x</p>");
177
+ }
178
+
179
+ #[test]
180
+ fn parsing_in_context_leaves_each_node_unlinked() {
181
+ let mut document = Document::new(DocumentKind::Html);
182
+ let context = Context::new(ContextNamespace::Html, "div");
183
+ let (nodes, _) = parse_in_context(
184
+ &mut document,
185
+ b"<p>a</p>b<svg/>",
186
+ &context,
187
+ &Options::default(),
188
+ )
189
+ .unwrap();
190
+ document.check_invariants().unwrap();
191
+ let parts: Vec<_> = nodes.iter().map(|&id| html(&document, id)).collect();
192
+ assert_eq!(parts, ["<p>a</p>", "b", "<svg></svg>"]);
193
+ for &id in &nodes {
194
+ assert_eq!(document.parent(id), None);
195
+ assert_eq!(document.previous_sibling(id), None);
196
+ assert_eq!(document.next_sibling(id), None);
197
+ }
198
+ assert!(document
199
+ .namespace_definitions(nodes[2])
200
+ .iter()
201
+ .any(|ns| ns.prefix.as_deref() == Some("svg")));
202
+ }
203
+
204
+ #[test]
205
+ fn parsing_in_context_adds_only_what_it_returns() {
206
+ let mut document = Document::new(DocumentKind::Html);
207
+ let context = Context::new(ContextNamespace::Html, "div").with_form_ancestor(true);
208
+ let before = document.node_ids().len();
209
+ let (nodes, _) = parse_in_context(
210
+ &mut document,
211
+ b"<html lang=en><p>a</p>",
212
+ &context,
213
+ &Options::default(),
214
+ )
215
+ .unwrap();
216
+ // the p and its text
217
+ assert_eq!(document.node_ids().len(), before + 2);
218
+ assert_eq!(html(&document, nodes[0]), "<p>a</p>");
219
+
220
+ let options = Options {
221
+ max_tree_depth: Some(1),
222
+ ..Options::default()
223
+ };
224
+ let error = parse_in_context(&mut document, b"<p><b>c</b></p>", &context, &options);
225
+ assert_eq!(error.unwrap_err(), LimitError::TreeTooDeep);
226
+ assert_eq!(document.node_ids().len(), before + 2);
227
+ document.check_invariants().unwrap();
228
+ }
229
+
230
+ /// Parses `input` in the context `Context::for_node` finds for the first
231
+ /// `local` element of `page`, or for the document if `local` is empty.
232
+ fn in_context_of(page: &str, local: &str, parsed: bool, input: &str) -> (Document, Vec<NodeId>) {
233
+ let mut document = parse(page);
234
+ let node = if local.is_empty() {
235
+ NodeId::DOCUMENT
236
+ } else {
237
+ find(&document, local)
238
+ };
239
+ let context = Context::for_node(&document, node, parsed);
240
+ let (nodes, _) = parse_in_context(
241
+ &mut document,
242
+ input.as_bytes(),
243
+ &context,
244
+ &Options::default(),
245
+ )
246
+ .unwrap();
247
+ document.check_invariants().unwrap();
248
+ (document, nodes)
249
+ }
250
+
251
+ #[test]
252
+ fn a_nodes_context_is_the_nearest_element() {
253
+ let (document, nodes) = in_context_of("<table><tr><td>", "tr", true, "<td>x</td>");
254
+ assert_eq!(html(&document, nodes[0]), "<td>x</td>");
255
+ let (_, nodes) = in_context_of("<form><div>", "div", true, "<form></form>");
256
+ assert!(nodes.is_empty());
257
+ let (document, nodes) = in_context_of("<svg><g>", "g", true, "<p>x");
258
+ assert_eq!(document.namespace(nodes[0]), None);
259
+ let page = "<math><annotation-xml encoding=text/html><mi>";
260
+ let (document, nodes) = in_context_of(page, "annotation-xml", true, "<x>");
261
+ assert_eq!(document.namespace(nodes[0]), None);
262
+ let page = "<math><annotation-xml><mi>";
263
+ let (document, nodes) = in_context_of(page, "annotation-xml", true, "<x>");
264
+ assert_eq!(document.namespace(nodes[0]).unwrap().prefix, Some("math"));
265
+ }
266
+
267
+ #[test]
268
+ fn a_nodes_context_takes_the_quirks_mode_of_a_parsed_document() {
269
+ let (document, nodes) = in_context_of("<p>", "", true, "<p><table>");
270
+ assert_eq!(html(&document, nodes[0]), "<p><table></table></p>");
271
+ let (document, nodes) = in_context_of("<p>", "", false, "<p><table>");
272
+ assert_eq!(html(&document, nodes[0]), "<p></p>");
273
+ let (document, nodes) = in_context_of("<!DOCTYPE html>", "body", true, "<p><table>");
274
+ assert_eq!(html(&document, nodes[0]), "<p></p>");
275
+ }
276
+
277
+ #[test]
278
+ fn a_form_ancestor_drops_nested_forms() {
279
+ let body = Context::new(ContextNamespace::Html, "body");
280
+ let (document, root) = fragment("<form></form>", &body.clone().with_form_ancestor(true));
281
+ assert_eq!(html(&document, root), "");
282
+ let (document, root) = fragment("<form></form>", &body);
283
+ assert_eq!(html(&document, root), "<form></form>");
284
+ }
285
+
286
+ #[test]
287
+ fn quirks_mode_comes_from_the_doctype() {
288
+ assert_eq!(
289
+ quirks_mode_for_doctype(Some(b"html"), None, None),
290
+ QuirksMode::NoQuirks
291
+ );
292
+ assert_eq!(
293
+ quirks_mode_for_doctype(None, None, None),
294
+ QuirksMode::Quirks
295
+ );
296
+ let public = b"-//W3C//DTD HTML 4.01 Transitional//EN";
297
+ assert_eq!(
298
+ quirks_mode_for_doctype(Some(b"html"), Some(public), Some(b"x")),
299
+ QuirksMode::LimitedQuirks
300
+ );
301
+ let (_, parsed) = parse_document(b"<p>", &Options::default()).unwrap();
302
+ assert_eq!(parsed.quirks_mode, QuirksMode::Quirks);
303
+ }
304
+
305
+ #[test]
306
+ fn fragments_report_their_contexts_quirks_mode() {
307
+ let mut document = Document::new(DocumentKind::Html);
308
+ let root = document.create_fragment();
309
+ let context = Context::new(ContextNamespace::Html, "body").with_quirks_mode(QuirksMode::Quirks);
310
+ let parsed = parse_fragment(
311
+ &mut document,
312
+ root,
313
+ b"<p><table>",
314
+ &context,
315
+ &Options::default(),
316
+ )
317
+ .unwrap();
318
+ assert_eq!(parsed.quirks_mode, QuirksMode::Quirks);
319
+ assert_eq!(html(&document, root), "<p><table></table></p>");
320
+ }
321
+
322
+ #[test]
323
+ fn cdata_sections_are_text() {
324
+ let svg = |input: &str| {
325
+ let document = parse(input);
326
+ html(&document, find(&document, "svg"))
327
+ };
328
+ assert_eq!(svg("<svg><![CDATA[a<b]]></svg>"), "<svg>a&lt;b</svg>");
329
+ assert_eq!(svg("<svg>a<![CDATA[b]]> </svg>"), "<svg>ab </svg>");
330
+ assert_eq!(
331
+ svg("<svg><![CDATA[a\0b]]>\0</svg>"),
332
+ "<svg>a\u{fffd}b\u{fffd}</svg>"
333
+ );
334
+ // Escaped text beside a section stays escaped
335
+ assert_eq!(
336
+ svg("<svg>]]&gt;&lt;img onerror=alert(1)&gt;<![CDATA[x]]></svg>"),
337
+ "<svg>]]&gt;&lt;img onerror=alert(1)&gt;x</svg>"
338
+ );
339
+ let document = parse("<svg>a<![CDATA[b]]>c</svg>");
340
+ assert_eq!(document.children(find(&document, "svg")).count(), 1);
341
+ // Not a section: a bogus comment
342
+ assert_eq!(
343
+ svg("<svg><![CDATB[a]]></svg>"),
344
+ "<svg><!--[CDATB[a]]--></svg>"
345
+ );
346
+ }
347
+
348
+ #[test]
349
+ fn depth_counts_open_elements() {
350
+ let options = |depth| Options {
351
+ max_tree_depth: Some(depth),
352
+ ..Options::default()
353
+ };
354
+ // html, body and two divs; the br is never open
355
+ let input = b"<div><div><br>";
356
+ assert!(parse_document(input, &options(4)).is_ok());
357
+ assert_eq!(
358
+ parse_document(input, &options(3)).err(),
359
+ Some(LimitError::TreeTooDeep)
360
+ );
361
+ let mut document = Document::new(DocumentKind::Html);
362
+ let root = document.create_fragment();
363
+ let body = Context::new(ContextNamespace::Html, "body");
364
+ assert!(parse_fragment(&mut document, root, b"<div><div>", &body, &options(2)).is_ok());
365
+ assert_eq!(
366
+ parse_fragment(&mut document, root, b"<div><div>", &body, &options(1)).err(),
367
+ Some(LimitError::TreeTooDeep)
368
+ );
369
+ }
370
+
371
+ #[test]
372
+ fn deep_trees_cost_no_stack() {
373
+ // Deeper input is slow, not dangerous: the scope checks of html5ever walk
374
+ // the stack of open elements, so time grows with the square of the depth.
375
+ // Miri would take hours at full depth.
376
+ let depth = if cfg!(miri) { 100 } else { 5_000 };
377
+ let parse_and_serialize = move || {
378
+ let input = "<div>".repeat(depth);
379
+ let (document, _) = parse_document(input.as_bytes(), &Options::default()).unwrap();
380
+ serialize(&document, NodeId::DOCUMENT, false, false).len()
381
+ };
382
+ let small_stack = std::thread::Builder::new().stack_size(256 * 1024);
383
+ let length = small_stack
384
+ .spawn(parse_and_serialize)
385
+ .unwrap()
386
+ .join()
387
+ .unwrap();
388
+ assert_eq!(length, 11 * depth + 39);
389
+ }
390
+
391
+ #[test]
392
+ fn attributes_are_counted_without_duplicates() {
393
+ let options = Options {
394
+ max_attributes: Some(2),
395
+ ..Options::default()
396
+ };
397
+ assert!(parse_document(b"<p a b a b>", &options).is_ok());
398
+ assert_eq!(
399
+ parse_document(b"</p a b c>", &options).err(),
400
+ Some(LimitError::TooManyAttributes)
401
+ );
402
+ }
403
+
404
+ #[test]
405
+ fn errors_stop_at_the_limit() {
406
+ let options = |max_errors| Options {
407
+ max_errors,
408
+ ..Options::default()
409
+ };
410
+ let input = b"<p>\n</b></i></u>";
411
+ let (_, parsed) = parse_document(input, &options(Some(0))).unwrap();
412
+ assert!(parsed.errors.is_empty());
413
+ let (_, parsed) = parse_document(input, &options(Some(2))).unwrap();
414
+ assert_eq!(parsed.errors.len(), 2);
415
+ let (_, parsed) = parse_document(input, &options(None)).unwrap();
416
+ assert!(parsed.errors.len() > 2);
417
+ assert_eq!(parsed.errors.last().unwrap().line, 2);
418
+ }
419
+
420
+ #[test]
421
+ fn invalid_utf8_is_replaced() {
422
+ let (document, _) = parse_document(b"<p>\xff</p>", &Options::default()).unwrap();
423
+ assert_eq!(
424
+ document.content(find(&document, "p")).unwrap(),
425
+ "\u{fffd}".as_bytes()
426
+ );
427
+ }
428
+
429
+ fn definitions(document: &Document, id: NodeId) -> Vec<&str> {
430
+ document
431
+ .namespace_definitions(id)
432
+ .iter()
433
+ .map(|definition| NamespaceRef::from(definition).prefix.unwrap())
434
+ .collect()
435
+ }
436
+
437
+ #[test]
438
+ fn foreign_namespaces_are_defined_on_the_html_element() {
439
+ let document = parse(
440
+ "<p><svg xmlns=\"http://www.w3.org/2000/svg\"><a xlink:href=x xml:lang=en/></svg><math></math>",
441
+ );
442
+ let html = find(&document, "html");
443
+ assert_eq!(
444
+ definitions(&document, html),
445
+ ["svg", "xmlns", "xlink", "math"]
446
+ );
447
+ assert!(definitions(&document, find(&document, "svg")).is_empty());
448
+ assert!(definitions(&parse("<p>"), NodeId::DOCUMENT).is_empty());
449
+ }
450
+
451
+ #[test]
452
+ fn fragment_namespaces_are_defined_on_each_top_level_element() {
453
+ let context = Context::new(ContextNamespace::Html, "body");
454
+ let (document, fragment) = fragment("<div><svg/></div>text<math/><p></p>", &context);
455
+ let elements: Vec<_> = document.element_children(fragment).collect();
456
+ let defined: Vec<_> = elements
457
+ .iter()
458
+ .map(|&element| definitions(&document, element))
459
+ .collect();
460
+ assert_eq!(defined, [vec!["svg"], vec!["math"], vec![]]);
461
+ }
462
+
463
+ #[test]
464
+ fn fragments_in_xml_documents_have_no_namespace() {
465
+ let mut document = Document::new(DocumentKind::Xml);
466
+ let fragment = document.create_fragment();
467
+ let context = Context::new(ContextNamespace::Html, "body");
468
+ parse_fragment(
469
+ &mut document,
470
+ fragment,
471
+ b"<p>a<svg></svg></p>",
472
+ &context,
473
+ &Options::default(),
474
+ )
475
+ .unwrap();
476
+ document.check_invariants().unwrap();
477
+ let p = document.first_child(fragment).unwrap();
478
+ let svg = document.last_child(p).unwrap();
479
+ let namespace = |document: &Document, id| match document.node_kind(id) {
480
+ NodeKind::Element(element) => element.name.ns.clone(),
481
+ _ => unreachable!(),
482
+ };
483
+ assert_eq!(
484
+ (namespace(&document, p), namespace(&document, svg)),
485
+ (ns!(), ns!(svg))
486
+ );
487
+ assert_eq!(html(&document, fragment), "<p>a<svg></svg></p>");
488
+
489
+ // A parse renames only what it made
490
+ let html_p = document.create_element(QualName::new(
491
+ None,
492
+ ns!(html),
493
+ crate::dom::LocalName::from("p"),
494
+ ));
495
+ parse_fragment(
496
+ &mut document,
497
+ fragment,
498
+ b"<i></i>",
499
+ &context,
500
+ &Options::default(),
501
+ )
502
+ .unwrap();
503
+ let i = document.last_child(fragment).unwrap();
504
+ assert_eq!(namespace(&document, html_p), ns!(html));
505
+ assert_eq!(namespace(&document, i), ns!());
506
+ }
507
+
508
+ #[test]
509
+ fn parsers_go_a_chunk_at_a_time() {
510
+ let count = if cfg!(miri) { 100 } else { 17_000 };
511
+ let input = "<p>chunk".repeat(count);
512
+ let mut parser = DocumentParser::new(input.clone().into_bytes(), &Options::default());
513
+ let mut steps = 0;
514
+ while parser.step() {
515
+ steps += 1;
516
+ }
517
+ assert_eq!(steps, input.len().div_ceil(parse::CHUNK));
518
+ let (document, _) = parser.finish().unwrap();
519
+ assert_eq!(
520
+ html(&document, NodeId::DOCUMENT),
521
+ html(&parse(&input), NodeId::DOCUMENT)
522
+ );
523
+
524
+ let body = Context::new(ContextNamespace::Html, "body");
525
+ let mut parser = FragmentParser::new(input.into_bytes(), &body, &Options::default());
526
+ assert!(parser.step());
527
+ let mut document = Document::new(DocumentKind::Html);
528
+ let root = document.create_fragment();
529
+ parser.finish().unwrap().append_to(&mut document, root);
530
+ assert_eq!(document.children(root).count(), count);
531
+ }
532
+
533
+ #[test]
534
+ fn parsers_stop_stepping_past_a_limit() {
535
+ let options = Options {
536
+ max_tree_depth: Some(10),
537
+ ..Options::default()
538
+ };
539
+ let input = format!(
540
+ "{}{}",
541
+ "<div>".repeat(11),
542
+ "<p>".repeat(if cfg!(miri) { 300 } else { 30_000 })
543
+ );
544
+ let mut parser = DocumentParser::new(input.into_bytes(), &options);
545
+ assert!(parser.step());
546
+ assert!(!parser.step());
547
+ assert_eq!(parser.finish().err(), Some(LimitError::TreeTooDeep));
548
+ }
@@ -0,0 +1,12 @@
1
+ //! The part of lobzique without Ruby: the engine that libxml2 and gumbo
2
+ //! are for Nokogiri. Code here must not depend on magnus or rb-sys, so Miri,
3
+ //! sanitizers and fuzzers can run it without a Ruby VM. See ARCHITECTURE.md.
4
+
5
+ #![forbid(unsafe_code)]
6
+
7
+ pub mod css;
8
+ pub mod dom;
9
+ pub mod html5;
10
+ pub mod work;
11
+ pub mod xml;
12
+ pub mod xpath;
@@ -0,0 +1,26 @@
1
+ //! A count of the work done, for fuzz targets that check how cost grows
2
+ //! with input. A time limit catches only catastrophic slowness, and timing
3
+ //! is too noisy to tell quadratic from linear. A unit is a node read
4
+ //! or created, a byte of text inserted or escaped, or a call from the tokenizer
5
+ //! or tree builder of html5ever. Their own scans of the stack of open elements
6
+ //! go through `elem_name`. Counted only when built with `--cfg fuzzing`,
7
+ //! as cargo-fuzz builds. Otherwise `add` compiles to nothing.
8
+
9
+ #[cfg(fuzzing)]
10
+ thread_local! {
11
+ static UNITS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
12
+ }
13
+
14
+ #[inline(always)]
15
+ pub(crate) fn add(units: usize) {
16
+ #[cfg(fuzzing)]
17
+ UNITS.with(|count| count.set(count.get().saturating_add(units as u64)));
18
+ #[cfg(not(fuzzing))]
19
+ let _ = units;
20
+ }
21
+
22
+ /// The units counted on this thread since the last call.
23
+ #[cfg(fuzzing)]
24
+ pub fn take() -> u64 {
25
+ UNITS.with(|count| count.replace(0))
26
+ }
@@ -0,0 +1,8 @@
1
+ //! XML and XHTML output as libxml2 writes it for Nokogiri, over the arena
2
+ //! DOM. XML parsing is out of scope (plan.md decision 4).
3
+
4
+ mod serialize;
5
+ #[cfg(test)]
6
+ mod tests;
7
+
8
+ pub use serialize::{save_options, write, HtmlUnsupported, Output};