Skip to content

Commit 07b5611

Browse files
fix(presets): escape markup in preset_add error handlers
Copilot review on #3577 flagged that the malformed-URL fix stopped short: `download_pack` now raises a clean `PresetError`, but the `preset_add` handler rendered `{e}` unescaped. A catalog `download_url` like `https://[not-an-ip]/x` is embedded verbatim in the message, so Rich interprets `[not-an-ip]` as a markup tag and can raise a style/markup exception while rendering the error — the CLI still crashes instead of exiting cleanly. Escape `str(e)` in the preset command handlers, matching the extension handler at `extensions/_commands.py:657`, and hoist the `rich.markup` import to module scope (dropping the two inline imports). Adds CLI-level regression tests: a bracketed-host `download_url` exits cleanly, and the compatibility/validation/error handlers escape markup-bearing messages. Both tests fail on the pre-fix handler (test-the-test verified). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
1 parent dc411dc commit 07b5611

2 files changed

Lines changed: 86 additions & 13 deletions

File tree

‎src/specify_cli/presets/_commands.py‎

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
import typer
1515
import yaml
16+
from rich.markup import escape as _escape_markup
1617

1718
from .._console import console
1819

@@ -107,8 +108,6 @@ def preset_add(
107108
try:
108109
_parsed = _urlparse(from_url)
109110
except ValueError:
110-
from rich.markup import escape as _escape_markup
111-
112111
console.print(f"[red]Error:[/red] Invalid URL: {_escape_markup(from_url)}")
113112
raise typer.Exit(1)
114113

@@ -141,9 +140,7 @@ def _validate_download_redirect(old_url, new_url):
141140
)
142141
raise typer.Exit(1)
143142

144-
from rich.markup import escape as _esc
145-
146-
console.print(f"Installing preset from [cyan]{_esc(from_url)}[/cyan]...")
143+
console.print(f"Installing preset from [cyan]{_escape_markup(from_url)}[/cyan]...")
147144
import urllib.error
148145
import tempfile
149146
import shutil
@@ -183,7 +180,7 @@ def _validate_download_redirect(old_url, new_url):
183180
except TypeError:
184181
output.write(response.read())
185182
except urllib.error.URLError as e:
186-
console.print(f"[red]Error:[/red] Failed to download: {e}")
183+
console.print(f"[red]Error:[/red] Failed to download: {_escape_markup(str(e))}")
187184
raise typer.Exit(1)
188185

189186
manifest = manager.install_from_zip(zip_path, speckit_version, priority)
@@ -240,13 +237,13 @@ def _validate_download_redirect(old_url, new_url):
240237
raise typer.Exit(1)
241238

242239
except PresetCompatibilityError as e:
243-
console.print(f"[red]Compatibility Error:[/red] {e}")
240+
console.print(f"[red]Compatibility Error:[/red] {_escape_markup(str(e))}")
244241
raise typer.Exit(1)
245242
except PresetValidationError as e:
246-
console.print(f"[red]Validation Error:[/red] {e}")
243+
console.print(f"[red]Validation Error:[/red] {_escape_markup(str(e))}")
247244
raise typer.Exit(1)
248245
except PresetError as e:
249-
console.print(f"[red]Error:[/red] {e}")
246+
console.print(f"[red]Error:[/red] {_escape_markup(str(e))}")
250247
raise typer.Exit(1)
251248

252249

