|
9 | 9 |
|
10 | 10 |
|
11 | 11 | class TestInlineParserSecurity(TestCase): |
| 12 | + def assert_max_token_depth(self, tokens, token_type, max_depth): |
| 13 | + stack = [(token, 0) for token in tokens] |
| 14 | + while stack: |
| 15 | + token, depth = stack.pop() |
| 16 | + if token["type"] == token_type: |
| 17 | + depth += 1 |
| 18 | + self.assertLessEqual(depth, max_depth) |
| 19 | + for child in token.get("children", ()): |
| 20 | + stack.append((child, depth)) |
| 21 | + |
12 | 22 | def test_link_title_redos_payload_returns_quickly(self): |
13 | 23 | md = create_markdown() |
14 | 24 | payload = '[x](y "' + "\\!" * 24 + ")" |
@@ -72,3 +82,34 @@ def test_deep_emphasis_input_does_not_recurse_forever(self): |
72 | 82 | self.assertLess(elapsed, DEADLINE) |
73 | 83 | self.assertLessEqual(html.count("<strong>") + html.count("<em>"), 20) |
74 | 84 | self.assertTrue(ast) |
| 85 | + |
| 86 | + def test_deep_image_input_does_not_recurse_forever(self): |
| 87 | + text = "" * 1000 |
| 88 | + |
| 89 | + start = time.monotonic() |
| 90 | + create_markdown()(text) |
| 91 | + ast = create_markdown(renderer="ast")(text) |
| 92 | + elapsed = time.monotonic() - start |
| 93 | + |
| 94 | + self.assertLess(elapsed, DEADLINE) |
| 95 | + self.assert_max_token_depth(ast, "image", 20) |
| 96 | + |
| 97 | + def test_link_with_deep_image_input_does_not_recurse_forever(self): |
| 98 | + text = "[" + "" * 1000 + "](u)" |
| 99 | + |
| 100 | + start = time.monotonic() |
| 101 | + create_markdown()(text) |
| 102 | + ast = create_markdown(renderer="ast")(text) |
| 103 | + elapsed = time.monotonic() - start |
| 104 | + |
| 105 | + self.assertLess(elapsed, DEADLINE) |
| 106 | + self.assert_max_token_depth(ast, "image", 20) |
| 107 | + |
| 108 | + def test_deep_link_input_does_not_recurse_forever(self): |
| 109 | + text = "[" * 1000 + "a" + "](u)" * 1000 |
| 110 | + |
| 111 | + start = time.monotonic() |
| 112 | + create_markdown(renderer="ast")(text) |
| 113 | + elapsed = time.monotonic() - start |
| 114 | + |
| 115 | + self.assertLess(elapsed, DEADLINE) |
0 commit comments