Escaping the `repl` argument to `re.sub()`, `re.subn()`
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 77.2k
- フォーク
- 35.9k
- PR マージ指標
- PR 指標を取得中
説明
Documentation
It's not immediately obvious how to escape the repl (replacement for matches) argument to re.sub() and re.subn() if repl is chosen by a potentially hostile actor. Obviously, re.escape() isn't the answer, as that escapes far too much.
The right answer seems to be escaped_repl = raw_repl.replace(bslash, bslash*2) where bslash = '\\'. It might be worth adding this to the documentation.
Here's the code I used to empirically validate the "right answer" given above (checked on Python 3.8 & 3.12):
from __future__ import annotations
import re, sys
def escape_re_sub_repl(repl: str) -> str:
return repl.replace('\\', '\\\\')
def test_escape_re_sub_repl() -> None:
backslash = '\\'
assert len(backslash) == 1
base_regex = 'TARGET'
assert base_regex == re.escape(base_regex)
base_prefix = 'BEFORE:'
base_suffix = ':AFTER'
base_input = f'{base_prefix}{base_regex}{base_suffix}'
base_chars = tuple(chr(p) for p in range(sys.maxunicode + 1))
escaped_chars = tuple(f'{backslash}{c}' for c in base_chars)
test_cases = base_chars + escaped_chars
assert {len(f) for f in test_cases} == {1, 2}
for raw in test_cases:
repl = escape_re_sub_repl(raw)
got, change_count = re.subn(base_regex, repl, base_input)
assert change_count == 1
assert got == f'{base_prefix}{raw}{base_suffix}'
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、re.sub() と re.subn() のドキュメントと、置換文字列の規則を確認します。既存の re.escape() に関するガイダンスを確認したうえで、悪意のある置換テキストに対するバックスラッシュ倍化のアプローチを文書化し、提示された例に対して検証します。関連するドキュメントで安全なエスケープのガイダンスが明確になっていれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- documentation
- issue の種類
- ドキュメント
- 難易度
- 2/5
- 見積もり時間
- 1〜3時間
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 45/100