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-bracket-affix-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
id: net-bracket-affix
valid:
- 'host = urlsplit(url).hostname'
invalid:
- 'is_v6 = host.startswith("[") and ":" in host'
8 changes: 8 additions & 0 deletions .ast-grep/rule-tests/net-scheme-affix-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
id: net-scheme-affix
valid:
- 'secure = urlsplit(url).scheme == "https"'
- 'is_meta = ipaddress.ip_address(host).is_link_local'
invalid:
- 'secure = url.startswith("https://")'
- 'is_meta = host.startswith("169.254.")'
- 'path = address.removeprefix("unix:path=")'
6 changes: 6 additions & 0 deletions .ast-grep/rule-tests/net-scheme-in-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
id: net-scheme-in
valid:
- 'has_scheme = urlsplit(url).scheme in ("http", "https")'
invalid:
- 'has_scheme = "://" in url'
- 'bare = "://" not in url'
7 changes: 7 additions & 0 deletions .ast-grep/rule-tests/net-url-build-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
id: net-url-build
valid:
- 'url = str(httpx2.URL(scheme="http", host=host, port=port))'
- 'message = f"see {host} for details"'
invalid:
- 'url = f"http://{host}:{port}"'
- 'url = f"http://{node_ip}:{node_port}"'
25 changes: 25 additions & 0 deletions .ast-grep/rules/net-bracket-affix.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
id: net-bracket-affix
language: python
severity: error
message: IPv6 brackets handled by hand. urllib.parse.urlsplit(value).hostname or httpx2.URL(value).host returns the bare host; parse it with ipaddress.ip_address.
rule:
kind: call
all:
- has:
field: function
kind: attribute
has:
field: attribute
regex: ^(startswith|endswith)$
- has:
field: arguments
has:
kind: string
regex: '^["'']\[["'']$'
- inside:
kind: boolean_operator
stopBy: end
has:
stopBy: end
kind: string
regex: ':'
19 changes: 19 additions & 0 deletions .ast-grep/rules/net-scheme-affix.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
id: net-scheme-affix
language: python
severity: error
message: Prefix or suffix test on a scheme or an address. Read the scheme with urllib.parse.urlsplit(value).scheme, container-engine endpoints (Podman or Docker) with docker.utils.parse_host and D-Bus addresses with jeepney; classify addresses with ipaddress (is_link_local, is_loopback, is_private).
rule:
kind: call
all:
- has:
field: function
kind: attribute
has:
field: attribute
regex: ^(startswith|endswith|removeprefix|removesuffix|replace)$
- has:
field: arguments
has:
stopBy: end
kind: string
regex: '://|^["'']unix:|^["'']\d{1,3}\.(\d{1,3}\.){0,2}["'']$'
12 changes: 12 additions & 0 deletions .ast-grep/rules/net-scheme-in.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
id: net-scheme-in
language: python
severity: error
message: Scheme detected by substring. Read it with urllib.parse.urlsplit(value).scheme.
rule:
any:
- pattern: $S in $X
- pattern: $S not in $X
constraints:
S:
kind: string
regex: "://"
7 changes: 7 additions & 0 deletions .ast-grep/rules/net-url-build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
id: net-url-build
language: python
severity: error
message: URL authority built with an f-string. Build it with httpx2.URL(scheme=..., host=..., port=...), which brackets IPv6 hosts, or httpx2.URL.copy_with / join.
rule:
kind: string
regex: '(?i)^f["''][a-z][a-z0-9+.-]*://\{[a-z_.]*(host|addr|address|ip|netloc|url|target|endpoint)'
27 changes: 26 additions & 1 deletion docs/agent/tasks/task-1107-hand-rolled-network-parsing-gate.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,33 @@ Delivered across 5 incremental pull requests.
- `src/devops_cli/ai/kb.py`: knowledge base article sources validation.
- [x] Add unit tests for case-insensitive scheme matching (`HTTPS://`) and non-URLs, TLS SAN `x509.IPAddress` generation, string JSON output, and `net-address-list` ast-grep scanner detection.

### PR 4: Scheme, URL Authority, and IPv6 Bracket ast-grep Rules (Part of #1107)

