Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(net): harden outbound endpoint validation (#1527)
Alpamys Makazhan5c335b93c3e4
diff --git a/docs/data.md b/docs/data.mdindex 113f7149..b584a69e 100644--- a/docs/data.md+++ b/docs/data.md@@ -388,7 +388,7 @@ soup ingest --source langfuse --pull --since 7d --output traces.jsonl- **What one row is.** One output row per `GENERATION` observation in the window — the unit that carries a model, the exact input it was given and the output it produced — read from Langfuse's Observations API v2 (`/api/public/traces` is removed from Langfuse Cloud on 2026-11-16) and checked again on each observation, so a server that ignores the `type` filter cannot turn spans or tool calls into rows — they are counted as skipped in the summary. A row's `trace_id` is the observation id. The API returns plain-text input and output as-is but structured values (chat message lists, objects) as JSON inside a string; those are decoded, and a chat message list becomes a `prompt` of every message's content joined by newlines (system prompt included), the same flattening `parse_langfuse` applies to a `{"messages": [...]}` export. An agent trace therefore yields one row per LLM call it made; its spans and tool calls yield none. Generations with no input or no output are skipped and counted in the summary line, so a pull that matched nothing usable says so instead of writing an empty file silently.- **Credentials.** Read from the environment only, never from a flag, so they never reach the audit log's argv. `LANGFUSE_BASE_URL` is honoured before `LANGFUSE_HOST`, the same precedence as the Langfuse SDK. The key pair is not written to the output, the console, debug logs or error messages.-- **Host checks.** HTTPS only. The host goes through the same SSRF validator as `--slack-url`; a private, link-local or loopback address (self-hosted Langfuse) additionally needs `--allow-private-host`. Redirects are refused rather than followed with credentials attached.+- **Host checks.** HTTPS only. The host goes through the same SSRF validator as `--slack-url`; a private, link-local, shared (`100.64.0.0/10`), site-local (`fec0::/10`) or loopback address (self-hosted Langfuse) additionally needs `--allow-private-host`. Redirects are refused rather than followed with credentials attached.- **Bounds.** `--since` accepts `30m` / `24h` / `7d` up to `365d` (default `7d`). Each request is bounded by a 30 s wall-clock deadline covering the connect and the whole response — a server that drip-feeds bytes cannot outlast it — and a response is capped at 64 MiB. Pages hold 100 generations; if results are still pending after `--max-pages` pages (default 100, max 10 000), the command stops with exit 1 and writes nothing — the output streams to a staging file, so an earlier file at `--output` is left untouched. HTTP 429 is retried up to 5 times, honouring `Retry-After` with a 60 s ceiling, and a pagination cursor the server repeats stops the pull instead of spending the rest of the page budget.- **Without `--pull`** nothing changes: the pull code is not imported and no connection is opened.@@ -427,7 +427,7 @@ soup data active-sample --input traces.jsonl --output for-review.jsonl --budgetThe output JSONL is a drop-in prompt set for `soup eval human` (v0.19). Budget is bounded `[1, 100 000]`.-**Webhooks (v0.71.5).** `soup ingest`, `soup prune-prompt`, `soup ab`, and `soup data active-sample` all accept `--slack-url` / `--discord-url` and POST a one-line summary on completion through the same SSRF-hardened validator as `soup drift-alarm` (scheme allowlist, loopback-only HTTP, RFC1918 / link-local / reserved / multicast rejected; the post never raises, so a flaky webhook can't fail the command). `soup ab` only fires when the sequential test actually decides (`reject_h0` / `accept_h0`), not while it's still `continue`-ing.+**Webhooks (v0.71.5).** `soup ingest`, `soup prune-prompt`, `soup ab`, and `soup data active-sample` all accept `--slack-url` / `--discord-url` and POST a one-line summary on completion through the same SSRF-hardened validator as `soup drift-alarm` (scheme allowlist, loopback-only HTTP, RFC1918 / link-local / shared `100.64.0.0/10` / site-local `fec0::/10` / reserved / multicast rejected; the post never raises, so a flaky webhook can't fail the command). `soup ab` only fires when the sequential test actually decides (`reject_h0` / `accept_h0`), not while it's still `continue`-ing.## Synthetic Data Generation@@ -451,6 +451,11 @@ soup data generate --prompt "..." --seed examples.jsonl --count 100soup data generate --prompt "..." --provider server --api-base http://localhost:11434/v1```+With `--provider server`, `openai` or `vllm`, `--api-base` takes plain HTTP only for loopback+(`localhost`, `127.0.0.1`, `::1`) and HTTPS for any other host; `--provider ollama` stays+loopback-only. A private, link-local or reserved IP literal is refused on either scheme, so+address a server on your network by its hostname.+### Multi-Provider Support```bash@@ -520,12 +525,12 @@ soup data augment ./data/train.jsonl --strategy translate --lang es,fr,de \soup data augment ./data/train.jsonl --strategy style --styles formal,casual \--output ./data/train_styled.jsonl-# Local provider (Ollama / vLLM) — loopback-only, pick the model + base URL+# Local provider (Ollama, loopback-only) — pick the model + base URLsoup data augment ./data/train.jsonl --strategy rephrase --count 2 \--provider ollama --model qwen2.5:0.5b --output ./data/train_local.jsonl```-Works with any provider supported by `soup data generate` (OpenAI, Ollama, vLLM, local server). `--model` and `--base-url` select a specific local model/endpoint; the Ollama/vLLM paths are loopback-only (SSRF-hardened). `--count` is capped at 10; `--lang` and `--styles` each capped at 10 entries × 32 chars.+Works with `--provider ollama` (the default), `anthropic` or `vllm`. `--model` and `--base-url` select a specific model/endpoint. The Ollama path is loopback-only; the vLLM path takes plain HTTP only for loopback and HTTPS for a remote server, and refuses a private, link-local or reserved IP literal (SSRF-hardened). `--count` is capped at 10; `--lang` and `--styles` each capped at 10 entries × 32 chars.A provider call that fails (transport error, non-200 status, malformed response) or returns an empty reply never becomes a row: that variant is dropped. The summary reports `N of M provider calls failed` with the first error, and the command exits 1 without writing the output file when no call produced a usable row.diff --git a/docs/evaluation.md b/docs/evaluation.mdindex acb3fb4f..8187dc83 100644--- a/docs/evaluation.md+++ b/docs/evaluation.md@@ -256,7 +256,7 @@ tasks:judge_model: ollama://llama3.1 # SSRF-allowlisted scheme```-`judge_model` accepts `ollama://<model>`, `http://localhost:<port>/<model>` or `https://<host>/<model>`. An `https://` judge URL uses `OPENAI_API_KEY` only when its host is `api.openai.com`; other hosts are called as an OpenAI-compatible server without that key.+`judge_model` accepts `ollama://<model>`, `http://localhost:<port>/<model>` or `https://<host>/<model>`. An `https://` judge URL uses `OPENAI_API_KEY` only when its host is `api.openai.com`; other hosts are called as an OpenAI-compatible server without that key. A judge URL whose host is a private, link-local or reserved IP literal is refused when the suite loads (loopback stays allowed): `soup eval gate` and `soup train --gate` stop with the error, and a suite named in `training.eval_gate` is skipped with a warning. Address an internal judge by its hostname.Baselines may be a registry reference (`registry://<name-or-id>`), a file path, or omitted for the first run. A registry baseline uses the newest eval row for each benchmark — re-measuring a benchmark replaces its baseline score — and warns, per benchmark, when that row's scorer stamp is missing or from a different scorer revision. A task whose evaluation raises (`ValueError`, `FileNotFoundError`, `OSError`, or a judge that stays unreachable) gets no score and fails the gate closed under `on_regression: stop`; the log line lists it as a task that could not be scored, with the error, rather than as a regression (#1447).@@ -310,7 +310,7 @@ soup drift-alarm --reference ft-time.jsonl --live yesterday.jsonl --threshold 0.--discord-url https://discord.com/api/webhooks/...```-Default threshold 0.2 matches v0.43.0 KL-delta quant-check thresholds. Webhooks are SSRF-validated (loopback HTTP only, RFC1918 / 169.254.x / 0.0.0.0 rejected). On drift the CLI exits with code 3 — cron-friendly automation.+Default threshold 0.2 matches v0.43.0 KL-delta quant-check thresholds. Webhooks are SSRF-validated (loopback HTTP only, RFC1918 / 169.254.x / `100.64.0.0/10` / `fec0::/10` / 0.0.0.0 rejected). On drift the CLI exits with code 3 — cron-friendly automation.## Diagnose (Post-Training Report Card)diff --git a/docs/serving-and-export.md b/docs/serving-and-export.mdindex e9fe1c90..ff36d7b5 100644--- a/docs/serving-and-export.md+++ b/docs/serving-and-export.md@@ -625,7 +625,7 @@ soup serve --model ./output \--trace-endpoint http://localhost:4317```-The OTLP endpoint is SSRF-hardened: only http/https schemes, plain HTTP only for loopback (`localhost`/`127.0.0.1`/`::1`), and RFC1918 / link-local / `0.0.0.0` all rejected via `ipaddress.ip_address`. When the SDK is missing the flag is a no-op with a warning — the server starts fine without spans.+The OTLP endpoint is SSRF-hardened: only http/https schemes, plain HTTP only for loopback (`localhost`/`127.0.0.1`/`::1`), and RFC1918 / link-local / shared `100.64.0.0/10` / site-local `fec0::/10` / `0.0.0.0` all rejected via `ipaddress.ip_address`. When the SDK is missing the flag is a no-op with a warning — the server starts fine without spans.> **Note:** `max_tokens` is capped at 16,384 per request. Error details are never exposed in HTTP responses.diff --git a/docs/training.md b/docs/training.mdindex a3cfca24..4410178c 100644--- a/docs/training.md+++ b/docs/training.md@@ -905,7 +905,9 @@ The judge is Soup's own OpenAI-compatible `JudgeEvaluator` adapted to TRL'sB,A orders agree). Recipe: `online-dpo-smollm2-135m`. Proof-of-mechanism wasvalidated on SmolLM2-135M with a synthetic judge (not a production RLHF claim; #286).An `https://` judge URL uses `OPENAI_API_KEY` only when its host is `api.openai.com`; other-hosts are called as an OpenAI-compatible server without that key.+hosts are called as an OpenAI-compatible server without that key. An `online_dpo_judge` whose+host is a private, link-local or reserved IP literal is refused when soup.yaml loads (loopback+stays allowed); address an internal judge by its hostname.A pair the judge cannot rank is left out of the loss: a tie, a failed or unreadable judgecall, or a verdict that changes when the two completions are swapped. Such a pair adds nodiff --git a/src/soup_cli/commands/generate.py b/src/soup_cli/commands/generate.pyindex 6867fa54..2333448d 100644--- a/src/soup_cli/commands/generate.py+++ b/src/soup_cli/commands/generate.py@@ -710,17 +710,21 @@ def _generate_openai(base_url = api_base or "https://api.openai.com/v1"- # Validate api_base to prevent SSRF (block non-HTTPS remote URLs)+ # Validate api_base to prevent SSRF (block non-HTTPS remote URLs and+ # private / link-local / reserved IP literals; 0.0.0.0 is not loopback)if api_base:from urllib.parse import urlparse+ from soup_cli.utils.net_guard import LOOPBACK_HOSTS, refuse_private_ip_literal+parsed = urlparse(api_base)- is_local = parsed.hostname in ("localhost", "127.0.0.1", "::1", "0.0.0.0")+ is_local = parsed.hostname in LOOPBACK_HOSTSif not is_local and parsed.scheme != "https":raise ValueError(f"api_base must use HTTPS for remote APIs (got {parsed.scheme}://). ""HTTP is only allowed for localhost.")+ refuse_private_ip_literal(parsed.hostname, label="api_base")if generation_prompt is None:generation_prompt = _build_generation_prompt(prompt, count, fmt, seed_examples)@@ -849,21 +853,25 @@ def _generate_server(base_url = api_base or "http://localhost:8000/v1"- # Validate api_base to prevent SSRF — only allow http/https, block remote non-HTTPS+ # Validate api_base to prevent SSRF — only allow http/https, block remote+ # non-HTTPS and private / link-local / reserved IP literalsif api_base:from urllib.parse import urlparse+ from soup_cli.utils.net_guard import LOOPBACK_HOSTS, refuse_private_ip_literal+parsed = urlparse(api_base)if parsed.scheme not in ("http", "https"):raise ValueError(f"api_base must use HTTP or HTTPS scheme (got {parsed.scheme}://)")- is_local = parsed.hostname in ("localhost", "127.0.0.1", "::1", "0.0.0.0")+ is_local = parsed.hostname in LOOPBACK_HOSTSif not is_local and parsed.scheme != "https":raise ValueError(f"api_base must use HTTPS for remote APIs (got {parsed.scheme}://). ""HTTP is only allowed for localhost.")+ refuse_private_ip_literal(parsed.hostname, label="api_base")# Strip trailing /v1 if present (we add it to the endpoint path)base_url = base_url.rstrip("/")diff --git a/src/soup_cli/commands/ship.py b/src/soup_cli/commands/ship.pyindex 9436ea93..a5a99026 100644--- a/src/soup_cli/commands/ship.py+++ b/src/soup_cli/commands/ship.py@@ -177,12 +177,22 @@ def _validate_judge_model_url(url: str) -> None:"""SSRF guard for --judge-model: urlparse hostname check (not startswith).Blocks the ``http://localhost.attacker.com`` prefix-bypass that a bare- ``startswith("http://localhost")`` check would allow through.+ ``startswith("http://localhost")`` check would allow through, and refuses a+ private / link-local / reserved IP literal as a usage error before any+ measurement runs."""from urllib.parse import urlparse+ from soup_cli.utils.net_guard import refuse_private_ip_literal+parsed = urlparse(url)- if parsed.scheme in ("ollama", "https"):+ if parsed.scheme == "ollama":+ return+ if parsed.scheme == "https":+ try:+ refuse_private_ip_literal(parsed.hostname, label="--judge-model")+ except ValueError as exc:+ _fail(str(exc), _EXIT_USAGE)returnif parsed.scheme == "http" and parsed.hostname in ("localhost", "127.0.0.1"):return@@ -1034,21 +1044,22 @@ def _verdict_live(# would be an unbounded number of full model passes.noise_floor_runs = _validate_noise_floor_flag(noise_floor_runs)+ # Judge modes need a judge model. Validate it BEFORE the base and tuned+ # models load and before the noise floor is measured (it scores the leg-1+ # task axis through the judge as well, #403) — a missing or refused judge+ # URL is a usage error, not a runtime one discovered after a model load.+ if task_mode == "judge_score":+ if not judge_model:+ _fail("--task-mode judge_score needs --judge-model <url>", _EXIT_USAGE)+ _validate_judge_model_url(judge_model)+ elif task_mode == "pairwise":+ if not judge_model:+ _fail("--task-mode pairwise needs --judge-model <url>", _EXIT_USAGE)+ _validate_judge_model_url(judge_model)+tuned_id = tuned if tuned else basetry:base_gen, tuned_gen = _resolve_generators(base, tuned, adapter, device, quantization)- # Judge modes need a judge model. Validate it BEFORE measuring the- # noise floor, which now scores the leg-1 task axis through the judge as- # well (#403) — a missing / malformed judge is a usage error (exit 2),- # not a runtime one discovered mid-measurement.- if task_mode == "judge_score":- if not judge_model:- _fail("--task-mode judge_score needs --judge-model <url>", _EXIT_USAGE)- _validate_judge_model_url(judge_model)- elif task_mode == "pairwise":- if not judge_model:- _fail("--task-mode pairwise needs --judge-model <url>", _EXIT_USAGE)- _validate_judge_model_url(judge_model)measured_floor: Optional[NoiseFloor] = Noneif noise_floor_runs is not None:diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex 58ed884f..2d90db15 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -1546,7 +1546,12 @@ class TrainingConfig(BaseModel):@field_validator("online_dpo_judge", mode="before")@classmethoddef _validate_online_dpo_judge_field(cls, value: Any) -> Optional[str]:- """v0.71.31 — shape-only validation (SSRF enforced at trainer setup)."""+ """v0.71.31 — shape validation; the full SSRF policy runs at trainer setup.++ A private / link-local / reserved IP literal in an http(s) judge URL is+ refused here as well, so a shared soup.yaml naming one fails at load+ instead of after the model download.+ """if value is None:return Noneif isinstance(value, bool) or not isinstance(value, str):@@ -1559,6 +1564,16 @@ class TrainingConfig(BaseModel):raise ValueError("online_dpo_judge must not contain null bytes")if len(value) > 512:raise ValueError("online_dpo_judge must be <= 512 chars")+ from urllib.parse import urlparse++ from soup_cli.utils.net_guard import refuse_private_ip_literal++ try:+ parsed = urlparse(value)+ except ValueError as exc:+ raise ValueError("online_dpo_judge is not a valid URL") from exc+ if parsed.scheme in ("http", "https"):+ refuse_private_ip_literal(parsed.hostname, label="online_dpo_judge")return value# v0.71.32 — ASR (Whisper) fine-tuning knobs.diff --git a/src/soup_cli/data/providers/vllm.py b/src/soup_cli/data/providers/vllm.pyindex 8570d93b..71299184 100644--- a/src/soup_cli/data/providers/vllm.py+++ b/src/soup_cli/data/providers/vllm.py@@ -18,9 +18,12 @@ def validate_vllm_url(base_url: str) -> None:Reuses the same validation as the server provider:- Scheme must be http or https- HTTP is only allowed for localhost+ - A private / link-local / reserved IP literal is refused on any schemeRaises ValueError if validation fails."""+ from soup_cli.utils.net_guard import refuse_private_ip_literal+parsed = urlparse(base_url)if parsed.scheme not in ("http", "https"):raise ValueError(@@ -36,6 +39,7 @@ def validate_vllm_url(base_url: str) -> None:f"vLLM URL must use HTTPS for remote servers (got {parsed.scheme}://). ""HTTP is only allowed for localhost.")+ refuse_private_ip_literal(parsed.hostname, label="vLLM URL")def generate_vllm(diff --git a/src/soup_cli/eval/gate.py b/src/soup_cli/eval/gate.pyindex 624fb43d..4ae73484 100644--- a/src/soup_cli/eval/gate.py+++ b/src/soup_cli/eval/gate.py@@ -95,7 +95,15 @@ class GateTask(BaseModel):# Allowlist of schemes — SSRF hardening consistent with the project.parsed = urlparse(value)- if parsed.scheme in ("ollama","https"):+ if parsed.scheme == "ollama":+ return value++ if parsed.scheme == "https":+ # A private IP literal is refused when the suite is parsed, so a+ # suite file cannot name one any more than --judge-model can.+ from soup_cli.utils.net_guard import refuse_private_ip_literal++ refuse_private_ip_literal(parsed.hostname, label="judge_model URL")return valueif (parsed.scheme == "http" and parsed.hostname in {"localhost", "127.0.0.1"}):diff --git a/src/soup_cli/eval/judge.py b/src/soup_cli/eval/judge.pyindex 5d277185..13d07d5e 100644--- a/src/soup_cli/eval/judge.py+++ b/src/soup_cli/eval/judge.py@@ -171,10 +171,17 @@ def load_rubric(path: Path) -> dict:def validate_judge_api_base(api_base: Optional[str]) -> None:- """SSRF protection for judge API base URL."""+ """SSRF protection for judge API base URL.++ ``JudgeEvaluator`` calls this when it is constructed, so every judge it+ builds is checked, whether the URL came from ``--api-base`` or from a+ config file.+ """if api_base is None:return+ from soup_cli.utils.net_guard import refuse_private_ip_literal+parsed = urlparse(api_base)if parsed.scheme not in ("http", "https"):raise ValueError(@@ -190,6 +197,8 @@ def validate_judge_api_base(api_base: Optional[str]) -> None:"HTTP is only allowed for localhost. ""Use HTTPS for remote URLs.")+ # ...and no private / link-local / reserved IP literal on either scheme.+ refuse_private_ip_literal(parsed.hostname, label="judge URL")def _build_judge_prompt(diff --git a/src/soup_cli/ui/app.py b/src/soup_cli/ui/app.pyindex a8af3158..41ecb9b9 100644--- a/src/soup_cli/ui/app.py+++ b/src/soup_cli/ui/app.py@@ -1051,17 +1051,26 @@ def create_app(host: str = "127.0.0.1", port: int = 7860):from fastapi.responses import StreamingResponse+ from soup_cli.utils.net_guard import refuse_private_ip_literal+# Validate messagesif not req.messages:raise HTTPException(status_code=400, detail="messages cannot be empty")- # SSRF protection: localhost-only HTTP, HTTPS for remote- parsed = urlparse(req.endpoint)+ # SSRF protection: localhost-only HTTP, HTTPS for remote, and no+ # private / link-local / reserved IP literal on either scheme.+ # 0.0.0.0 is the bind-any wildcard, not a loopback address.+ try:+ parsed = urlparse(req.endpoint)+ except ValueError:+ # e.g. an unbalanced or non-IPv6 bracketed host: a bad request,+ # not a server error.+ raise HTTPException(status_code=400, detail="endpoint is not a valid URL") from Noneif parsed.scheme == "http":import ipaddress as _ipaddrhost = parsed.hostname or ""- is_local = host in ("localhost", "0.0.0.0")+ is_local = host == "localhost"if not is_local:try:addr = _ipaddr.ip_address(host)@@ -1078,6 +1087,12 @@ def create_app(host: str = "127.0.0.1", port: int = 7860):status_code=400,detail="Only HTTP (localhost) or HTTPS endpoints allowed",)+ try:+ refuse_private_ip_literal(parsed.hostname, label="endpoint")+ except ValueError as exc:+ # The message is fixed text (the label is a constant); the+ # endpoint itself is never echoed back.+ raise HTTPException(status_code=400, detail=str(exc)) from None# Validate boundsif req.max_tokens > 16384:diff --git a/src/soup_cli/utils/net_guard.py b/src/soup_cli/utils/net_guard.pyindex 5df62f96..6ecf79dd 100644--- a/src/soup_cli/utils/net_guard.py+++ b/src/soup_cli/utils/net_guard.py@@ -46,6 +46,33 @@ import ipaddressLOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})+def _ascii_spellings(host: str) -> list[str]:+ """``host`` plus the ASCII forms an HTTP client may turn it into.++ A client IDNA-encodes a non-ASCII host before it resolves it: urllib and+ :mod:`socket` through the stdlib codec (IDNA 2003, whose nameprep step+ NFKC-folds and drops characters such as the soft hyphen), httpx through the+ ``idna`` package (IDNA 2008). Both treat U+3002, U+FF0E and U+FF61 as label+ separators, so text that is not an IP literal as written -- ``10.0.0.1``+ with U+3002 IDEOGRAPHIC FULL STOP in place of each dot, for instance -- can+ be one once encoded. A form that fails to encode is skipped.+ """+ if host.isascii():+ return [host]+ spellings = [host]+ try:+ spellings.append(host.encode("idna").decode("ascii"))+ except UnicodeError:+ pass+ try:+ import idna # noqa: PLC0415 — the encoder httpx uses; optional here++ spellings.append(idna.encode(host.lower()).decode("ascii"))+ except (ImportError, UnicodeError): # idna.IDNAError is a UnicodeError+ pass+ return spellings++def parse_ip_literal(host: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None:"""Parse ``host`` as an IP literal, or ``None`` if it isn't one.@@ -55,7 +82,22 @@ def parse_ip_literal(host: str) -> ipaddress.IPv4Address | ipaddress.IPv6Addresslibrary :func:`socket.inet_aton`. The latter is a pure in-processstring parser — no DNS lookup is performed. A hostname (``"localhost"``,``"evil.example.com"``) returns ``None`` rather than being resolved.++ A non-ASCII host is also read in the ASCII forms a client would connect to+ (see :func:`_ascii_spellings`), and the first form that is an IP literal is+ returned, so ``10.0.0.1`` written with ideographic full stops parses as+ ``10.0.0.1``."""+ for spelling in _ascii_spellings(host):+ addr = _parse_ascii_ip_literal(spelling)+ if addr is not None:+ return addr+ return None+++def _parse_ascii_ip_literal(+ host: str,+) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None:import socket # noqa: PLC0415 — lazy import (stdlib, negligible cost)clean_host = host.rstrip(".")@@ -77,6 +119,13 @@ def is_private_or_link_local(host: str) -> bool:multicast / unspecified IP — the union of every guard's policy in thisrepo, since consolidating stops being safe the moment a caller'spredicate is quietly narrower than the shared one it now uses.++ Also any address ``ipaddress`` does not consider globally reachable+ (``not is_global``) — that adds RFC 6598 shared address space,+ ``100.64.0.0/10``, which is neither ``is_private`` nor ``is_global`` —+ and the deprecated IPv6 site-local block ``fec0::/10``, which+ ``ipaddress`` still reports as global. ``is_reserved`` stays: NAT64+ ``64:ff9b::/96`` IS ``is_global``."""addr = parse_ip_literal(host)if addr is None:@@ -91,4 +140,36 @@ def is_private_or_link_local(host: str) -> bool:or addr.is_unspecifiedor addr.is_reservedor addr.is_multicast+ or not addr.is_global+ or getattr(addr, "is_site_local", False))+++def refuse_private_ip_literal(host: str | None, *, label: str) -> None:+ """Raise ``ValueError`` if an outbound endpoint's host is a non-public IP.++ ``host`` is a URL's ``hostname``. It is refused when it is an IP literal, in+ any spelling :func:`parse_ip_literal` accepts (IPv4-mapped IPv6 included),+ that :func:`is_private_or_link_local` classifies as non-public, on every+ scheme. Loopback stays allowed, because a server on the same machine+ (Ollama, vLLM, ``soup serve``) is a supported target. A hostname passes+ unchanged and is NOT resolved, so this narrows which addresses a URL can+ name directly; it does not make internal services unreachable by name. An+ empty or missing host passes too: the caller's scheme check owns that case.+ ``label`` names the setting in the message.+ """+ clean = (host or "").strip().lower().rstrip(".")+ if clean.startswith("[") and clean.endswith("]"):+ clean = clean[1:-1]+ if not clean or clean in LOOPBACK_HOSTS:+ return+ addr = parse_ip_literal(clean)+ if addr is None:+ return+ mapped = getattr(addr, "ipv4_mapped", None)+ if (mapped if mapped is not None else addr).is_loopback:+ return+ if is_private_or_link_local(clean):+ raise ValueError(+ f"{label}: private/link-local/reserved IP hosts are not allowed (SSRF protection)"+ )diff --git a/tests/test_issue616_net_guard_is_shared.py b/tests/test_issue616_net_guard_is_shared.pyindex 6e8ef1ed..f2479b91 100644--- a/tests/test_issue616_net_guard_is_shared.py+++ b/tests/test_issue616_net_guard_is_shared.py@@ -27,6 +27,8 @@ from __future__ import annotationsimport astfrom pathlib import Path+import pytest+_UTILS_DIR = Path(__file__).resolve().parent.parent / "src" / "soup_cli" / "utils"_SRC_ROOT = _UTILS_DIR.parent_HOME = _UTILS_DIR / "net_guard.py"@@ -206,3 +208,229 @@ class TestMutationsThatUsedToSurvive:rogue.write_text('LOOPBACK_HOSTS: frozenset = frozenset({"localhost"})\n')found = _builders(rogue)assert found == ["LOOPBACK_HOSTS"]+++# ---------------------------------------------------------------------------+# Outbound endpoint checks refuse non-public IP literals through ONE helper.+# ---------------------------------------------------------------------------++_REFUSAL = "refuse_private_ip_literal"++# Every check in front of an outbound request whose URL comes from a flag, a+# config file or a request body. Each must call the shared refusal, so deleting+# the call fails here as well as in tests/test_outbound_endpoint_ip_literals.py.+_OUTBOUND_GATES = (+ ("data/providers/vllm.py", "validate_vllm_url"),+ ("commands/generate.py", "_generate_openai"),+ ("commands/generate.py", "_generate_server"),+ ("eval/judge.py", "validate_judge_api_base"),+ ("eval/gate.py", "_valid_judge_url"),+ ("commands/ship.py", "_validate_judge_model_url"),+ ("ui/app.py", "chat_send"),+ ("config/schema.py", "_validate_online_dpo_judge_field"),+)++# Every OTHER function that reads a URL's hostname next to a loopback allowlist+# -- the shape every copy of the http-only check had -- and does not call the+# shared refusal, each with the reason. A NEW function of that shape fails+# test_every_hostname_check_is_accounted_for until it calls the refusal or is+# declared here. Calling is_private_or_link_local does not qualify a function+# on its own: a call made only on the plain-HTTP branch looks the same to an+# AST walk, so each entry is a statement that someone read the function.+_HOSTNAME_CHECKS_WITHOUT_THE_REFUSAL = {+ ("data/providers/ollama.py", "validate_ollama_url"): (+ "loopback only: any other host is refused outright"+ ),+ ("eval/gate.py", "_parse_judge_url"): (+ "a classifier; JudgeEvaluator enforces the policy via validate_judge_api_base"+ ),+ ("utils/loop_stages.py", "_endpoint_is_local"): (+ "the deploy-canary policy REQUIRES a local or LAN endpoint, on purpose"+ ),+ ("utils/qr_url.py", "build_phone_url"): "builds a URL to display; makes no request",+ ("utils/webhooks.py", "validate_webhook_url"): (+ "applies is_private_or_link_local itself, on every scheme"+ ),+ ("utils/tracing.py", "validate_otlp_endpoint"): (+ "applies is_private_or_link_local itself, on every scheme"+ ),+ ("utils/trackers.py", "_telemetry_endpoint_is_safe"): (+ "https only; applies is_private_or_link_local itself, before and after DNS"+ ),+ ("utils/hf.py", "resolve_endpoint"): (+ "HF_ENDPOINT is read only from the operator's own environment"+ ),+ ("utils/hubs.py", "validate_hub_endpoint"): (+ "hub endpoints are read only from the operator's own environment"+ ),+}+++def _functions(path: Path) -> list[ast.FunctionDef | ast.AsyncFunctionDef]:+ return [+ node+ for node in ast.walk(_parse(path))+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))+ ]+++def _own_nodes(func: ast.AST) -> list[ast.AST]:+ """Nodes of ``func``'s own body, excluding nested defs, classes and lambdas."""+ found: list[ast.AST] = []+ stack = list(getattr(func, "body", []))+ while stack:+ node = stack.pop()+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):+ continue+ found.append(node)+ stack.extend(ast.iter_child_nodes(node))+ return found+++def _called_names(func: ast.AST) -> set[str]:+ names: set[str] = set()+ for node in _own_nodes(func):+ if isinstance(node, ast.Call):+ if isinstance(node.func, ast.Name):+ names.add(node.func.id)+ elif isinstance(node.func, ast.Attribute):+ names.add(node.func.attr)+ return names+++def _is_hostname_check(func: ast.AST) -> bool:+ """Reads ``<url>.hostname`` and holds a loopback allowlist in its own body."""+ nodes = _own_nodes(func)+ reads_hostname = any(isinstance(n, ast.Attribute) and n.attr == "hostname" for n in nodes)+ has_allowlist = any(+ (isinstance(n, ast.Constant) and n.value == "localhost")+ or (isinstance(n, ast.Name) and _normalised(n.id).endswith(_normalised(_SET_SUFFIX)))+ for n in nodes+ )+ return reads_hostname and has_allowlist+++def _unguarded_hostname_checks(path: Path) -> list[str]:+ """THE discovery matcher, shared by the real-tree scan and its self-tests."""+ return [+ func.name+ for func in _functions(path)+ if _is_hostname_check(func) and _REFUSAL not in _called_names(func)+ ]+++def _imports_the_refusal(path: Path) -> bool:+ return any(+ isinstance(node, ast.ImportFrom)+ and node.module == "soup_cli.utils.net_guard"+ and any(alias.name == _REFUSAL for alias in node.names)+ for node in ast.walk(_parse(path))+ )+++class TestOutboundGatesShareTheRefusal:+ def test_the_refusal_is_defined_only_in_the_shared_module(self) -> None:+ definers = [+ f"{path.relative_to(_SRC_ROOT).as_posix()}::{func.name}"+ for path in sorted(_SRC_ROOT.rglob("*.py"))+ for func in _functions(path)+ if func.name.endswith(_REFUSAL)+ ]+ assert definers == [f"{_HOME.relative_to(_SRC_ROOT).as_posix()}::{_REFUSAL}"]++ @pytest.mark.parametrize(("relpath", "func_name"), _OUTBOUND_GATES)+ def test_each_gate_calls_it(self, relpath: str, func_name: str) -> None:+ path = _SRC_ROOT / relpath+ funcs = [func for func in _functions(path) if func.name == func_name]+ assert len(funcs) == 1, f"{relpath}::{func_name} not found exactly once"+ assert _REFUSAL in _called_names(funcs[0]), (+ f"{relpath}::{func_name} must call net_guard.{_REFUSAL}"+ )+ assert _imports_the_refusal(path), f"{relpath} must import {_REFUSAL} from net_guard"++ def test_every_hostname_check_is_accounted_for(self) -> None:+ unaccounted = [+ f"{rel}::{name}"+ for path in sorted(_SRC_ROOT.rglob("*.py"))+ for rel in [path.relative_to(_SRC_ROOT).as_posix()]+ for name in _unguarded_hostname_checks(path)+ if (rel, name) not in _HOSTNAME_CHECKS_WITHOUT_THE_REFUSAL+ ]+ assert unaccounted == [], (+ "these read a URL's hostname next to a loopback allowlist without calling "+ f"net_guard.{_REFUSAL}; call it, or declare them in "+ f"_HOSTNAME_CHECKS_WITHOUT_THE_REFUSAL with the reason: {unaccounted}"+ )++ @pytest.mark.parametrize(+ ("relpath", "func_name"), sorted(_HOSTNAME_CHECKS_WITHOUT_THE_REFUSAL)+ )+ def test_every_declared_exemption_is_still_needed(+ self, relpath: str, func_name: str+ ) -> None:+ """A renamed, rewritten or since-fixed entry must leave the table, not rot in it."""+ funcs = [func for func in _functions(_SRC_ROOT / relpath) if func.name == func_name]+ assert len(funcs) == 1 and _is_hostname_check(funcs[0]), (+ f"{relpath}::{func_name} is no longer a hostname check; drop its entry"+ )+ assert _REFUSAL not in _called_names(funcs[0]), (+ f"{relpath}::{func_name} calls {_REFUSAL} now; drop its entry"+ )+++class TestTheDiscoveryCatchesANewCopy:+ """Demonstrates, not just asserts: both spellings of the old check are caught."""++ _BODY = (+ "from urllib.parse import urlparse\n"+ "{imports}"+ "\n\ndef validate_new_url(url):\n"+ " parsed = urlparse(url)\n"+ " if parsed.hostname not in {allowlist} and parsed.scheme != 'https':\n"+ " raise ValueError('HTTPS for remote')\n"+ "{extra}"+ )++ def _write(self, tmp_path: Path, **parts: str) -> Path:+ values = {"imports": "", "allowlist": "('localhost', '127.0.0.1')", "extra": ""}+ values.update(parts)+ rogue = tmp_path / "rogue_gate.py"+ rogue.write_text(self._BODY.format(**values), encoding="utf-8")+ return rogue++ def test_a_literal_allowlist_copy_is_caught(self, tmp_path: Path) -> None:+ assert _unguarded_hostname_checks(self._write(tmp_path)) == ["validate_new_url"]++ def test_a_shared_set_copy_is_caught(self, tmp_path: Path) -> None:+ rogue = self._write(+ tmp_path,+ imports="from soup_cli.utils.net_guard import LOOPBACK_HOSTS\n",+ allowlist="LOOPBACK_HOSTS",+ )+ assert _unguarded_hostname_checks(rogue) == ["validate_new_url"]++ def test_a_copy_that_calls_the_refusal_is_not(self, tmp_path: Path) -> None:+ rogue = self._write(+ tmp_path,+ imports="from soup_cli.utils.net_guard import refuse_private_ip_literal\n",+ extra=" refuse_private_ip_literal(parsed.hostname, label='x')\n",+ )+ assert _unguarded_hostname_checks(rogue) == []++ def test_a_predicate_call_on_the_http_branch_alone_is_still_caught(+ self, tmp_path: Path+ ) -> None:+ """Why a call to the predicate does not exempt a function by itself."""+ rogue = tmp_path / "rogue_http_branch.py"+ rogue.write_text(+ "from urllib.parse import urlparse\n"+ "from soup_cli.utils.net_guard import LOOPBACK_HOSTS, is_private_or_link_local\n"+ "\n\ndef validate_new_url(url):\n"+ " parsed = urlparse(url)\n"+ " if parsed.scheme == 'http' and parsed.hostname not in LOOPBACK_HOSTS:\n"+ " if is_private_or_link_local(parsed.hostname):\n"+ " raise ValueError('private hosts require HTTPS')\n"+ " raise ValueError('HTTPS for remote')\n",+ encoding="utf-8",+ )+ assert _unguarded_hostname_checks(rogue) == ["validate_new_url"]diff --git a/tests/test_outbound_endpoint_ip_literals.py b/tests/test_outbound_endpoint_ip_literals.pynew file mode 100644index 00000000..ee185077--- /dev/null+++ b/tests/test_outbound_endpoint_ip_literals.py@@ -0,0 +1,734 @@+"""Outbound endpoint validators refuse non-public IP literals on every scheme.++Each validator below sits in front of an outbound HTTP request whose URL comes+from a flag, a config file or a request body. They already refused plain HTTP+to a non-loopback host. They must also refuse a URL whose host is an IP literal+in a non-public range, in every spelling ``net_guard.parse_ip_literal`` accepts+(abbreviated, decimal, hex and octal IPv4, IPv4-mapped IPv6), while loopback+literals and hostnames keep working. Hostnames are not resolved, here or+anywhere else in the repo, so this narrows what a URL can name directly; it+does not make an internal service unreachable by name.++No test in this file touches the network: ``httpx.post`` and ``httpx.stream``+are replaced by a recorder that raises instead of connecting. Every refused+case asserts the recorder was never reached, and every allowed case asserts it+WAS reached, so the first assertion cannot pass vacuously.+"""++from __future__ import annotations++import io+import re+from types import SimpleNamespace++import pytest++_REFUSED = "private/link-local/reserved IP hosts are not allowed"++# The host part of the URL, as written in its authority.+_NON_PUBLIC_HOSTS = [+ pytest.param("10.0.0.1", id="10/8"),+ pytest.param("172.16.0.1", id="172.16/12"),+ pytest.param("192.168.1.10:8443", id="192.168/16-with-port"),+ pytest.param("169.254.169.254", id="link-local-v4"),+ pytest.param("[fd00::1]", id="unique-local-v6"),+ pytest.param("[fe80::1]", id="link-local-v6"),+ pytest.param("[::ffff:10.0.0.1]", id="v4-mapped-v6"),+ pytest.param("[64:ff9b::a9fe:a9fe]", id="nat64-v6"),+ pytest.param("10.1", id="abbreviated-v4"),+ pytest.param("167772161", id="decimal-v4"),+ pytest.param("0x0a000001", id="hex-v4"),+ pytest.param("012.0.0.1", id="octal-v4"),+ pytest.param("169.254.169.254.", id="trailing-dot"),+ pytest.param("0.0.0.0", id="unspecified-v4"),+ pytest.param("[::]", id="unspecified-v6"),+ pytest.param("224.0.0.1", id="multicast-v4"),+ # RFC 6598 shared address space: neither is_private nor is_global.+ pytest.param("100.64.0.1", id="shared-space"),+ pytest.param("100.127.255.254", id="shared-space-top"),+ pytest.param("[::ffff:100.64.0.1]", id="shared-space-v4-mapped"),+ # Deprecated IPv6 site-local, which ipaddress still reports as global.+ pytest.param("[fec0::1]", id="site-local-v6"),+ # A client IDNA-encodes a non-ASCII host before it connects, folding these+ # separators and digits to ASCII: httpx dials 10.0.0.1 for the first three.+ pytest.param("10\u30020\u30020\u30021", id="ideographic-full-stops"),+ pytest.param("10\uff0e0\uff0e0\uff0e1", id="fullwidth-full-stops"),+ pytest.param("10\uff610\uff610\uff611", id="halfwidth-ideographic-full-stops"),+ pytest.param("169\uff0e254\uff0e169\uff0e254", id="link-local-fullwidth-stops"),+ pytest.param("0xa\u30020\u30020\u30021", id="hex-with-ideographic-stops"),+ pytest.param("10\ufe520\ufe520\ufe521", id="small-full-stops"),+ pytest.param("\uff11\uff10.0.0.1", id="fullwidth-digits"),+ pytest.param("1\u00ad0.0.0.1", id="soft-hyphen"),+]++# Loopback is the one non-public range these endpoints exist to reach.+_ALLOWED_HOSTS = [+ pytest.param("api.example.com", id="hostname"),+ pytest.param("8.8.8.8", id="public-v4"),+ pytest.param("100.63.255.255", id="just-below-shared-space"),+ pytest.param("100.128.0.1", id="just-above-shared-space"),+ pytest.param("127.0.0.1:8443", id="loopback-v4"),+ pytest.param("127.0.0.5", id="loopback-range"),+ pytest.param("127.1", id="abbreviated-loopback"),+ pytest.param("[::1]:8443", id="loopback-v6"),+ pytest.param("[::ffff:127.0.0.1]", id="v4-mapped-loopback"),+ pytest.param("127\u30020\u30020\u30021", id="loopback-ideographic-stops"),+ pytest.param("8\uff0e8\uff0e8\uff0e8", id="public-fullwidth-stops"),+ pytest.param("m\u00fcnchen.example", id="idn-hostname"),+]+++class _RequestAttemptedError(Exception):+ """Raised by the recorder in place of a request."""+++def sent(monkeypatch) -> list[tuple[str, dict]]:+ """``httpx.post`` / ``httpx.stream`` replaced by a recorder that never connects."""+ import httpx++ calls: list[tuple[str, dict]] = []++ def _post(url, *args, **kwargs):+ calls.append((str(url), dict(kwargs.get("headers") or {})))+ raise _RequestAttemptedError(str(url))++ def _stream(method, url, *args, **kwargs):+ calls.append((str(url), dict(kwargs.get("headers") or {})))+ raise _RequestAttemptedError(str(url))++ monkeypatch.setattr(httpx, "post", _post)+ monkeypatch.setattr(httpx, "stream", _stream)+ return calls++[email protected](autouse=True)+def _online_dpo_without_trl(monkeypatch):+ """Keep the online-DPO judge path off trl (its version probe imports it)."""+ import soup_cli.trainer.online_dpo as od++ monkeypatch.setattr(od, "_trl_has_judges", lambda: False)+ monkeypatch.setattr(od, "_ONLINE_DPO_JUDGE_OVERRIDE", None)+++# --- one adapter per gate; each takes the URL's scheme://authority ----------+++def _vllm_url(base: str) -> None:+ from soup_cli.data.providers.vllm import validate_vllm_url++ validate_vllm_url(base)+++def _vllm_generate(base: str) -> None:+ from soup_cli.data.providers.vllm import generate_vllm++ generate_vllm(+ prompt="p", count=1, fmt="alpaca", model_name="m", base_url=base,+ temperature=0.0, generation_prompt="g",+ )+++def _generate_openai(base: str) -> None:+ from soup_cli.commands.generate import _generate_openai as run++ run(+ prompt="p", count=1, fmt="alpaca", model_name="m", api_key="sk-test",+ api_base=base, temperature=0.0, seed_examples=[], generation_prompt="g",+ )+++def _generate_server(base: str) -> None:+ from soup_cli.commands.generate import _generate_server as run++ run(+ prompt="p", count=1, fmt="alpaca", model_name="m", api_base=base,+ temperature=0.0, seed_examples=[], generation_prompt="g",+ )+++def _judge_api_base(base: str) -> None:+ from soup_cli.eval.judge import validate_judge_api_base++ validate_judge_api_base(base)+++def _judge_evaluator(base: str) -> None:+ from soup_cli.eval.judge import JudgeEvaluator++ JudgeEvaluator(provider="server", model="m", api_base=base)._call_llm("p")+++def _gate_suite_task(base: str) -> None:+ from soup_cli.eval.gate import GateTask++ GateTask(+ type="judge", name="t", threshold=0.5, prompts="p.jsonl", judge_model=f"{base}/m"+ )+++def _online_dpo_field(base: str) -> None:+ from soup_cli.config.schema import TrainingConfig++ TrainingConfig(online_dpo_judge=f"{base}/m")+++def _online_dpo_trainer(base: str) -> None:+ """Trainer setup, reached with a config the schema never validated."""+ import soup_cli.trainer.online_dpo as od++ wrapper = object.__new__(od.OnlineDPOTrainerWrapper)+ wrapper._build_judge_or_reward(+ SimpleNamespace(online_dpo_judge=f"{base}/m", reward_model=None)+ )+++_VALIDATORS = [+ pytest.param(_vllm_url, id="vllm-url"),+ pytest.param(_vllm_generate, id="vllm-generate"),+ pytest.param(_generate_openai, id="generate-openai"),+ pytest.param(_generate_server, id="generate-server"),+ pytest.param(_judge_api_base, id="judge-api-base"),+ pytest.param(_judge_evaluator, id="judge-evaluator"),+ pytest.param(_gate_suite_task, id="gate-suite-judge-model"),+ pytest.param(_online_dpo_field, id="online-dpo-judge-field"),+ pytest.param(_online_dpo_trainer, id="online-dpo-trainer"),+]+# The adapters that go on to make a request once their gate passes.+_SINKS = frozenset({_vllm_generate, _generate_openai, _generate_server, _judge_evaluator})++# The setting each gate names in its refusal.+_LABELS = {+ _vllm_url: "vLLM URL",+ _vllm_generate: "vLLM URL",+ _generate_openai: "api_base",+ _generate_server: "api_base",+ _judge_api_base: "judge URL",+ _judge_evaluator: "judge URL",+ _gate_suite_task: "judge_model URL",+ _online_dpo_field: "online_dpo_judge",+ _online_dpo_trainer: "judge URL",+}++_ANSI = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")+++def _plain(text: str) -> str:+ """CLI output without colour codes and with Rich's line wrapping undone."""+ return " ".join(_ANSI.sub("", text).split())+++class TestNonPublicLiteralsAreRefused:+ @pytest.mark.parametrize("host", _NON_PUBLIC_HOSTS)+ @pytest.mark.parametrize("validator", _VALIDATORS)+ def test_refused_before_any_request(self, validator, host, sent):+ with pytest.raises(ValueError, match=re.escape(_REFUSED)):+ validator(f"https://{host}")+ assert sent == [], f"a request was attempted for {host!r}: {sent}"++ @pytest.mark.parametrize("validator", _VALIDATORS)+ def test_refusal_names_the_setting(self, validator, sent):+ with pytest.raises(ValueError) as info:+ validator("https://10.0.0.1")+ assert f"{_LABELS[validator]}: {_REFUSED}" in str(info.value)+ assert sent == []++ @pytest.mark.parametrize("validator", _VALIDATORS)+ def test_unspecified_address_is_not_local_over_http(self, validator, sent):+ with pytest.raises(ValueError):+ validator("http://0.0.0.0:8000")+ assert sent == []+++class TestPublicAndLoopbackStillPass:+ @pytest.mark.parametrize("host", _ALLOWED_HOSTS)+ @pytest.mark.parametrize("validator", _VALIDATORS)+ def test_allowed(self, validator, host, sent):+ base = f"https://{host}"+ try:+ validator(base)+ except _RequestAttemptedError:+ pass+ urls = [url for url, _headers in sent]+ if validator in _SINKS:+ assert len(urls) == 1 and urls[0].startswith(base + "/"), urls+ else:+ assert urls == []++ @pytest.mark.parametrize("base", ["http://localhost:8000", "http://127.0.0.1:8000"])+ @pytest.mark.parametrize("validator", _VALIDATORS)+ def test_loopback_over_http(self, validator, base, sent):+ try:+ validator(base)+ except _RequestAttemptedError:+ pass+ assert len(sent) == (1 if validator in _SINKS else 0)++ @pytest.mark.parametrize(+ "validator",+ [+ _vllm_url, _vllm_generate, _generate_openai, _generate_server, _judge_api_base,+ _judge_evaluator, _online_dpo_field,+ ],+ )+ def test_ipv6_loopback_over_http(self, validator, sent):+ """``::1`` is loopback for these gates. The eval-gate suite, ``soup ship`` and+ the online-DPO trainer accept only ``localhost`` and ``127.0.0.1`` over http."""+ try:+ validator("http://[::1]:8000")+ except _RequestAttemptedError:+ pass+ assert len(sent) == (1 if validator in _SINKS else 0)++ def test_default_openai_base_still_carries_the_key(self, sent):+ from soup_cli.commands.generate import _generate_openai as run++ with pytest.raises(_RequestAttemptedError):+ run(+ prompt="p", count=1, fmt="alpaca", model_name="m", api_key="sk-test",+ api_base=None, temperature=0.0, seed_examples=[], generation_prompt="g",+ )+ [(url, headers)] = sent+ assert url == "https://api.openai.com/v1/chat/completions"+ assert headers.get("Authorization") == "Bearer sk-test"+++class TestRemoteHttpKeepsItsMessage:+ """The scheme check still runs first, so the existing message is unchanged."""++ @pytest.mark.parametrize(+ ("validator", "message"),+ [+ (_vllm_url, "HTTPS for remote"),+ (_generate_openai, "HTTPS for remote"),+ (_generate_server, "HTTPS for remote"),+ (_judge_api_base, "Use HTTPS for remote"),+ (_gate_suite_task, "disallowed scheme"),+ ],+ )+ def test_remote_http(self, validator, message, sent):+ with pytest.raises(ValueError, match=message):+ validator("http://10.0.0.1:8000")+ assert sent == []++ @pytest.mark.parametrize(+ ("validator", "message"),+ [+ (_vllm_url, "HTTPS for remote"),+ (_generate_openai, "HTTPS for remote"),+ (_generate_server, "HTTPS for remote"),+ (_judge_api_base, "Use HTTPS for remote"),+ ],+ )+ def test_localhost_lookalike_is_remote_over_http(self, validator, message, sent):+ with pytest.raises(ValueError, match=message):+ validator("http://localhost.attacker.example:8000")+ assert sent == []++ @pytest.mark.parametrize("validator", [_generate_openai, _generate_server])+ def test_unspecified_address_is_remote_to_the_scheme_check(self, validator, sent):+ """0.0.0.0 is the bind-any wildcard; these two used to count it as loopback."""+ with pytest.raises(ValueError, match="HTTPS for remote"):+ validator("http://0.0.0.0:8000")+ assert sent == []+++class TestShipJudgeModelFlag:+ @pytest.fixture+ def out(self, monkeypatch) -> io.StringIO:+ from rich.console import Console++ import soup_cli.commands.ship as ship++ buf = io.StringIO()+ monkeypatch.setattr(ship, "console", Console(file=buf, width=400, color_system=None))+ return buf++ @pytest.mark.parametrize("host", _NON_PUBLIC_HOSTS)+ def test_refused_as_a_usage_error(self, host, out):+ import click++ from soup_cli.commands.ship import _validate_judge_model_url++ with pytest.raises(click.exceptions.Exit) as info:+ _validate_judge_model_url(f"https://{host}/m")+ assert info.value.exit_code == 3+ assert f"--judge-model: {_REFUSED}" in out.getvalue()++ @pytest.mark.parametrize("host", _ALLOWED_HOSTS)+ def test_allowed(self, host, out):+ from soup_cli.commands.ship import _validate_judge_model_url++ _validate_judge_model_url(f"https://{host}/m")+ assert out.getvalue() == ""++ def test_refused_before_any_model_loads(self, monkeypatch, tmp_path):+ """Through the real command: the judge URL is a usage error before the base+ and tuned models are built, not after."""+ import json++ from typer.testing import CliRunner++ from soup_cli.commands import ship as ship_cmd+ from soup_cli.utils import live_eval++ loads: list[str] = []++ def _factory(model_id, **_kwargs):+ loads.append(str(model_id))+ return lambda prompt: ""++ monkeypatch.setattr(live_eval, "make_generator", _factory)+ monkeypatch.chdir(tmp_path)+ row = {"prompt": "p", "expected": "x", "scoring": "contains"}+ (tmp_path / "tasks.jsonl").write_text(json.dumps(row) + "\n", encoding="utf-8")+ res = CliRunner().invoke(+ ship_cmd.app,+ [+ "--base", "fake-base", "--adapter", "fake-adapter",+ "--task-eval", "tasks.jsonl", "--task-mode", "judge_score",+ "--judge-model", "https://10.0.0.1/m",+ ],+ )+ assert res.exit_code == 3, (res.output, repr(res.exception))+ assert f"--judge-model: {_REFUSED}" in _plain(res.output)+ assert loads == []+++class TestChatProxy:+ @pytest.fixture+ def post(self, sent):+ pytest.importorskip("fastapi")+ from fastapi.testclient import TestClient++ from soup_cli.ui.app import create_app, get_auth_token++ client = TestClient(create_app())+ headers = {"Authorization": f"Bearer {get_auth_token()}"}++ def _post(endpoint: str):+ body = {"messages": [{"role": "user", "content": "hi"}], "endpoint": endpoint}+ return client.post("/api/chat/send", json=body, headers=headers)++ return _post++ @pytest.mark.parametrize("host", _NON_PUBLIC_HOSTS)+ def test_refused_with_400_before_dispatch(self, host, post, sent):+ resp = post(f"https://{host}")+ assert resp.status_code == 400, resp.text+ detail = resp.json()["detail"]+ assert detail == f"endpoint: {_REFUSED} (SSRF protection)"+ assert sent == []++ @pytest.mark.parametrize("host", _ALLOWED_HOSTS)+ def test_allowed_endpoint_is_dispatched(self, host, post, sent):+ resp = post(f"https://{host}")+ assert resp.status_code == 200, resp.text+ assert [url for url, _ in sent] == [f"https://{host}/v1/chat/completions"]++ def test_unspecified_address_over_http_is_refused(self, post, sent):+ """0.0.0.0 is the bind-any wildcard; the scheme check used to count it as local."""+ resp = post("http://0.0.0.0:8000")+ assert resp.status_code == 400, resp.text+ assert resp.json()["detail"] == "HTTP only allowed for localhost endpoints"+ assert sent == []++ def test_loopback_range_over_http_is_dispatched(self, post, sent):+ resp = post("http://127.0.0.5:8000")+ assert resp.status_code == 200, resp.text+ assert [url for url, _ in sent] == ["http://127.0.0.5:8000/v1/chat/completions"]++ @pytest.mark.parametrize(+ "base", ["http://localhost:8000", "http://127.0.0.1:8000", "http://[::1]:8000"]+ )+ def test_loopback_spellings_over_http_are_dispatched(self, base, post, sent):+ resp = post(base)+ assert resp.status_code == 200, resp.text+ assert [url for url, _ in sent] == [f"{base}/v1/chat/completions"]++ def test_localhost_lookalike_over_http_is_refused(self, post, sent):+ resp = post("http://localhost.attacker.example:8000")+ assert resp.status_code == 400, resp.text+ assert resp.json()["detail"] == "HTTP only allowed for localhost endpoints"+ assert sent == []++ @pytest.mark.parametrize("endpoint", ["https://[fd00::1/m", "https://[10.0.0.1]/m"])+ def test_malformed_endpoint_is_a_bad_request(self, endpoint, post, sent):+ """An unbalanced or non-IPv6 bracketed host is the client's error (400), not+ the server's (500)."""+ resp = post(endpoint)+ assert resp.status_code == 400, resp.text+ assert sent == []+++_ODPO_YAML = (+ "base: sshleifer/tiny-gpt2\ntask: online_dpo\ndata:\n train: x.jsonl\n"+ 'training:\n online_dpo_judge: "{judge}"\n'+)+++class TestConfigLoad:+ """A shared soup.yaml is refused at load, before any model download."""++ @pytest.mark.parametrize(+ "judge",+ [+ "https://10.0.0.1/m",+ "https://[fd00::1]:8443/m",+ "https://167772161/m",+ "http://169.254.169.254/m",+ ],+ )+ def test_non_public_judge_literal_is_refused(self, judge):+ from soup_cli.config.loader import load_config_from_string++ with pytest.raises(ValueError) as info:+ load_config_from_string(_ODPO_YAML.format(judge=judge))+ assert "online_dpo_judge" in str(info.value)+ assert _REFUSED in str(info.value)++ @pytest.mark.parametrize(+ "judge",+ [+ "https://judge.example.com/m",+ "https://127.0.0.1:8443/m",+ "http://localhost:8000/m",+ "ollama://llama3.1",+ ],+ )+ def test_other_judges_still_load(self, judge):+ from soup_cli.config.loader import load_config_from_string++ cfg = load_config_from_string(_ODPO_YAML.format(judge=judge))+ assert cfg.training.online_dpo_judge == judge++ def test_an_unparsable_judge_url_names_the_setting(self):+ from soup_cli.config.schema import TrainingConfig++ with pytest.raises(ValueError, match="online_dpo_judge is not a valid URL"):+ TrainingConfig(online_dpo_judge="https://[::1/m")+++class TestCliEntryPoints:+ """The flags reach the same checks through the real commands."""++ def test_data_generate_refuses_a_private_api_base(self, sent, tmp_path, monkeypatch):+ from typer.testing import CliRunner++ from soup_cli.cli import app++ monkeypatch.chdir(tmp_path)+ res = CliRunner().invoke(+ app,+ [+ "data", "generate", "--prompt", "x", "--provider", "server",+ "--api-base", "https://10.0.0.1/v1", "--count", "1", "--output", "out.jsonl",+ ],+ )+ assert res.exit_code == 1, (res.output, repr(res.exception))+ assert f"api_base: {_REFUSED}" in _plain(res.output)+ assert sent == []+ assert not (tmp_path / "out.jsonl").exists()++ def test_eval_judge_refuses_a_private_api_base(self, sent, tmp_path, monkeypatch):+ from typer.testing import CliRunner++ from soup_cli.cli import app++ monkeypatch.chdir(tmp_path)+ (tmp_path / "t.jsonl").write_text('{"prompt": "p", "response": "r"}\n', encoding="utf-8")+ res = CliRunner().invoke(+ app, ["eval", "judge", "--target", "t.jsonl", "--api-base", "https://10.0.0.1/v1"]+ )+ assert res.exit_code == 1, (res.output, repr(res.exception))+ assert f"judge URL: {_REFUSED}" in _plain(res.output)+ assert sent == []+++class TestTheSharedHelper:+ @pytest.mark.parametrize(+ "host",+ [+ None, "", "localhost", "localhost.", "127.0.0.1", "::1", "[::1]", "127.1",+ "2130706433", "::ffff:127.0.0.1", "api.example.com", "8.8.8.8",+ "2606:4700::1111",+ ],+ )+ def test_passes(self, host):+ from soup_cli.utils.net_guard import refuse_private_ip_literal++ refuse_private_ip_literal(host, label="x")++ @pytest.mark.parametrize(+ "host",+ [+ "10.0.0.1", " 10.0.0.1", "[fd00::1]", "FE80::1", "fe80::1%eth0", "169.254.169.254.",+ "0", "::",+ ],+ )+ def test_refuses_with_the_label_first(self, host):+ from soup_cli.utils.net_guard import refuse_private_ip_literal++ with pytest.raises(ValueError) as info:+ refuse_private_ip_literal(host, label="vLLM URL")+ assert str(info.value) == f"vLLM URL: {_REFUSED} (SSRF protection)"++ def test_mapped_loopback_does_not_depend_on_the_interpreter(self, monkeypatch):+ """Whether ``IPv6Address.is_loopback`` looks through an IPv4-mapped address+ depends on the interpreter's patch release, so the helper unwraps it+ itself. Simulate an interpreter that does not."""+ import ipaddress++ from soup_cli.utils.net_guard import refuse_private_ip_literal++ monkeypatch.setattr(+ ipaddress.IPv6Address, "is_loopback", property(lambda self: self._ip == 1)+ )+ assert not ipaddress.ip_address("::ffff:127.0.0.1").is_loopback+ refuse_private_ip_literal("::ffff:127.0.0.1", label="x")+ with pytest.raises(ValueError, match=re.escape(_REFUSED)):+ refuse_private_ip_literal("::ffff:10.0.0.1", label="x")++ @pytest.mark.parametrize(+ "host",+ ["\u00e9" * 64 + ".example", "\u00e9..example"],+ ids=["label-too-long", "empty-label"],+ )+ def test_a_non_ascii_host_that_does_not_encode_is_a_hostname(self, host):+ """No client can dial a host that does not IDNA-encode, and the check must not+ raise on one either: it is treated as a hostname."""+ from soup_cli.utils.net_guard import is_private_or_link_local, refuse_private_ip_literal++ refuse_private_ip_literal(host, label="x")+ assert is_private_or_link_local(host) is False+++class TestTheSharedPredicate:+ """The predicate also backs webhooks, OTLP, telemetry, ``soup ingest --pull``+ and the hub endpoints, so the two ranges it missed close for them too."""++ @pytest.mark.parametrize(+ "host",+ [+ "100.64.0.0", "100.100.100.200", "100.127.255.255", "::ffff:100.64.0.1",+ "fec0::1", "feff:ffff::1",+ ],+ )+ def test_non_public(self, host):+ from soup_cli.utils.net_guard import is_private_or_link_local++ assert is_private_or_link_local(host) is True++ @pytest.mark.parametrize(+ "host", ["100.63.255.255", "100.128.0.0", "8.8.8.8", "2606:4700::1111", "2001:4860::8888"]+ )+ def test_public(self, host):+ from soup_cli.utils.net_guard import is_private_or_link_local++ assert is_private_or_link_local(host) is False++ def test_webhook_url(self):+ from soup_cli.utils.webhooks import validate_webhook_url++ with pytest.raises(ValueError, match="private/link-local/reserved"):+ validate_webhook_url("https://100.64.0.1/hook")++ def test_otlp_endpoint(self):+ from soup_cli.utils.tracing import validate_otlp_endpoint++ with pytest.raises(ValueError, match="private"):+ validate_otlp_endpoint("https://100.64.0.1:4317")++ def test_telemetry_endpoint(self):+ from soup_cli.utils.trackers import _telemetry_endpoint_is_safe++ assert _telemetry_endpoint_is_safe("https://100.64.0.1/i/v0/e/") is False++ def test_ingest_pull_needs_the_private_host_opt_in(self):+ from soup_cli.utils.ingest_pull import _is_private++ assert _is_private("https://100.64.0.1") is True++ @pytest.mark.parametrize(+ "host", ["10\u30020\u30020\u30021", "\uff11\uff10.0.0.1", "1\u00ad0.0.0.1"]+ )+ def test_non_ascii_spellings_are_classified(self, host):+ from soup_cli.utils.net_guard import is_private_or_link_local++ assert is_private_or_link_local(host) is True++ @pytest.mark.parametrize("host", ["8\u30028\u30028\u30028", "m\u00fcnchen.example"])+ def test_non_ascii_public_hosts_stay_public(self, host):+ from soup_cli.utils.net_guard import is_private_or_link_local++ assert is_private_or_link_local(host) is False++ def test_webhook_url_with_ideographic_stops(self):+ from soup_cli.utils.webhooks import validate_webhook_url++ with pytest.raises(ValueError, match="private/link-local/reserved"):+ validate_webhook_url("https://10\u30020\u30020\u30021/hook")++ def test_otlp_endpoint_with_fullwidth_stops(self):+ from soup_cli.utils.tracing import validate_otlp_endpoint++ with pytest.raises(ValueError, match="private"):+ validate_otlp_endpoint("https://10\uff0e0\uff0e0\uff0e1:4317")++ def test_hub_endpoint_counts_shared_space_as_private(self):+ from soup_cli.utils.hubs import validate_hub_endpoint++ with pytest.raises(ValueError, match="private/link-local hosts require HTTPS"):+ validate_hub_endpoint("http://100.64.0.1", hub="modelscope")++ def test_hf_endpoint_counts_shared_space_as_private(self, monkeypatch):+ from soup_cli.utils import hf++ monkeypatch.setenv("HF_ENDPOINT", "http://100.64.0.1")+ with pytest.raises(ValueError, match="private/link-local hosts require HTTPS"):+ hf.resolve_endpoint()++ def test_ingest_pull_with_ideographic_stops(self):+ from soup_cli.utils.ingest_pull import _is_private++ assert _is_private("https://10\u30020\u30020\u30021") is True+++class TestWhatTheClientConnectsTo:+ """The checks read ``urlparse(url).hostname``; httpx connects to+ ``httpx.URL(url).host``, which it IDNA-encodes first. Whenever the host+ httpx would dial is a non-public, non-loopback IP literal, the check must+ refuse the URL, and when it is public or loopback, the check must not."""++ @pytest.mark.parametrize("separator", [".", "\u3002", "\uff0e", "\uff61"])+ @pytest.mark.parametrize(+ "address",+ [+ "10.0.0.1", "192.168.1.10", "169.254.169.254", "100.64.0.1", "0xa.0.0.1",+ "10.1", "127.0.0.1", "127.0.0.5", "8.8.8.8",+ ],+ )+ def test_the_check_agrees_with_the_client(self, separator, address):+ httpx = pytest.importorskip("httpx")+ from urllib.parse import urlparse++ from soup_cli.utils.net_guard import (+ is_private_or_link_local,+ parse_ip_literal,+ refuse_private_ip_literal,+ )++ url = f"https://{address.replace('.', separator)}/v1"+ try:+ dialled = httpx.URL(url).host+ except httpx.InvalidURL:+ pytest.skip("this httpx refuses the spelling outright, so it cannot dial it")+ assert dialled.isascii(), dialled+ target = parse_ip_literal(dialled)+ assert target is not None, dialled+ hostname = urlparse(url).hostname+ if is_private_or_link_local(dialled) and not target.is_loopback:+ with pytest.raises(ValueError, match=re.escape(_REFUSED)):+ refuse_private_ip_literal(hostname, label="x")+ else:+ refuse_private_ip_literal(hostname, label="x")