Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/mdit_py_plugins/attrs/index.py: 45%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

136 statements  

1from __future__ import annotations 

2 

3from collections.abc import Sequence 

4from functools import partial 

5import re 

6from typing import Any 

7 

8from markdown_it import MarkdownIt 

9from markdown_it.rules_block import StateBlock 

10from markdown_it.rules_core import StateCore 

11from markdown_it.rules_inline import StateInline 

12from markdown_it.token import Token 

13 

14from mdit_py_plugins.utils import is_code_block 

15 

16from .parse import ParseError, parse 

17 

18 

19def attrs_plugin( 

20 md: MarkdownIt, 

21 *, 

22 after: Sequence[str] = ("image", "code_inline", "link_close", "span_close"), 

23 spans: bool = False, 

24 span_after: str = "link", 

25 allowed: Sequence[str] | None = None, 

26) -> None: 

27 """Parse inline attributes that immediately follow certain inline elements:: 

28 

29 ![alt](https://image.com){#id .a b=c} 

30 

31 This syntax is inspired by 

32 `Djot spans 

33 <https://htmlpreview.github.io/?https://github.com/jgm/djot/blob/master/doc/syntax.html#inline-attributes>`_. 

34 

35 Inside the curly braces, the following syntax is possible: 

36 

37 - `.foo` specifies foo as a class. 

38 Multiple classes may be given in this way; they will be combined. 

39 - `#foo` specifies foo as an identifier. 

40 An element may have only one identifier; 

41 if multiple identifiers are given, the last one is used. 

42 - `key="value"` or `key=value` specifies a key-value attribute. 

43 Quotes are not needed when the value consists entirely of 

44 ASCII alphanumeric characters or `_` or `:` or `-`. 

45 Backslash escapes may be used inside quoted values, 

46 to allow a ``"`` character within the value. 

47 Note that the backslash is retained in the value: 

48 ``{k="a\\"b"}`` gives ``k`` the value ``a\\"b``. 

49 - `%` begins a comment, which ends with the next `%`. 

50 If no further `%` occurs in the rest of the line (for a block attribute) 

51 or of the inline content (for an inline attribute), 

52 the comment instead ends at the next `}`, which also ends the attribute. 

53 

54 Multiple attribute blocks are merged. 

55 

56 :param md: The MarkdownIt instance to modify. 

57 :param after: The names of inline elements after which attributes may be specified. 

58 This plugin does not support attributes after emphasis, strikethrough or text elements, 

59 which all require post-parse processing. 

60 :param spans: If True, also parse attributes after spans of text, encapsulated by `[]`. 

61 Note Markdown link references take precedence over this syntax. 

62 :param span_after: The name of an inline rule after which spans may be specified. 

63 :param allowed: A list of allowed attribute names. 

64 If not ``None``, any attributes not in this list will be removed 

65 and placed in the token's meta under the key "insecure_attrs". 

66 If ``None`` (the default), event-handler attributes 

67 (any name starting with ``on``, such as ``onclick``) are still removed, 

68 as a baseline protection against script injection. 

69 Other attributes, including ``style``, are kept. 

70 Whatever ``allowed`` says, the URL-valued attributes 

71 ``href``, ``src``, ``action``, ``formaction`` and ``xlink:href`` 

72 are removed when ``md.validateLink`` rejects their value 

73 (for example a ``javascript:`` URL), as for Markdown links and images. 

74 This is not a full sanitiser: to safely render untrusted input, 

75 pass an explicit ``allowed`` list (e.g. ``("id", "class")``). 

76 """ 

77 

78 if spans: 

79 md.inline.ruler.after( 

80 span_after, 

81 "span", 

82 partial(_span_rule, allowed=None if allowed is None else set(allowed)), 

83 ) 

84 if after: 

85 md.inline.ruler.push( 

86 "attr", 

87 partial( 

88 _attr_inline_rule, 

89 after=after, 

90 allowed=None if allowed is None else set(allowed), 

91 ), 

92 ) 

93 

94 

95def attrs_block_plugin(md: MarkdownIt, *, allowed: Sequence[str] | None = None) -> None: 

