Skip to content

Commit 9d31ef5

Browse files
tacaswellmeeseeksmachine
authored andcommitted
Backport PR matplotlib#31632: FIX: Prohibit special TeX chars in pgf metadata
1 parent f281eba commit 9d31ef5

2 files changed

Lines changed: 30 additions & 1 deletion

File tree

lib/matplotlib/backends/backend_pgf.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,15 @@ def _metadata_to_str(key, value):
154154
value = value.name.decode('ascii')
155155
else:
156156
value = str(value)
157+
158+
# ensure that metadata does not contain special TeX chars because we
159+
# insert the metadata as raw text into the TeX source
160+
invalid_chars = r"\{}[]()"
161+
if any(c in value + key for c in invalid_chars):
162+
raise ValueError(
163+
f"Invalid metadata value for {key!r}: {value!r}. "
164+
f"The value must not contain the chars {invalid_chars}.")
165+
157166
return f'{key}={{{value}}}'
158167

159168

lib/matplotlib/tests/test_backend_pgf.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from matplotlib.testing import _has_tex_package, _check_for_pgf
1616
from matplotlib.testing.exceptions import ImageComparisonFailure
1717
from matplotlib.testing.compare import compare_images
18-
from matplotlib.backends.backend_pgf import PdfPages
18+
from matplotlib.backends.backend_pgf import _metadata_to_str, PdfPages
1919
from matplotlib.testing.decorators import (
2020
_image_directories, check_figures_equal, image_comparison)
2121
from matplotlib.testing._markers import (
@@ -37,6 +37,26 @@ def compare_figure(fname, savefig_kwargs={}, tol=0):
3737
raise ImageComparisonFailure(err)
3838

3939

40+
@pytest.mark.parametrize("key, value, expected_str", [
41+
("Author", "me", "Author={me}"),
42+
("ModDate",
43+
datetime.datetime(1968, 8, 1, tzinfo=datetime.timezone(datetime.timedelta(0))),
44+
"ModDate={D:19680801000000Z}"),
45+
])
46+
def test__metadata_to_str(key, value, expected_str):
47+
assert _metadata_to_str(key, value) == expected_str
48+
49+
50+
@pytest.mark.parametrize("value", [
51+
r"Backslashes, e.g. in \commands",
52+
r"funny braces {}",
53+
r"and square brackets]",
54+
])
55+
def test__metadata_to_str_error(value):
56+
with pytest.raises(ValueError, match="value must not contain the chars"):
57+
_metadata_to_str("Title", value)
58+
59+
4060
@needs_pgf_xelatex
4161
@needs_ghostscript
4262
@pytest.mark.backend('pgf')

0 commit comments

Comments
 (0)