@@ -288,7 +285,7 @@ def preset_search(
288285
try:
289286
results = catalog.search(query=query, tag=tag, author=author)
290287
except PresetError as e:
291-
console.print(f"[red]Error:[/red] {e}")
288+
console.print(f"[red]Error:[/red] {_escape_markup(str(e))}")
292289
raise typer.Exit(1)
293290

294291
if not results:
@@ -582,7 +579,7 @@ def preset_catalog_list():
582579
try:
583580
active_catalogs = catalog.get_active_catalogs()
584581
except PresetValidationError as e:
585-
console.print(f"[red]Error:[/red] {e}")
582+
console.print(f"[red]Error:[/red] {_escape_markup(str(e))}")
586583
raise typer.Exit(1)
587584

588585
console.print("\n[bold cyan]Active Preset Catalogs:[/bold cyan]\n")
@@ -647,7 +644,7 @@ def preset_catalog_add(
647644
try:
648645
tmp_catalog._validate_catalog_url(url)
649646
except PresetValidationError as e:
650-
console.print(f"[red]Error:[/red] {e}")
647+
console.print(f"[red]Error:[/red] {_escape_markup(str(e))}")
651648
raise typer.Exit(1)
652649

653650
config_path = specify_dir / "preset-catalogs.yml"
@@ -658,7 +655,7 @@ def preset_catalog_add(
658655
config = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}
659656
except Exception as e:
660657
config_label = _display_project_path(project_root, config_path)
661-
console.print(f"[red]Error:[/red] Failed to read {config_label}: {e}")
658+
console.print(f"[red]Error:[/red] Failed to read {_escape_markup(str(config_label))}: {_escape_markup(str(e))}")
662659
raise typer.Exit(1)
663660
else:
664661
config = {}

‎tests/test_presets.py‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5440,6 +5440,82 @@ def test_preset_add_from_malformed_ipv6_url_exits_cleanly(self, project_dir):
54405440
assert "Invalid URL" in output
54415441
open_url.assert_not_called()
54425442

5443+
def test_preset_add_bracketed_host_download_url_exits_cleanly(self, project_dir):
5444+
"""A catalog download_url with a bracketed non-IP host must render cleanly.
5445+
5446+
``download_pack`` raises ``PresetError`` whose message embeds the raw URL
5447+
(e.g. ``https://[not-an-ip]/x``). The ``preset_add`` handler must escape
5448+
that message before printing so Rich does not interpret ``[not-an-ip]``
5449+
as a markup tag and crash while rendering the error.
5450+
"""
5451+
from typer.testing import CliRunner
5452+
from unittest.mock import patch
5453+
from specify_cli import app
5454+
5455+
bad_url = "https://[not-an-ip]/x"
5456+
catalog_data = {
5457+
"test-pack": {
5458+
"name": "Test Pack",
5459+
"version": "1.0.0",
5460+
"download_url": bad_url,
5461+
}
5462+
}
5463+
5464+
runner = CliRunner()
5465+
with patch.object(Path, "cwd", return_value=project_dir), \
5466+
patch.object(PresetCatalog, "_get_merged_packs", return_value=catalog_data):
5467+
result = runner.invoke(
5468+
app,
5469+
["preset", "add", "test-pack"],
5470+
catch_exceptions=True,
5471+
)
5472+
5473+
assert result.exit_code == 1, result.output
5474+
assert result.exception is None or isinstance(result.exception, SystemExit)
5475+
output = strip_ansi(result.output)
5476+
assert "Error:" in output
5477+
# The malformed URL surfaces verbatim rather than crashing the renderer.
5478+
assert bad_url in output
5479+
5480+
@pytest.mark.parametrize(
5481+
("exc_type", "label"),
5482+
[
5483+
(PresetCompatibilityError, "Compatibility Error"),
5484+
(PresetValidationError, "Validation Error"),
5485+
(PresetError, "Error"),
5486+
],
5487+
)
5488+
def test_preset_add_exception_handlers_escape_markup(self, project_dir, exc_type, label):
5489+
"""Preset install exceptions can include catalog-controlled values.
5490+
5491+
The message must be escaped so Rich does not treat bracketed content as
5492+
markup and raise while rendering the error.
5493+
"""
5494+
from typer.testing import CliRunner
5495+
from unittest.mock import patch
5496+
from specify_cli import app
5497+
5498+
dev_dir = project_dir / "dev-pack"
5499+
dev_dir.mkdir()
5500+
5501+
runner = CliRunner()
5502+
with patch.object(Path, "cwd", return_value=project_dir), \
5503+
patch.object(
5504+
PresetManager,
5505+
"install_from_directory",
5506+
side_effect=exc_type("bad [red]preset[/red]"),
5507+
):
5508+
result = runner.invoke(
5509+
app,
5510+
["preset", "add", "--dev", str(dev_dir)],
5511+
catch_exceptions=True,
5512+
)
5513+
5514+
assert result.exit_code == 1, result.output
5515+
assert result.exception is None or isinstance(result.exception, SystemExit)
5516+
assert f"{label}:" in result.output
5517+
assert "bad [red]preset[/red]" in result.output
5518+
54435519
def test_preset_add_from_url_redirect_error_describes_disallowed_url(self, project_dir, monkeypatch, capsys):
54445520
"""Redirect rejection message covers hostless HTTPS, not only non-HTTPS URLs."""
54455521
import typer

0 commit comments

Comments
 (0)