diff --git a/.ast-grep/rule-tests/net-domain-list-test.yml b/.ast-grep/rule-tests/net-domain-list-test.yml new file mode 100644 index 0000000000..3a367ae72d --- /dev/null +++ b/.ast-grep/rule-tests/net-domain-list-test.yml @@ -0,0 +1,5 @@ +id: net-domain-list +valid: + - 'LOCAL_DOMAIN = "example.com"' +invalid: + - 'LOCAL_DOMAIN_SUFFIXES = (".internal", ".home.arpa")' diff --git a/.ast-grep/rule-tests/net-domain-suffix-test.yml b/.ast-grep/rule-tests/net-domain-suffix-test.yml new file mode 100644 index 0000000000..d1b7e99483 --- /dev/null +++ b/.ast-grep/rule-tests/net-domain-suffix-test.yml @@ -0,0 +1,8 @@ +id: net-domain-suffix +valid: + - 'inside = dns.name.from_text(host).is_subdomain(dns.name.from_text("example.com"))' + - 'is_yaml = filename.endswith(".yaml")' +invalid: + - 'inside = host.endswith(".example.com")' + - 'inside = hostname.endswith(f".{domain}")' + - 'inside = netloc.endswith("." + domain)' diff --git a/.ast-grep/rule-tests/net-hostport-test.yml b/.ast-grep/rule-tests/net-hostport-test.yml new file mode 100644 index 0000000000..1d6a5c9aed --- /dev/null +++ b/.ast-grep/rule-tests/net-hostport-test.yml @@ -0,0 +1,7 @@ +id: net-hostport +valid: + - 'host = urlsplit(url).hostname' + - 'key, value = line.split(":", 1)' +invalid: + - 'host = urlparse(url).netloc.split(":")[0]' + - 'host, _, port = endpoint.rpartition(":")' diff --git a/.ast-grep/rule-tests/net-normalise-test.yml b/.ast-grep/rule-tests/net-normalise-test.yml new file mode 100644 index 0000000000..81f510b20f --- /dev/null +++ b/.ast-grep/rule-tests/net-normalise-test.yml @@ -0,0 +1,7 @@ +id: net-normalise +valid: + - 'host = httpx2.URL(url).host' + - 'name = value.strip().lower()' +invalid: + - 'host = value.strip("[]")' + - 'host = value.lower().rstrip(".")' diff --git a/.ast-grep/rules/net-domain-list.yml b/.ast-grep/rules/net-domain-list.yml new file mode 100644 index 0000000000..21eaf504da --- /dev/null +++ b/.ast-grep/rules/net-domain-list.yml @@ -0,0 +1,16 @@ +id: net-domain-list +language: python +severity: error +message: Literal list of domain suffixes. Use tldextract (Public Suffix List) or dns.name is_subdomain. +rule: + kind: assignment + all: + - has: + field: left + regex: (?i)(domain|tld) + - has: + field: right + has: + stopBy: end + kind: string + regex: '^["'']\.[a-z]' diff --git a/.ast-grep/rules/net-domain-suffix.yml b/.ast-grep/rules/net-domain-suffix.yml new file mode 100644 index 0000000000..8b8e1b3517 --- /dev/null +++ b/.ast-grep/rules/net-domain-suffix.yml @@ -0,0 +1,23 @@ +id: net-domain-suffix +language: python +severity: error +message: Domain matched by string suffix. Use dns.name.from_text(host).is_subdomain(dns.name.from_text(domain)); public-suffix questions go to tldextract. +rule: + kind: call + all: + - has: + field: function + kind: attribute + all: + - has: + field: attribute + regex: ^(endswith|removesuffix)$ + - has: + field: object + regex: (?i)(host|domain|netloc|server|endpoint|url|addr|fqdn) + - has: + field: arguments + has: + stopBy: end + kind: string + regex: '^f?["'']\.' diff --git a/.ast-grep/rules/net-hostport.yml b/.ast-grep/rules/net-hostport.yml new file mode 100644 index 0000000000..a3a106998e --- /dev/null +++ b/.ast-grep/rules/net-hostport.yml @@ -0,0 +1,16 @@ +id: net-hostport +language: python +severity: error +message: Host, port or userinfo split by hand. Use urllib.parse.urlsplit(value) (.hostname, .port, .username), urlsplit("//" + authority) for a bare authority, or httpx2.URL(value). +rule: + any: + - pattern: $R.$M($SEP) + - pattern: $R.$M($SEP, $$$REST) +constraints: + M: + regex: ^(split|rsplit|partition|rpartition)$ + SEP: + kind: string + regex: '^["''][:@]["'']$' + R: + regex: (?i)(host|netloc|addr|endpoint|server|authority) diff --git a/.ast-grep/rules/net-normalise.yml b/.ast-grep/rules/net-normalise.yml new file mode 100644 index 0000000000..ee5bca6bf1 --- /dev/null +++ b/.ast-grep/rules/net-normalise.yml @@ -0,0 +1,26 @@ +id: net-normalise +language: python +severity: error +message: Host canonicalised by hand. httpx2.URL(value).host or urllib.parse.urlsplit(value).hostname drops brackets and lower-cases; ipaddress.ip_address and dns.name.from_text give the canonical form. +rule: + kind: call + all: + - has: + field: function + kind: attribute + has: + field: attribute + regex: ^(strip|rstrip|lstrip)$ + - any: + - has: + field: arguments + has: + kind: string + regex: '^["'']\[\]["'']$' + - all: + - has: + field: arguments + has: + kind: string + regex: '^["'']\.["'']$' + - regex: '\.lower\(\)' diff --git a/changelog.d/1107.md b/changelog.d/1107.md new file mode 100644 index 0000000000..3646fd2161 --- /dev/null +++ b/changelog.d/1107.md @@ -0,0 +1,9 @@ +### Added + +- Added `constructs` CI quality gate powered by `ast-grep-cli==0.51.0` enforcing 12 structural AST rules against hand-rolled URL, scheme, domain suffix, and IP address manipulation across the codebase with a suppression ceiling of 0 ([#1107](https://github.com/dan-petty/devops-cli/issues/1107)). +- Configured Ruff `TID251` (banned-api) to forbid legacy `socket.inet_*` functions in favor of `ipaddress.ip_address` ([#1107](https://github.com/dan-petty/devops-cli/issues/1107)). + +### Changed + +- Replaced hand-rolled network, scheme, URL authority, and domain matching across `src/` with official standard library and ecosystem parsers (`ipaddress`, `urllib.parse`, `httpx2`, `dns.name`, `jeepney`) ([#1107](https://github.com/dan-petty/devops-cli/issues/1107)). +- Migrated default homelab IP configuration and TLS SAN certificate request models to use `ipaddress` objects natively ([#1107](https://github.com/dan-petty/devops-cli/issues/1107)). diff --git a/docs/agent/tasks/task-1107-hand-rolled-network-parsing-gate.md b/docs/agent/tasks/task-1107-hand-rolled-network-parsing-gate.md index 3167df7ae6..1b6e087ad4 100644 --- a/docs/agent/tasks/task-1107-hand-rolled-network-parsing-gate.md +++ b/docs/agent/tasks/task-1107-hand-rolled-network-parsing-gate.md @@ -73,7 +73,26 @@ Delivered across 5 incremental pull requests. - `src/devops_cli/ai/agents/media.py`: check media URI scheme with `urlsplit(data).scheme == "media+sha256"`. - [x] Add unit tests for IPv6 host parsing and upper-case schemes in Valkey endpoint and config parsers, IPv6 bracketing in gateway and run store URL builders, `DBUS_SESSION_BUS_ADDRESS` parsing with escaped paths and multiple addresses through `jeepney`, and ast-grep scanner detection for each new rule. -### Follow-up Pull Requests +### PR 5: Domain and Hostport Rules and Gate Completion (Closes #1107) -- PR 2: AGENTS.md, template, `generate_agents.md`, `architecture.md` instruction updates and `.devops/review.md` house rule under #1107. -- PR 5: `net-domain-suffix`, `net-domain-list`, `net-normalise`, `net-hostport` under #1107 (closes #1107). +- [x] Add 4 `net-*` rules to `.ast-grep/rules/` and unit tests to `.ast-grep/rule-tests/`: + - `net-domain-suffix`: flags domain matching by string suffix with `endswith` or `removesuffix`. + - `net-domain-list`: flags literal assignment lists of domain suffixes. + - `net-normalise`: flags hand-rolled host canonicalisation via `.strip("[]")` or `.lower().rstrip(".")`. + - `net-hostport`: flags host, port, or userinfo splitting by hand with `:|@` and `split|rsplit|partition|rpartition`. +- [x] Register `"net-domain-list"`, `"net-domain-suffix"`, `"net-hostport"`, and `"net-normalise"` in `CONST_NET_CONSTRUCT_RULES` in `src/devops_cli/config/constants.py` (completing all 12 rules). +- [x] Remediate hand-rolled domain suffix and normalization sites across `src/`: + - `src/devops_cli/ai/models/ollama.py`: replace `.endswith(".ollama.com")` with `dns.name.is_subdomain`. + - `src/devops_cli/commands/review.py`: replace `.endswith(".svc.cluster.local")` with `dns.name.is_subdomain`. + - `src/devops_cli/k8s/template.py`: normalize domain using `dns.name.from_text` and `to_unicode(omit_final_dot=True)`. + - `src/devops_cli/http/urls.py`: replace `netloc.split("@")` with `netloc.endswith(":")`. + - `src/devops_cli/commands/k8s/networking.py`: parse `existing_host_raw` using `urlsplit`. + - `src/devops_cli/ai/spend/pricing.py`: canonicalize `host` using `urlsplit(f"//{host}").hostname` without `strip("[]")`. + - `src/devops_cli/core/validation.py`: canonicalize hosts in `is_loopback_host` and `is_loopback_or_private_host` using `urlsplit` and `dns.name.from_text(h).to_text(omit_final_dot=True)`. +- [x] Add unit tests for mixed-case, trailing dots, look-alikes (`evilollama.com`), bracketed IPv6, and scanner detection for each of the 4 new rules in `tests/test_net_construct_rules.py`. +- [x] Zero ast-grep scan errors and zero suppressions across all 12 rules in `src/`. +- [x] Add `changelog.d/1107.md`. + +### Follow-up Tracking + +- PR 2: AGENTS.md character budget ceiling (#1107 Comment 4) paused; tracked for budget refactor. diff --git a/src/devops_cli/ai/models/ollama.py b/src/devops_cli/ai/models/ollama.py index 3d23288197..b157e6868c 100644 --- a/src/devops_cli/ai/models/ollama.py +++ b/src/devops_cli/ai/models/ollama.py @@ -97,10 +97,18 @@ def is_ollama_cloud(base_url: str | None = None, model_name: str | None = None) upstream JSON Schema grammar constraints at generation time. """ if base_url: + import dns.exception + import dns.name + parsed = urlsplit(base_url.strip()) - hostname = (parsed.hostname or "").lower() - if hostname == "ollama.com" or hostname.endswith(".ollama.com"): - return True + hostname = parsed.hostname + if hostname: + try: + h_name = dns.name.from_text(hostname) + if h_name.is_subdomain(dns.name.from_text("ollama.com")): + return True + except dns.exception.DNSException, ValueError, AttributeError: + pass if model_name and model_name.strip().lower().endswith("-cloud"): return True diff --git a/src/devops_cli/ai/spend/pricing.py b/src/devops_cli/ai/spend/pricing.py index 8dac354c7a..f1f0333813 100644 --- a/src/devops_cli/ai/spend/pricing.py +++ b/src/devops_cli/ai/spend/pricing.py @@ -194,8 +194,9 @@ def _is_configured_ai_server_host(host: str) -> bool: def _is_local_host(host: str) -> bool: from devops_cli.core.dns_names import is_public_dns_name + clean = urlsplit(f"//{host}").hostname or host try: - ip = ipaddress.ip_address(host.strip("[]")) + ip = ipaddress.ip_address(clean) if ip.is_loopback or ip.is_private: return True except ValueError: diff --git a/src/devops_cli/commands/k8s/networking.py b/src/devops_cli/commands/k8s/networking.py index c5b94a966c..7b20b82207 100644 --- a/src/devops_cli/commands/k8s/networking.py +++ b/src/devops_cli/commands/k8s/networking.py @@ -463,7 +463,6 @@ def _has_non_default_valkey_port(valkey_cfg: Any, existing_url: str | None) -> b def _should_update_valkey(settings: Any, valkey_url: str | None) -> bool: """Determine whether detected valkey_url should update valkey host/port configuration.""" - from urllib.parse import urlparse if not valkey_url: return False @@ -478,8 +477,9 @@ def _should_update_valkey(settings: Any, valkey_url: str | None) -> bool: return False existing_host_raw = getattr(valkey_cfg, "host", "") or "" - existing_host = existing_host_raw.split(":")[0].strip().lower() - new_host = (urlparse(valkey_url).hostname or "").strip().lower() + parsed_existing = urlsplit(f"//{existing_host_raw.strip()}") + existing_host = (parsed_existing.hostname or existing_host_raw).strip().lower() + new_host = (urlsplit(valkey_url).hostname or "").strip().lower() if existing_host and not is_loopback_host(existing_host) and is_loopback_host(new_host): return False return True diff --git a/src/devops_cli/commands/review.py b/src/devops_cli/commands/review.py index eea082a55d..564f104c9b 100644 --- a/src/devops_cli/commands/review.py +++ b/src/devops_cli/commands/review.py @@ -7,7 +7,7 @@ from datetime import UTC, datetime from pathlib import Path from typing import TYPE_CHECKING, Annotated, Any -from urllib.parse import urlparse +from urllib.parse import urlsplit if TYPE_CHECKING: from devops_cli.ai.analyze.symbols import BaseRevision @@ -1285,8 +1285,20 @@ def review_stats( def _backend_host(served_by: str) -> str: """Shorten a serving backend's API base to its host, and an in-cluster host to its pod or service.""" - host = urlparse(served_by).hostname or served_by - return host.split(".", 1)[0] if host.endswith(".svc.cluster.local") else host + import dns.exception + import dns.name + + parsed = urlsplit(served_by) + if not parsed.scheme and not parsed.netloc: + parsed = urlsplit(f"//{served_by}") + host = parsed.hostname or served_by + try: + h_name = dns.name.from_text(host) + if h_name.is_subdomain(dns.name.from_text("svc.cluster.local")): + return h_name.labels[0].decode("ascii", errors="replace") + except dns.exception.DNSException, ValueError, AttributeError: + pass + return host def _busy_shares(stage: StageSummary) -> str: diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 39e141f506..7d65d74cfa 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -4085,7 +4085,11 @@ "net-address-list", "net-bracket-affix", "net-cidr-build", + "net-domain-list", + "net-domain-suffix", + "net-hostport", "net-ip-literal", + "net-normalise", "net-port-table", "net-scheme-affix", "net-scheme-in", diff --git a/src/devops_cli/core/validation.py b/src/devops_cli/core/validation.py index a25f83dfdc..27e88b9c91 100644 --- a/src/devops_cli/core/validation.py +++ b/src/devops_cli/core/validation.py @@ -10,6 +10,7 @@ import socket from pathlib import Path from typing import Any, Literal +from urllib.parse import urlsplit import dns.exception import dns.name @@ -255,9 +256,23 @@ def parse_numeric_ip(host: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address return None +def _normalize_host_or_ip(raw_host: str) -> str: + """Canonicalise a host or IP string, stripping brackets and trailing dots.""" + s = str(raw_host).strip() + if not s: + return "" + try: + return str(ipaddress.ip_address(s)) + except ValueError: + pass + parsed = urlsplit(f"//{s}") + h = parsed.hostname or s + return h.rstrip(".").lower() + + def is_loopback_host(host: str) -> bool: """Whether a host is `localhost` or a loopback address, decided without a DNS query.""" - clean = str(host).strip().lower().removeprefix("[").removesuffix("]").rstrip(".") + clean = _normalize_host_or_ip(host) if clean == CONST_LOOPBACK_HOSTNAME: return True addr = parse_numeric_ip(clean) @@ -429,7 +444,7 @@ def is_loopback_or_private_host(host_or_ip: str, *, resolve_dns: bool = True) -> """Return True if host or IP string resolves to loopback, link-local, private, or non-global space.""" from devops_cli.core.dns_names import is_public_dns_name - clean = str(host_or_ip).strip().lower().removeprefix("[").removesuffix("]").rstrip(".") + clean = _normalize_host_or_ip(host_or_ip) if not clean: return True if is_loopback_host(clean): diff --git a/src/devops_cli/http/urls.py b/src/devops_cli/http/urls.py index b90f14b779..bec133afe3 100644 --- a/src/devops_cli/http/urls.py +++ b/src/devops_cli/http/urls.py @@ -34,8 +34,7 @@ def _bracket_bare_ipv6(s: str) -> str: def _has_empty_port(netloc: str) -> bool: """Check if netloc ends with a colon or has an empty port component.""" - host_port = netloc.split("@")[-1] - return host_port.endswith(":") + return netloc.endswith(":") def _resolve_netloc_fallback(s: str, parsed: SplitResult) -> SplitResult: diff --git a/src/devops_cli/k8s/template.py b/src/devops_cli/k8s/template.py index 52ca530c34..15645958c6 100644 --- a/src/devops_cli/k8s/template.py +++ b/src/devops_cli/k8s/template.py @@ -22,7 +22,18 @@ def normalize_domain(domain: str) -> str: """Normalize and validate a target domain string for template substitution.""" - norm = domain.strip().lower().lstrip(".") + import dns.exception + import dns.name + + clean = domain.strip().removeprefix(".") + try: + parsed = dns.name.from_text(clean) + norm = parsed.to_unicode(omit_final_dot=True).lower() + except (dns.exception.DNSException, ValueError, AttributeError) as exc: + raise KubernetesContextError( + f"Invalid domain name for template substitution: {domain!r}. " + "Must be a valid RFC 1123 domain name." + ) from exc if not norm or not CONST_K8S_SUBDOMAIN_RE.match(norm): raise KubernetesContextError( f"Invalid domain name for template substitution: {domain!r}. " diff --git a/tests/test_k8s_template.py b/tests/test_k8s_template.py index 0723ca52dc..bf7831ceda 100644 --- a/tests/test_k8s_template.py +++ b/tests/test_k8s_template.py @@ -27,7 +27,8 @@ def test_normalize_domain_valid() -> None: """Normalize whitespace, uppercase, and leading dots on valid domains.""" res_a = normalize_domain(" EXAMPLE.COM ") res_b = normalize_domain(".example.com") - assert (res_a, res_b) == ("example.com", "example.com") + res_c = normalize_domain("example.com.") + assert (res_a, res_b, res_c) == ("example.com", "example.com", "example.com") def test_normalize_domain_invalid_raises() -> None: diff --git a/tests/test_net_construct_rules.py b/tests/test_net_construct_rules.py index 3323640797..c5a7bb6fec 100644 --- a/tests/test_net_construct_rules.py +++ b/tests/test_net_construct_rules.py @@ -117,6 +117,96 @@ def test_ast_grep_scan_detects_net_url_build(tmp_path: Path) -> None: assert "net-url-build" in res.stdout or "net-url-build" in res.stderr +def test_ast_grep_scan_detects_net_domain_suffix(tmp_path: Path) -> None: + """ast-grep scan detects domain string suffix matching in source code.""" + scratch = tmp_path / "scratch.py" + scratch.write_text('inside = host.endswith(".example.com")\n', encoding="utf-8") + + res = subprocess.run( + ["ast-grep", "scan", str(scratch)], + capture_output=True, + text=True, + check=False, + ) + assert res.returncode != 0 + assert "net-domain-suffix" in res.stdout or "net-domain-suffix" in res.stderr + + +def test_ast_grep_scan_detects_net_domain_list(tmp_path: Path) -> None: + """ast-grep scan detects literal lists of domain suffixes in source code.""" + scratch = tmp_path / "scratch.py" + scratch.write_text('LOCAL_DOMAINS = (".internal", ".home.arpa")\n', encoding="utf-8") + + res = subprocess.run( + ["ast-grep", "scan", str(scratch)], + capture_output=True, + text=True, + check=False, + ) + assert res.returncode != 0 + assert "net-domain-list" in res.stdout or "net-domain-list" in res.stderr + + +def test_ast_grep_scan_detects_net_normalise(tmp_path: Path) -> None: + """ast-grep scan detects hand-rolled host canonicalisation in source code.""" + scratch = tmp_path / "scratch.py" + scratch.write_text('host = value.strip("[]")\n', encoding="utf-8") + + res = subprocess.run( + ["ast-grep", "scan", str(scratch)], + capture_output=True, + text=True, + check=False, + ) + assert res.returncode != 0 + assert "net-normalise" in res.stdout or "net-normalise" in res.stderr + + +def test_ast_grep_scan_detects_net_hostport(tmp_path: Path) -> None: + """ast-grep scan detects host/port split operations in source code.""" + scratch = tmp_path / "scratch.py" + scratch.write_text('host, _, port = endpoint.rpartition(":")\n', encoding="utf-8") + + res = subprocess.run( + ["ast-grep", "scan", str(scratch)], + capture_output=True, + text=True, + check=False, + ) + assert res.returncode != 0 + assert "net-hostport" in res.stdout or "net-hostport" in res.stderr + + +def test_ast_grep_scan_detects_net_ip_literal(tmp_path: Path) -> None: + """ast-grep scan detects IP address literal comparison in source code.""" + scratch = tmp_path / "scratch.py" + scratch.write_text('local = host == "127.0.0.1"\n', encoding="utf-8") + + res = subprocess.run( + ["ast-grep", "scan", str(scratch)], + capture_output=True, + text=True, + check=False, + ) + assert res.returncode != 0 + assert "net-ip-literal" in res.stdout or "net-ip-literal" in res.stderr + + +def test_ast_grep_scan_detects_net_cidr_build(tmp_path: Path) -> None: + """ast-grep scan detects manual CIDR string construction in source code.""" + scratch = tmp_path / "scratch.py" + scratch.write_text('network = f"{ip}/32"\n', encoding="utf-8") + + res = subprocess.run( + ["ast-grep", "scan", str(scratch)], + capture_output=True, + text=True, + check=False, + ) + assert res.returncode != 0 + assert "net-cidr-build" in res.stdout or "net-cidr-build" in res.stderr + + def test_ruff_tid251_detects_banned_socket_apis(tmp_path: Path) -> None: """Ruff TID251 flags banned socket.inet_* APIs in source code.""" scratch = tmp_path / "scratch.py" diff --git a/tests/test_pydantic_ai_ollama.py b/tests/test_pydantic_ai_ollama.py index 4d56d080c6..991e653fd6 100644 --- a/tests/test_pydantic_ai_ollama.py +++ b/tests/test_pydantic_ai_ollama.py @@ -114,7 +114,11 @@ def test_is_ollama_cloud() -> None: # By base_url assert is_ollama_cloud(base_url="https://ollama.com/v1") is True + assert is_ollama_cloud(base_url="https://OLLAMA.COM/v1") is True + assert is_ollama_cloud(base_url="https://ollama.com./v1") is True assert is_ollama_cloud(base_url="https://api.ollama.com/v1") is True + assert is_ollama_cloud(base_url="https://evilollama.com/v1") is False + assert is_ollama_cloud(base_url="http://[::1]:11434/v1") is False assert is_ollama_cloud(base_url="http://localhost:11434/v1") is False assert is_ollama_cloud(base_url="http://192.168.1.50:11434/v1") is False assert is_ollama_cloud(base_url="https://attacker-ollama.com/v1") is False diff --git a/tests/test_review_profile.py b/tests/test_review_profile.py index 590cf11514..23fe851fdf 100644 --- a/tests/test_review_profile.py +++ b/tests/test_review_profile.py @@ -379,9 +379,17 @@ def test_backend_labels_drop_the_cluster_dns_suffix() -> None: """Verify in-cluster backends are labelled by pod or service, other backends by host.""" assert [ _backend_host("http://ollama-0.ollama-nodes.llm.svc.cluster.local:11434"), - _backend_host("http://ollama-16gib.llm.svc.cluster.local:11434"), + _backend_host("http://OLLAMA-16GIB.llm.svc.cluster.local.:11434"), + _backend_host("http://evil-svc.cluster.local.evil.com:11434"), + _backend_host("http://[::1]:11434"), _backend_host(REMOTE), - ] == ["ollama-0", "ollama-16gib", "remote.example.com"] + ] == [ + "ollama-0", + "ollama-16gib", + "evil-svc.cluster.local.evil.com", + "::1", + "remote.example.com", + ] def test_profiler_accumulates_cost_usd_per_stage(tmp_path: Path) -> None: diff --git a/tests/test_vulnerability_lookup.py b/tests/test_vulnerability_lookup.py index f066a65f1f..f7e513f779 100644 --- a/tests/test_vulnerability_lookup.py +++ b/tests/test_vulnerability_lookup.py @@ -574,3 +574,16 @@ def test_extract_domain_target() -> None: CloudflareRadarClient._extract_domain_target("example.com:8080"), extract_domain_target("example.com:8080"), ) == ("example.com", "example.com") + + +def test_read_url_or_authority() -> None: + """Verify read_url_or_authority parses URLs and host[:port] authorities safely.""" + from devops_cli.http.urls import read_url_or_authority + + assert read_url_or_authority("https://example.com:443/path").hostname == "example.com" + assert read_url_or_authority("example.com:8080").port == 8080 + assert read_url_or_authority("user:pass@example.com:9000").hostname == "example.com" + assert read_url_or_authority("[2001:db8::1]:8080").hostname == "2001:db8::1" + assert read_url_or_authority("example.com:") is None + assert read_url_or_authority("user:pass@example.com:") is None + assert read_url_or_authority("") is None