Skip to content

Commit 882e1e9

Browse files
marcelsafinCopilot
andauthored
fix(cli): exit cleanly on malformed IPv6 URLs in extension/preset/workflow add (#3369)
* fix(cli): exit cleanly on malformed IPv6 URLs in extension/preset/workflow add extension add --from, preset add --from, and workflow add <url> parsed the user-supplied URL with a bare urlparse before their HTTPS/host validation, so an unclosed IPv6 bracket escaped as a raw ValueError traceback. Wrap each parse and emit the surrounding validation's clean error style + typer.Exit(1) instead. Fixes #3368 Co-authored-by: Copilot <[email protected]> * fix(cli): convert malformed redirect URLs to URLError in shared redirect handler Parse the redirect target once in _StripAuthOnRedirect.redirect_request before the validator and stdlib handler run, converting ValueError into URLError which every download path already catches. Also escape from_url in the preset install message so IPv6 brackets don't break Rich markup. Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Copilot <[email protected]>
1 parent a307894 commit 882e1e9

8 files changed

Lines changed: 104 additions & 5 deletions

File tree

‎src/specify_cli/authentication/http.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,13 @@ def __init__(
7373
self._redirect_validator = redirect_validator
7474

7575
def redirect_request(self, req, fp, code, msg, headers, newurl):
76+
try:
77+
new_parsed = urlparse(newurl)
78+
except ValueError as exc:
79+
# Malformed redirect target (e.g. unterminated IPv6 bracket).
80+
# Surface as URLError so callers' download error handling applies.
81+
raise urllib.error.URLError(f"malformed redirect URL: {exc}") from exc
82+
7683
if self._redirect_validator is not None:
7784
self._redirect_validator(req.full_url, newurl)
7885

@@ -83,7 +90,6 @@ def redirect_request(self, req, fp, code, msg, headers, newurl):
8390
new_req = super().redirect_request(req, fp, code, msg, headers, newurl)
8491
if new_req is not None:
8592
old_scheme = urlparse(req.full_url).scheme
86-
new_parsed = urlparse(newurl)
8793
hostname = (new_parsed.hostname or "").lower()
8894
is_https_downgrade = old_scheme == "https" and new_parsed.scheme != "https"
8995
if _hostname_in_hosts(hostname, self._hosts) and not is_https_downgrade:

‎src/specify_cli/extensions/_commands.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -426,7 +426,11 @@ def extension_add(
426426
if from_url and not dev:
427427
from urllib.parse import urlparse
428428

429-
parsed = urlparse(from_url)
429+
try:
430+
parsed = urlparse(from_url)
431+
except ValueError:
432+
console.print(f"[red]Error:[/red] Invalid URL: {_escape_markup(from_url)}")
433+
raise typer.Exit(1)
430434
is_localhost = parsed.hostname in ("localhost", "127.0.0.1", "::1")
431435

432436
if parsed.scheme != "https" and not (parsed.scheme == "http" and is_localhost):

‎src/specify_cli/presets/_commands.py‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,13 @@ def preset_add(
104104
from ipaddress import ip_address
105105
from urllib.parse import urlparse as _urlparse
106106

107-
_parsed = _urlparse(from_url)
107+
try:
108+
_parsed = _urlparse(from_url)
109+
except ValueError:
110+
from rich.markup import escape as _escape_markup
111+
112+
console.print(f"[red]Error:[/red] Invalid URL: {_escape_markup(from_url)}")
113+
raise typer.Exit(1)
108114

109115
def _is_allowed_download_url(parsed_url):
110116
host = parsed_url.hostname
@@ -135,7 +141,9 @@ def _validate_download_redirect(old_url, new_url):
135141
)
136142
raise typer.Exit(1)
137143

138-
console.print(f"Installing preset from [cyan]{from_url}[/cyan]...")
144+
from rich.markup import escape as _esc
145+
146+
console.print(f"Installing preset from [cyan]{_esc(from_url)}[/cyan]...")
139147
import urllib.error
140148
import tempfile
141149
import shutil

‎src/specify_cli/workflows/_commands.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -631,7 +631,11 @@ def _validate_and_install_local(yaml_path: Path, source_label: str) -> None:
631631
from urllib.parse import urlparse
632632
from specify_cli.authentication.http import open_url as _open_url
633633

634-
parsed_src = urlparse(source)
634+
try:
635+
parsed_src = urlparse(source)
636+
except ValueError:
637+
console.print(f"[red]Error:[/red] Invalid URL: {_escape_markup(source)}")
638+
raise typer.Exit(1)
635639
src_host = parsed_src.hostname or ""
636640
src_loopback = src_host == "localhost"
637641
if not src_loopback:

‎tests/test_authentication.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -845,6 +845,22 @@ def test_multi_hop_redirect_within_hosts_preserves_auth(self):
845845
auth3 = req3.get_header("Authorization") or req3.unredirected_hdrs.get("Authorization")
846846
assert auth3 == "Bearer tok"
847847

848+
def test_malformed_redirect_url_raises_urlerror_not_valueerror(self):
849+
"""A redirect to a malformed URL (unterminated IPv6 bracket) surfaces
850+
as URLError, which download paths already handle, rather than an
851+
unhandled ValueError traceback."""
852+
import urllib.error
853+
from specify_cli.authentication.http import _StripAuthOnRedirect
854+
from urllib.request import Request
855+
import io
856+
857+
handler = _StripAuthOnRedirect(("github.com",))
858+
req = Request("https://github.com/org/repo")
859+
860+
with pytest.raises(urllib.error.URLError):
861+
handler.redirect_request(req, io.BytesIO(b""), 302, "Found", {},
862+
"https://[::1/asset")
863+
848864

849865
# ---------------------------------------------------------------------------
850866
# _fetch_latest_release_tag delegation

‎tests/test_extensions.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5441,6 +5441,29 @@ def record_status(*args, **kwargs):
54415441
f"confirm must precede spinner, got: {call_order}"
54425442
assert result.exit_code == 0 # user declined → clean exit
54435443

5444+
def test_add_from_malformed_ipv6_url_exits_cleanly(self, tmp_path):
5445+
"""A malformed IPv6 URL must produce a clean error, not a ValueError traceback."""
5446+
from typer.testing import CliRunner
5447+
from unittest.mock import patch
5448+
from specify_cli import app
5449+
5450+
project_dir = tmp_path / "test-project"
5451+
project_dir.mkdir()
5452+
(project_dir / ".specify").mkdir()
5453+
5454+
runner = CliRunner()
5455+
with patch.object(Path, "cwd", return_value=project_dir):
5456+
result = runner.invoke(
5457+
app,
5458+
["extension", "add", "my-ext", "--from", "https://[::1/ext.zip"],
5459+
catch_exceptions=True,
5460+
)
5461+
5462+
assert result.exit_code == 1
5463+
assert result.exception is None or isinstance(result.exception, SystemExit)
5464+
plain = strip_ansi(result.output)
5465+
assert "Invalid URL" in plain
5466+
54445467
def test_add_status_escapes_extension_markup(self, tmp_path):
54455468
"""User-controlled extension names must not be parsed as Rich markup."""
54465469
from rich.markup import escape as escape_markup

‎tests/test_presets.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4538,6 +4538,27 @@ def test_preset_add_from_url_rejects_hostless_https_url(self, project_dir):
45384538
assert "got https://" not in output
45394539
open_url.assert_not_called()
45404540

4541+
def test_preset_add_from_malformed_ipv6_url_exits_cleanly(self, project_dir):
4542+
"""A malformed IPv6 URL must produce a clean error, not a ValueError traceback."""
4543+
from typer.testing import CliRunner
4544+
from unittest.mock import patch
4545+
from specify_cli import app
4546+
4547+
runner = CliRunner()
4548+
with patch.object(Path, "cwd", return_value=project_dir), \
4549+
patch("specify_cli.authentication.http.open_url") as open_url:
4550+
result = runner.invoke(
4551+
app,
4552+
["preset", "add", "--from", "https://[::1/preset.zip"],
4553+
catch_exceptions=True,
4554+
)
4555+
4556+
assert result.exit_code == 1
4557+
assert result.exception is None or isinstance(result.exception, SystemExit)
4558+
output = strip_ansi(result.output)
4559+
assert "Invalid URL" in output
4560+
open_url.assert_not_called()
4561+
45414562
def test_preset_add_from_url_redirect_error_describes_disallowed_url(self, project_dir, monkeypatch, capsys):
45424563
"""Redirect rejection message covers hostless HTTPS, not only non-HTTPS URLs."""
45434564
import typer

‎tests/test_workflows.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5593,6 +5593,23 @@ def test_remove_refuses_non_directory_workflow_path(self, project_dir, monkeypat
55935593

55945594

55955595
class TestWorkflowAddSymlinkGuard:
5596+
def test_add_malformed_ipv6_url_exits_cleanly(self, temp_dir, monkeypatch):
5597+
"""A malformed IPv6 URL must produce a clean error, not a ValueError traceback."""
5598+
from typer.testing import CliRunner
5599+
from specify_cli import app
5600+
5601+
(temp_dir / ".specify").mkdir(exist_ok=True)
5602+
monkeypatch.chdir(temp_dir)
5603+
result = CliRunner().invoke(
5604+
app,
5605+
["workflow", "add", "https://[::1/wf.yaml"],
5606+
catch_exceptions=True,
5607+
)
5608+
5609+
assert result.exit_code == 1
5610+
assert result.exception is None or isinstance(result.exception, SystemExit)
5611+
assert "Invalid URL" in result.output
5612+
55965613
@pytest.mark.skipif(not hasattr(os, "symlink"), reason="symlinks are unavailable")
55975614
def test_add_refuses_symlinked_specify(self, temp_dir, monkeypatch):
55985615
"""workflow add must refuse a symlinked .specify (writes could escape root)."""

0 commit comments

Comments
 (0)