Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .ast-grep/rule-tests/net-domain-list-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
id: net-domain-list
valid:
- 'LOCAL_DOMAIN = "example.com"'
invalid:
- 'LOCAL_DOMAIN_SUFFIXES = (".internal", ".home.arpa")'
8 changes: 8 additions & 0 deletions .ast-grep/rule-tests/net-domain-suffix-test.yml
Original file line number Diff line number Diff line change
@@ -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)'
7 changes: 7 additions & 0 deletions .ast-grep/rule-tests/net-hostport-test.yml
Original file line number Diff line number Diff line change
@@ -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(":")'
7 changes: 7 additions & 0 deletions .ast-grep/rule-tests/net-normalise-test.yml
Original file line number Diff line number Diff line change
@@ -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(".")'
16 changes: 16 additions & 0 deletions .ast-grep/rules/net-domain-list.yml
Original file line number Diff line number Diff line change
@@ -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]'
23 changes: 23 additions & 0 deletions .ast-grep/rules/net-domain-suffix.yml
Original file line number Diff line number Diff line change
@@ -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?["'']\.'
16 changes: 16 additions & 0 deletions .ast-grep/rules/net-hostport.yml
Original file line number Diff line number Diff line change
@@ -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)
26 changes: 26 additions & 0 deletions .ast-grep/rules/net-normalise.yml
Original file line number Diff line number Diff line change
@@ -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\(\)'
9 changes: 9 additions & 0 deletions changelog.d/1107.md
Original file line number Diff line number Diff line change
@@ -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)).
25 changes: 22 additions & 3 deletions docs/agent/tasks/task-1107-hand-rolled-network-parsing-gate.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
14 changes: 11 additions & 3 deletions src/devops_cli/ai/models/ollama.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion src/devops_cli/ai/spend/pricing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 3 additions & 3 deletions src/devops_cli/commands/k8s/networking.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
18 changes: 15 additions & 3 deletions src/devops_cli/commands/review.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
4 changes: 4 additions & 0 deletions src/devops_cli/config/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
19 changes: 17 additions & 2 deletions src/devops_cli/core/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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):
Expand Down
3 changes: 1 addition & 2 deletions src/devops_cli/http/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
13 changes: 12 additions & 1 deletion src/devops_cli/k8s/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}. "
Expand Down
3 changes: 2 additions & 1 deletion tests/test_k8s_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading
Loading