96 """Parse block attributes. 

97 

98 Block attributes are attributes on a single line, with no other content. 

99 They attach the specified attributes to the block below them:: 

100 

101 {.a #b c=1} 

102 A paragraph, that will be assigned the class ``a`` and the identifier ``b``. 

103 

104 Attributes can be stacked, with classes accumulating and lower attributes overriding higher:: 

105 

106 {#a .a c=1} 

107 {#b .b c=2} 

108 A paragraph, that will be assigned the class ``a b c``, and the identifier ``b``. 

109 

110 This syntax is inspired by Djot block attributes. 

111 

112 :param allowed: A list of allowed attribute names. 

113 If not ``None``, any attributes not in this list will be removed 

114 and placed in the token's meta under the key "insecure_attrs". 

115 If ``None`` (the default), event-handler attributes 

116 (any name starting with ``on``, such as ``onclick``) are still removed, 

117 as a baseline protection against script injection. 

118 Other attributes, including ``style``, are kept. 

119 Whatever ``allowed`` says, the URL-valued attributes 

120 ``href``, ``src``, ``action``, ``formaction`` and ``xlink:href`` 

121 are removed when ``md.validateLink`` rejects their value 

122 (for example a ``javascript:`` URL), as for Markdown links and images. 

123 This is not a full sanitiser: to safely render untrusted input, 

124 pass an explicit ``allowed`` list (e.g. ``("id", "class")``). 

125 """ 

126 md.block.ruler.before("fence", "attr", _attr_block_rule) 

127 md.core.ruler.after( 

128 "block", 

129 "attr", 

130 partial( 

131 _attr_resolve_block_rule, allowed=None if allowed is None else set(allowed) 

132 ), 

133 ) 

134 

135 

136def _find_opening(tokens: Sequence[Token], index: int) -> int | None: 

137 """Find the opening token index, if the token is closing.""" 

138 if tokens[index].nesting != -1: 

139 return index 

140 level = 0 

141 while index >= 0: 

142 level += tokens[index].nesting 

143 if level == 0: 

144 return index 

145 index -= 1 

146 return None 

147 

148 

149def _span_rule( 

150 state: StateInline, silent: bool, *, allowed: set[str] | None = None 

151) -> bool: 

152 if state.src[state.pos] != "[": 

153 return False 

154 

155 maximum = state.posMax 

156 labelStart = state.pos + 1 

157 labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, False) 

158 

159 # parser failed to find ']', so it's not a valid span 

160 if labelEnd < 0: 

161 return False 

162 

163 pos = labelEnd + 1 

164 

165 # check not at end of inline 

166 if pos >= maximum: 

167 return False 

168 

169 try: 

170 new_pos, attrs = parse(state.src[pos:]) 

171 except ParseError: 

172 return False 

173 

174 pos += new_pos + 1 

175 

176 if not silent: 

177 state.pos = labelStart 

178 state.posMax = labelEnd 

179 token = state.push("span_open", "span", 1) 

180 _add_attrs(state.md, token, attrs, allowed) 

181 state.md.inline.tokenize(state) 

182 token = state.push("span_close", "span", -1) 

183 

184 state.pos = pos 

185 state.posMax = maximum 

186 return True 

187 

188 

189def _attr_inline_rule( 

190 state: StateInline, 

191 silent: bool, 

192 after: Sequence[str], 

193 *, 

194 allowed: set[str] | None = None, 

195) -> bool: 

196 if state.pending or not state.tokens: 

197 return False 

198 token = state.tokens[-1] 

199 if token.type not in after: 

200 return False 

201 try: 

202 new_pos, attrs = parse(state.src[state.pos :]) 

203 except ParseError: 

204 return False 

205 token_index = _find_opening(state.tokens, len(state.tokens) - 1) 

206 if token_index is None: 

207 return False 

208 state.pos += new_pos + 1 

209 if not silent: 

210 attr_token = state.tokens[token_index] 

211 if "class" in attrs and "class" in attr_token.attrs: 

212 attrs["class"] = f"{attr_token.attrs['class']} {attrs['class']}" 

213 _add_attrs(state.md, attr_token, attrs, allowed) 

214 return True 

215 

216 

217def _attr_block_rule( 

218 state: StateBlock, startLine: int, endLine: int, silent: bool 

219) -> bool: 

220 """Find a block of attributes. 

221 

222 The block must be a single line that begins with a `{`, after three or less spaces, 

223 and end with a `}` followed by any number if spaces. 

224 """ 

225 if is_code_block(state, startLine): 

226 return False 

227 

228 pos = state.bMarks[startLine] + state.tShift[startLine] 

229 maximum = state.eMarks[startLine] 

230 

231 # if it doesn't start with a {, it's not an attribute block 

232 if state.src[pos] != "{": 

233 return False 

234 

235 # find first non-space character from the right 

236 while maximum > pos and state.src[maximum - 1] in (" ", "\t"): 

237 maximum -= 1 

238 # if it doesn't end with a }, it's not an attribute block 

239 if maximum <= pos: 

240 return False 

241 if state.src[maximum - 1] != "}": 

242 return False 

243 

244 try: 