- [x] Add `jeepney==0.9.0` to dependencies in `pyproject.toml` and lock with `uv lock`.
- [x] Add 4 `net-*` rules to `.ast-grep/rules/` and unit tests to `.ast-grep/rule-tests/`:
- `net-scheme-in`: flags substring tests `"://" in x` or `not in x`.
- `net-scheme-affix`: flags prefix/suffix tests on schemes, unix sockets, or IPv4 prefixes.
- `net-bracket-affix`: flags hand-rolled IPv6 bracket parsing with `startswith("[")` and `":" in host`.
- `net-url-build`: flags building URL authorities using f-strings instead of `httpx2.URL`.
- [x] Register `"net-bracket-affix"`, `"net-scheme-affix"`, `"net-scheme-in"`, and `"net-url-build"` in `CONST_NET_CONSTRUCT_RULES` in `src/devops_cli/config/constants.py`.
- [x] Add `CONST_VALKEY_SCHEMES` to `src/devops_cli/config/constants.py`.
- [x] Remediate hand-rolled scheme, URL authority, and bracket parsing across `src/`:
- `src/devops_cli/valkey/client.py`: parse Valkey and Redis endpoints using `urllib.parse.urlsplit`.
- `src/devops_cli/config/settings.py`: parse and normalize Valkey URLs and hosts using `urllib.parse.urlsplit`.
- `src/devops_cli/commands/devcontainer.py`: parse `DBUS_SESSION_BUS_ADDRESS` using `jeepney.bus.parse_addresses`.
- `src/devops_cli/commands/ai_gateway.py`: construct gateway URL authority with `httpx2.URL(scheme="http", host=host, port=port)`.
- `src/devops_cli/commands/ai_runs.py`: construct Valkey run index URL with `httpx2.URL(scheme="valkey", host=host, port=port)`.
- `src/devops_cli/commands/k8s/cluster_context.py`: check manifest path scheme with `bool(urlsplit(path).scheme)`.
- `src/devops_cli/commands/repos.py`: extract URL path and file scheme using `urllib.parse.urlsplit`.
- `src/devops_cli/commands/sandbox.py`: check target schemes with `bool(urlsplit(identifier).scheme)`.
- `src/devops_cli/core/paths.py`: check absolute path schemes with `bool(urlsplit(unquoted).scheme)`.
- `src/devops_cli/k8s/argocd_gate.py`: normalize git URLs with `urllib.parse.urlsplit`.
- `src/devops_cli/roadmap/refine.py`: check HTTP/HTTPS source schemes with `urlsplit(src).scheme in {"http", "https"}`.
- `src/devops_cli/security/reference_extractor.py`: validate URL targets using `urllib.parse.urlsplit` without substring checks.
- `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 2: AGENTS.md, template, `generate_agents.md`, `architecture.md` instruction updates and `.devops/review.md` house rule under #1107.
- PR 4: `net-scheme-in`, `net-scheme-affix`, `net-url-build`, `net-bracket-affix` under #1107.
- PR 5: `net-domain-suffix`, `net-domain-list`, `net-normalise`, `net-hostport` under #1107 (closes #1107).
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ dependencies = [
"pydantic-graph==2.54.0",
"opentelemetry-api==1.44.0",
"secretstorage==3.5.0; sys_platform == 'linux'",
"jeepney==0.9.0",
"dnspython[idna]==2.8.0",
"genai-prices==0.1.9",
"opentelemetry-exporter-otlp-proto-grpc==1.44.0",
Expand Down
4 changes: 2 additions & 2 deletions src/devops_cli/ai/agents/media.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import sqlite3
from pathlib import Path
from typing import Any, Protocol, runtime_checkable
from urllib.parse import parse_qs, urlencode, urlparse
from urllib.parse import parse_qs, urlencode, urlparse, urlsplit

from pydantic import BaseModel, Field

Expand Down Expand Up @@ -181,7 +181,7 @@ def externalize_media(data: Any, store: MediaStore) -> Any:

def restore_media(data: Any, store: MediaStore) -> Any:
"""Recursively resolve media+sha256:// URIs back to BinaryContent instances."""
if isinstance(data, str) and data.startswith("media+sha256://"):
if isinstance(data, str) and urlsplit(data).scheme == "media+sha256":
content = store.get(data)
return content if content is not None else data
elif isinstance(data, dict):
Expand Down
5 changes: 5 additions & 0 deletions src/devops_cli/commands/ai.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,11 @@ def _try_retrieve_rag_context(
) -> str | None:
"""Attempt to retrieve relevant semantic context from RAG vector store."""
try:
from devops_cli.config.settings import load_settings

if not load_settings().ai.rag.enabled:
return None

from devops_cli.ai.rag.investigator import investigate_rag_context
from devops_cli.ai.rag.kb_sync import ensure_knowledge_base_ready
from devops_cli.commands.rag import _get_rag_components
Expand Down
3 changes: 2 additions & 1 deletion src/devops_cli/commands/ai_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from pathlib import Path
from typing import Annotated, Any

import httpx2
import typer

from devops_cli.ai.client.models import AICredentialsError
Expand Down Expand Up @@ -203,7 +204,7 @@ def connect_cmd(
print_error(f"Cannot find the LLM gateway: {exc.message}", prefix=False)
raise typer.Exit(code=1) from exc

base_url = f"http://{host}:{port}"
base_url = str(httpx2.URL(scheme="http", host=host, port=port))
node_port_url = f"{base_url}/v1"
validate_url_egress(base_url, purpose="AI gateway", allow_private=True)

Expand Down
3 changes: 2 additions & 1 deletion src/devops_cli/commands/ai_runs.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import json
from typing import Annotated, Any

import httpx2
import typer

from devops_cli.ai.run_store import (
Expand Down Expand Up @@ -156,7 +157,7 @@ def connect_cmd(
except ServiceNotReachableError as exc:
print_error(f"Cannot find the run index: {exc.message}", prefix=False)
raise typer.Exit(code=1) from exc
url = f"valkey://{host}:{port}"
url = str(httpx2.URL(scheme="valkey", host=host, port=port))
records = load_runs()
try:
with RunIndex.connect(url, password) as index:
Expand Down
14 changes: 11 additions & 3 deletions src/devops_cli/commands/devcontainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -1282,10 +1282,18 @@ def _run_post_start_lifecycle(workspace_dir: Path, *, dry_run: bool = False) ->

def _session_bus_socket() -> Path | None:
"""Return the socket path named by a unix:path= DBUS_SESSION_BUS_ADDRESS, if one is set."""
address = os.getenv("DBUS_SESSION_BUS_ADDRESS", "")
if not address.startswith("unix:path="):
address = os.getenv("DBUS_SESSION_BUS_ADDRESS", "").strip()
if not address:
return None
return Path(address.removeprefix("unix:path=").split(",", 1)[0])
try:
from jeepney.bus import parse_addresses # type: ignore[import-untyped]

for transport, params in parse_addresses(address):
if transport == "unix" and "path" in params:
return Path(params["path"])
except ValueError, KeyError:
return None
return None


def _is_session_bus_running(socket_path: Path) -> bool:
Expand Down
3 changes: 2 additions & 1 deletion src/devops_cli/commands/k8s/cluster_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import json
import logging
from typing import Annotated, Any
from urllib.parse import urlsplit

import typer

Expand Down Expand Up @@ -192,7 +193,7 @@ def apply(
] = None,
) -> None:
"""Apply a Kubernetes manifest (delegates to kubectl)."""
if "://" in path:
if bool(urlsplit(path).scheme):
validate_url_egress(
path,
purpose="manifest",
Expand Down
8 changes: 4 additions & 4 deletions src/devops_cli/commands/repos.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,12 +205,12 @@ def clone_org(
def _extract_url_path(url: str) -> tuple[str, bool]:
"""Extract raw path from URL and return whether it is a file:// scheme."""
clean = url.strip()
if ":" in clean and "://" not in clean:
parsed = urlsplit(clean)
if parsed.scheme:
return parsed.path, parsed.scheme == "file"
if ":" in clean:
_, _, path = clean.rpartition(":")
return path, False
if "://" in clean:
parsed = urlsplit(clean)
return parsed.path, parsed.scheme == "file"
return clean, False


Expand Down
5 changes: 3 additions & 2 deletions src/devops_cli/commands/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import json
from pathlib import Path
from typing import Annotated, Any
from urllib.parse import urlsplit

import typer
import yaml
Expand Down Expand Up @@ -453,7 +454,7 @@ def probe(
else:
raise SandboxNotFoundError(f"Sandbox '{identifier}' not found")
except SandboxNotFoundError as exc:
if "://" in identifier or ":" in identifier:
if bool(urlsplit(identifier).scheme) or ":" in identifier:
from devops_cli.sandbox.probe import run_sandbox_probes

report = run_sandbox_probes(
Expand Down Expand Up @@ -675,7 +676,7 @@ def metrics(
latency_sla_ms=latency_sla_ms,
)
except SandboxNotFoundError as exc:
if "://" in identifier or ":" in identifier:
if bool(urlsplit(identifier).scheme) or ":" in identifier:
from devops_cli.sandbox.metrics import collect_sandbox_metrics

snapshot = collect_sandbox_metrics(
Expand Down
9 changes: 9 additions & 0 deletions src/devops_cli/config/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -2597,6 +2597,11 @@
# RAG embedding distributed caching
CONST_VALKEY_EMBEDDING_PREFIX: Final[str] = "valkey:rag:embedding"

# Schemes recognized for Valkey and Redis connection endpoints
CONST_VALKEY_SCHEMES: Final[frozenset[str]] = frozenset(
{"valkey", "valkeys", "redis", "rediss", "tcp"}
)

# Characters of a failed embedding reply's body quoted in its EmbeddingsError
CONST_EMBEDDING_REPLY_EXCERPT_CHARS: Final[int] = 500

Expand Down Expand Up @@ -4078,9 +4083,13 @@
)
CONST_NET_CONSTRUCT_RULES: Final[tuple[str, ...]] = (
"net-address-list",
"net-bracket-affix",
"net-cidr-build",
"net-ip-literal",
"net-port-table",
"net-scheme-affix",
"net-scheme-in",
"net-url-build",
)
CONST_AST_GREP_SCAN_ARGS: Final[tuple[str, ...]] = (
"scan",
Expand Down
37 changes: 21 additions & 16 deletions src/devops_cli/config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from collections.abc import Iterable
from pathlib import Path
from typing import Any
from urllib.parse import urlsplit

import yaml
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
Expand All @@ -22,6 +23,7 @@
CONST_AI_GATEWAY_PROVIDER,
CONST_KEYRING_UNLOCK_PROBE_KEY,
CONST_SETTINGS_CACHE_SETTLE_SECONDS,
CONST_VALKEY_SCHEMES,
)
from devops_cli.config.constants import (
CONST_CONFIG_PATH as CONFIG_PATH,
Expand Down Expand Up @@ -214,13 +216,13 @@ class OpenWebUIConfig(BaseModel):

def _parse_valkey_url(raw_url: str, data: dict[str, Any]) -> None:
"""Derive host, port, and password from valkey connection URL."""
from urllib.parse import urlparse

if not isinstance(raw_url, str):
return
clean_url = raw_url.strip()
if "://" not in clean_url:
clean_url = f"tcp://{clean_url}"
scheme = urlsplit(clean_url).scheme.lower()
target = clean_url if scheme in CONST_VALKEY_SCHEMES else f"//{clean_url}"
try:
parsed = urlparse(clean_url)
parsed = urlsplit(target)
if parsed.hostname:
port = parsed.port or 6379
h = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
Expand All @@ -234,19 +236,22 @@ def _parse_valkey_url(raw_url: str, data: dict[str, Any]) -> None:

def _normalize_valkey_host(raw_host: str, raw_port: Any, data: dict[str, Any]) -> None:
"""Normalize host string and port integer."""
if not isinstance(raw_host, str):
return
clean = raw_host.strip()
if clean.startswith("[") and "]:" in clean:
_, p = clean.rsplit("]:", 1)
if p.isdigit():
data["host"] = clean
data["port"] = int(p)
return
elif ":" in clean and not clean.startswith("["):
parts = clean.rsplit(":", 1)
if parts[1].isdigit():
data["host"] = clean
data["port"] = int(parts[1])
scheme = urlsplit(clean).scheme.lower()
target = clean if scheme in CONST_VALKEY_SCHEMES else f"//{clean}"
try:
parsed = urlsplit(target)
if parsed.hostname:
port = parsed.port or (int(raw_port) if raw_port is not None else None)
h = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
data["host"] = f"{h}:{port}" if port is not None else h
if port is not None:
data["port"] = port
return
except ValueError, AttributeError:
pass
if raw_port is not None:
data["host"] = f"{clean}:{raw_port}"

Expand Down
3 changes: 2 additions & 1 deletion src/devops_cli/core/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import re
from pathlib import Path
from typing import Any, TypeVar
from urllib.parse import urlsplit

from devops_cli.config.constants import CONST_FORBIDDEN_SYSTEM_DIRS
from devops_cli.exceptions import ValidationError
Expand Down Expand Up @@ -187,7 +188,7 @@ def validate_path_parameter(
p.is_absolute()
or raw_str.startswith(("/", "\\"))
or unquoted.startswith(("/", "\\", "~"))
or "://" in unquoted
or bool(urlsplit(unquoted).scheme)
)
if is_abs:
raise error_cls(
Expand Down
Loading
Loading