Skip to content

Commit 756e6b3

Browse files
ShotaroKataokaShotaro Kataoka
andauthored
fix(builder): resolve image paths through resolve_image_path everywhere (#701)
* fix(builder): resolve image paths through resolve_image_path everywhere The image element, injected group/shape images and video posters resolve their file through resolve_image_path, which gains a base_dir argument for deck-relative paths and applies its '..' rule to icons:/assets: references too. * fix(assets): refuse '..' segments in the asset lookup itself The '..' rule for icons:/assets: references lived in resolve_image_path, so only the PPTX image element applied it. resolve_asset_path now refuses such references, which covers the HTML assembly and check_asset_exists as well; both treat a refused reference like a missing asset. Images injected into groups and shapes now warn when their path is refused. --------- Co-authored-by: Shotaro Kataoka <sktok@amazon.co.jp>
1 parent ce6981e commit 756e6b3

7 files changed

Lines changed: 198 additions & 20 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,13 @@ Under an Upgrading section, the bullets after **Local installs (`sdpm update`).*
7272

7373
### Fixed
7474

75+
- **Image paths resolve one way everywhere.** The image element, images inside imported
76+
groups and shapes, and video posters now all resolve their file through
77+
`resolve_image_path`, so they follow the same rules (relative to the deck directory, `~`
78+
expanded, no `..` segments). An image file that does not pass is skipped with a warning,
79+
as a missing image already was. The asset lookup behind `icons:`/`assets:` references
80+
refuses `..` segments too, for PPTX and HTML decks alike; such a reference is reported
81+
like a missing asset.
7582
- **A textbox border keeps its `lineOpacity`** (#667). The textbox builder ignored
7683
`lineOpacity`, so a translucent border came out fully opaque, and a PPTX → JSON → PPTX
7784
round trip lost the opacity `pptx_to_json` had read. It now writes the border alpha as

‎sdpm/sdpm/engine/builder/elements/group.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
22
# SPDX-License-Identifier: MIT-0
33
"""Group and arch-group elements."""
4+
import sys
5+
46
from sdpm.engine.accessibility import write_element_metadata
57
from sdpm.engine.builder.constants import ARCH_GROUP_DEFS
68
from sdpm.engine.schema.regions import is_comment_element
79
from sdpm.utils import xml_safe
10+
from sdpm.utils.image import resolve_image_path
811

912

1013
class GroupMixin:
@@ -109,11 +112,11 @@ def _reattach_xml_images(self, slide, xml_el, images_map):
109112
new_rids = {}
110113
for old_rid, rel_path in images_map.items():
111114
try:
112-
img_path = self._base_dir / rel_path
113-
if not img_path.exists():
114-
continue
115+
img_path = resolve_image_path(rel_path, base_dir=self._base_dir)
115116
image_part, rid = slide.part.get_or_add_image_part(str(img_path))
116117
new_rids[old_rid] = rid
118+
except ValueError as e:
119+
print(f"Warning: {e} — image skipped", file=sys.stderr)
117120
except Exception:
118121
continue
119122
for el_ref in xml_el.iter():

‎sdpm/sdpm/engine/builder/elements/image.py‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -102,14 +102,14 @@ def _add_image(self, slide, elem):
102102
return
103103

104104
# Resolve image path
105+
theme = "dark" if self.is_dark else "light"
105106
if src.startswith("icons:") or src.startswith("assets:"):
106-
img_path = resolve_image_path(src, "dark" if self.is_dark else "light")
107+
img_path = resolve_image_path(src, theme)
107108
else:
108-
img_path = Path(src).expanduser()
109-
if not img_path.is_absolute():
110-
img_path = self._base_dir / src
111-
if not img_path.exists():
112-
print(f"Warning: Image not found: {img_path}", file=sys.stderr)
109+
try:
110+
img_path = resolve_image_path(src, theme, base_dir=self._base_dir)
111+
except (ValueError, FileNotFoundError) as e:
112+
print(f"Warning: {e} — element dropped from PPTX", file=sys.stderr)
113113
return
114114

115115
is_svg = img_path.suffix.lower() == ".svg"
@@ -349,7 +349,12 @@ def _add_video(self, slide, elem):
349349
return
350350

351351
video_path = self._base_dir / src
352-
poster_path = self._base_dir / poster if poster else None
352+
poster_path = None
353+
if poster:
354+
try:
355+
poster_path = resolve_image_path(poster, base_dir=self._base_dir)
356+
except (ValueError, FileNotFoundError) as e:
357+
print(f"Warning: video poster skipped: {e}", file=sys.stderr)
353358

354359
if not video_path or not Path(video_path).exists():
355360
print(f"Warning: Video not found: {src}", file=sys.stderr)

‎sdpm/sdpm/engine/html/assemble.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,9 @@ def _path(self, ref: str, where: str) -> Path | None:
232232
except FileNotFoundError:
233233
self.warn(f"{where}: asset not found: {ref}; take the name from search_assets")
234234
return None
235+
except ValueError as e:
236+
self.warn(f"{where}: {e} — not embedded; take the name from search_assets")
237+
return None
235238
if kind == "relative":
236239
target = (self.deck_dir / ref.strip().split("#", 1)[0].split("?", 1)[0]).resolve()
237240
if not target.is_relative_to(self.deck_dir):

‎sdpm/sdpm/knowledge/assets/__init__.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ def check_asset_exists(ref: str, theme: str = "light") -> bool:
228228
try:
229229
resolve_asset_path(ref, theme=theme)
230230
return True
231-
except FileNotFoundError:
231+
except (FileNotFoundError, ValueError):
232232
return False
233233

234234

@@ -274,8 +274,12 @@ def resolve_asset_path(ref: str, theme: str = "light") -> Path:
274274
Resolved file Path.
275275
276276
Raises:
277+
ValueError: If the reference contains a ``..`` segment.
277278
FileNotFoundError: If asset not found in any source.
278279
"""
280+
name_part = ref.split(":", 1)[1] if ref.startswith(("assets:", "icons:")) else ref
281+
if ".." in Path(name_part).parts:
282+
raise ValueError(f"Asset reference must not contain '..': {ref}")
279283
if ref.startswith("assets:"):
280284
# assets:aws/Arch_Amazon-S3 → search specific source
281285
remainder = ref.split(":", 1)[1]

‎sdpm/sdpm/utils/image.py‎

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,25 @@
77
from sdpm.utils import xml_safe
88

99

10-
def resolve_image_path(src: str, theme: str = "light") -> Path:
11-
"""Resolve image source to file path."""
10+
def resolve_image_path(src: str, theme: str = "light", base_dir: Path | None = None) -> Path:
11+
"""Resolve image source to file path.
12+
13+
``icons:``/``assets:`` references go to the asset lookup, which refuses
14+
``..`` segments itself. Any other value is a file path (``~`` expanded); a
15+
relative one is taken from ``base_dir`` (the deck directory) when given.
16+
``..`` segments are refused here too.
17+
"""
1218
if src.startswith("icons:") or src.startswith("assets:"):
1319
return resolve_asset_path(src, theme)
14-
else:
15-
path = Path(src).expanduser().resolve()
16-
if ".." in Path(src).parts:
17-
raise ValueError(f"Path traversal not allowed: {src}")
18-
if not path.exists():
19-
raise FileNotFoundError(f"Image not found: {src}")
20-
return path
20+
if ".." in Path(src).parts:
21+
raise ValueError(f"Image path must not contain '..': {src}")
22+
path = Path(src).expanduser()
23+
if not path.is_absolute() and base_dir is not None:
24+
path = Path(base_dir) / path
25+
path = path.resolve()
26+
if not path.exists():
27+
raise FileNotFoundError(f"Image not found: {src}")
28+
return path
2129

2230

2331
def apply_image_effects(pic_element, elem_def):
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
"""Every image ``src`` the builder reads goes through ``resolve_image_path``.
2+
3+
``resolve_image_path`` owns the rules for turning an image reference into a
4+
file: ``icons:``/``assets:`` lookups, ``~`` expansion, paths relative to the
5+
deck directory, and refusing ``..`` segments. These tests pin that the image
6+
element, injected group/shape images and video posters all follow it.
7+
"""
8+
9+
import io
10+
from pathlib import Path
11+
12+
import pytest
13+
from lxml import etree
14+
from PIL import Image
15+
16+
from sdpm.utils.image import resolve_image_path
17+
18+
TEMPLATE = Path(__file__).parent.parent / "sdpm" / "templates" / "blank-light.pptx"
19+
20+
21+
def _png(path: Path) -> Path:
22+
path.parent.mkdir(parents=True, exist_ok=True)
23+
buf = io.BytesIO()
24+
Image.new("RGB", (4, 4), "red").save(buf, format="PNG")
25+
path.write_bytes(buf.getvalue())
26+
return path
27+
28+
29+
def _builder(base_dir: Path):
30+
from sdpm.engine.builder import PPTXBuilder
31+
32+
return PPTXBuilder(
33+
str(TEMPLATE),
34+
fonts={"fullwidth": "Meiryo", "halfwidth": "Arial"},
35+
default_text_color="#000000",
36+
base_dir=base_dir,
37+
)
38+
39+
40+
def _pictures(builder) -> list:
41+
slide = builder.prs.slides[-1]
42+
return [s for s in slide.shapes if s.shape_type == 13] # MSO_SHAPE_TYPE.PICTURE
43+
44+
45+
def _add_image_slide(builder, src: str) -> None:
46+
builder.add_slide({"layout": "Blank", "elements": [
47+
{"type": "image", "src": src, "x": 0, "y": 0, "width": 100, "height": 100},
48+
]})
49+
50+
51+
def test_resolve_image_path_resolves_relative_to_base_dir(tmp_path):
52+
img = _png(tmp_path / "deck" / "images" / "a.png")
53+
assert resolve_image_path("images/a.png", base_dir=tmp_path / "deck") == img.resolve()
54+
55+
56+
def test_resolve_image_path_keeps_absolute_paths(tmp_path):
57+
img = _png(tmp_path / "a.png")
58+
assert resolve_image_path(str(img), base_dir=tmp_path / "elsewhere") == img.resolve()
59+
60+
61+
@pytest.mark.parametrize("src", ["images/../a.png", "assets:aws/../a", "icons:../a"])
62+
def test_resolve_image_path_rejects_parent_segments(tmp_path, src):
63+
_png(tmp_path / "a.png")
64+
with pytest.raises(ValueError):
65+
resolve_image_path(src, base_dir=tmp_path)
66+
67+
68+
def test_add_image_embeds_relative_src(tmp_path):
69+
_png(tmp_path / "images" / "a.png")
70+
b = _builder(tmp_path)
71+
_add_image_slide(b, "images/a.png")
72+
assert len(_pictures(b)) == 1
73+
74+
75+
def test_add_image_uses_resolve_image_path_rules(tmp_path):
76+
deck = tmp_path / "deck"
77+
(deck / "images").mkdir(parents=True)
78+
_png(tmp_path / "a.png")
79+
b = _builder(deck)
80+
_add_image_slide(b, "images/../../a.png")
81+
assert _pictures(b) == []
82+
83+
84+
def test_injected_images_use_resolve_image_path_rules(tmp_path):
85+
deck = tmp_path / "deck"
86+
deck.mkdir()
87+
_png(tmp_path / "a.png")
88+
_png(deck / "b.png")
89+
b = _builder(deck)
90+
b.add_slide({"layout": "Blank", "elements": []})
91+
slide = b.prs.slides[-1]
92+
r_embed = "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed"
93+
xml_el = etree.Element("root")
94+
etree.SubElement(xml_el, "blip").set(r_embed, "rIdOut")
95+
etree.SubElement(xml_el, "blip").set(r_embed, "rIdIn")
96+
b._reattach_xml_images(slide, xml_el, {"rIdOut": "../a.png", "rIdIn": "b.png"})
97+
embeds = [el.get(r_embed) for el in xml_el.iter("blip")]
98+
assert embeds[0] == "rIdOut" # left unmapped
99+
assert embeds[1] != "rIdIn" # remapped to the added part
100+
101+
102+
# ``icons:``/``assets:`` references: the asset lookup itself refuses ``..``, so
103+
# every caller (PPTX builder, HTML assembly, the pre-build asset check) gets it.
104+
105+
106+
@pytest.fixture
107+
def outside_asset(tmp_path, monkeypatch):
108+
"""An image one level above a stand-in assets directory, and the ref that names it."""
109+
import sdpm.knowledge.assets as assets_mod
110+
111+
assets_dir = tmp_path / "assets"
112+
(assets_dir / "aws").mkdir(parents=True)
113+
monkeypatch.setattr(assets_mod, "ASSETS_DIR", assets_dir)
114+
_png(tmp_path / "outside" / "evil.png")
115+
return "assets:../outside/evil"
116+
117+
118+
@pytest.mark.parametrize("ref", ["assets:../x/y", "assets:aws/../x", "icons:../x", "../x"])
119+
def test_resolve_asset_path_rejects_parent_segments(ref):
120+
from sdpm.knowledge.assets import resolve_asset_path
121+
122+
with pytest.raises(ValueError):
123+
resolve_asset_path(ref)
124+
125+
126+
def test_check_asset_exists_refuses_parent_segments(outside_asset):
127+
from sdpm.knowledge.assets import check_asset_exists
128+
129+
assert check_asset_exists(outside_asset) is False
130+
131+
132+
def test_html_asset_ref_with_parent_segment_is_not_embedded(tmp_path, outside_asset):
133+
from sdpm.engine.html.assemble import _Resolver
134+
135+
warnings: list[str] = []
136+
resolver = _Resolver(tmp_path / "deck", "light", warnings.append)
137+
assert resolver.path(outside_asset, "slide 1") is None
138+
assert any("'..'" in w for w in warnings)
139+
140+
141+
def test_injected_image_with_parent_segment_warns(tmp_path, capsys):
142+
deck = tmp_path / "deck"
143+
deck.mkdir()
144+
_png(tmp_path / "a.png")
145+
b = _builder(deck)
146+
b.add_slide({"layout": "Blank", "elements": []})
147+
b._reattach_xml_images(b.prs.slides[-1], etree.Element("root"), {"rId1": "../a.png"})
148+
assert "image skipped" in capsys.readouterr().err

0 commit comments

Comments
 (0)