245 _new_pos, attrs = parse(state.src[pos:maximum]) 

246 except ParseError: 

247 return False 

248 

249 # if the block was resolved earlier than expected, it's not an attribute block 

250 # TODO this was not working in some instances, so I disabled it 

251 # if (maximum - 1) != new_pos: 

252 # return False 

253 

254 if silent: 

255 return True 

256 

257 token = state.push("attrs_block", "", 0) 

258 token.attrs = attrs # type: ignore[assignment] 

259 token.map = [startLine, startLine + 1] 

260 

261 state.line = startLine + 1 

262 return True 

263 

264 

265def _attr_resolve_block_rule(state: StateCore, *, allowed: set[str] | None) -> None: 

266 """Find attribute block then move its attributes to the next block.""" 

267 i = 0 

268 len_tokens = len(state.tokens) 

269 while i < len_tokens: 

270 if state.tokens[i].type != "attrs_block": 

271 i += 1 

272 continue 

273 

274 # skip closing tokens; attributes would be rendered into the closing tag 

275 if i + 1 < len_tokens and state.tokens[i + 1].nesting >= 0: 

276 next_token = state.tokens[i + 1] 

277 

278 # classes are appended 

279 if "class" in state.tokens[i].attrs and "class" in next_token.attrs: 

280 state.tokens[i].attrs["class"] = ( 

281 f"{state.tokens[i].attrs['class']} {next_token.attrs['class']}" 

282 ) 

283 

284 if next_token.type == "attrs_block": 

285 # subsequent attribute blocks take precedence, when merging 

286 for key, value in state.tokens[i].attrs.items(): 

287 if key == "class" or key not in next_token.attrs: 

288 next_token.attrs[key] = value 

289 else: 

290 _add_attrs(state.md, next_token, state.tokens[i].attrs, allowed) 

291 

292 state.tokens.pop(i) 

293 len_tokens -= 1 

294 

295 

296_URL_ATTRS = frozenset(("href", "src", "action", "formaction", "xlink:href")) 

297"""Attributes whose value is a URL, checked with ``md.validateLink``.""" 

298 

299_URL_IGNORED_RE = re.compile(r"[\t\n\r]") 

300_URL_STRIP = "".join(chr(i) for i in range(0x21)) 

301 

302 

303def _is_insecure_attr(key: str) -> bool: 

304 """Return True for event-handler attributes (``on*``, e.g. ``onclick``). 

305 

306 They execute JavaScript, so they are removed by default 

307 when no explicit ``allowed`` list is given. 

308 """ 

309 return key.lower().startswith("on") 

310 

311 

312def _is_valid_url(md: MarkdownIt, value: Any) -> bool: 

313 """Return True if ``md.validateLink`` accepts a URL-valued attribute. 

314 

315 Browsers ignore ASCII tabs and newlines anywhere in a URL, 

316 and control characters and spaces around it, before reading its scheme 

317 (so ``java<TAB>script:`` is a ``javascript:`` URL). 

318 The value is emitted as written, so those characters are removed 

319 before it is normalised and validated. 

320 """ 

321 url = _URL_IGNORED_RE.sub("", str(value)).strip(_URL_STRIP) 

322 return md.validateLink(md.normalizeLink(url)) 

323 

324 

325def _add_attrs( 

326 md: MarkdownIt, 

327 token: Token, 

328 attrs: dict[str, Any], 

329 allowed: set[str] | None, 

330) -> None: 

331 """Add attributes to a token, skipping any disallowed attributes. 

332 

333 When ``allowed`` is not ``None`` only those names are kept. 

334 When it is ``None`` (the default) event-handler (``on*``) attributes 

335 are still removed, so untrusted input cannot inject script. 

336 In both cases, a URL-valued attribute (``href``, ``src``, ...) 

337 is removed if ``md.validateLink`` rejects it. 

338 Anything removed is preserved in ``token.meta["insecure_attrs"]``. 

339 """ 

340 if allowed is not None: 

341 disallowed = {k: v for k, v in attrs.items() if k not in allowed} 

342 else: 

343 disallowed = {k: v for k, v in attrs.items() if _is_insecure_attr(k)} 

344 disallowed.update( 

345 (k, v) 

346 for k, v in attrs.items() 

347 if k not in disallowed and k.lower() in _URL_ATTRS and not _is_valid_url(md, v) 

348 ) 

349 

350 if disallowed: 

351 token.meta["insecure_attrs"] = disallowed 

352 attrs = {k: v for k, v in attrs.items() if k not in disallowed} 

353 

354 # attributes takes precedence over existing attributes 

355 token.attrs.update(attrs)