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): numeric-looking hosts are read the same way on every platform (follow-up to #1562) (#1650)
Alpamys Makazhand37a163967ed
diff --git a/changelog.d/0.75.1/1650.fixed.md b/changelog.d/0.75.1/1650.fixed.mdnew file mode 100644index 00000000..7874162b--- /dev/null+++ b/changelog.d/0.75.1/1650.fixed.md@@ -0,0 +1 @@+- **A host written only as numbers is an IPv4 address or it is refused (#1650, follow-up to #1562).** `net_guard` reads IPv4 spellings with one strict grammar on every platform, and text that looks like a number but does not fit it (a number too large for its position such as `4294967296` or `10.0.0.256`, a `0x` with no hex digit after it, an `8` in an octal part, a fifth part) was treated as a hostname, although C libraries do not all read such text the same way. The outbound endpoint checks (`--api-base`, judge URLs, `online_dpo_judge`, the vLLM URL, webhooks, the OTLP endpoint, the Langfuse host, the telemetry endpoint, the Web UI chat endpoint) now refuse a host made of numeric labels only that is not a valid IPv4 address; where the check reports its own message it reads `an all-numeric host that is not a valid IPv4 address is not allowed`. A hostname with any label that is not a number, loopback, and every numeric spelling that is a valid address are unaffected. A decimal number longer than `int()` converts (4300 digits) is now "not an address" instead of an uncaught `ValueError`. A host that is a single space counts as non-public on every platform, as it did on Windows.diff --git a/docs/data.md b/docs/data.mdindex c6e105ac..2a45c93f 100644--- a/docs/data.md+++ b/docs/data.md@@ -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 / 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.+**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, as is a host written only as numbers that is not a valid IPv4 address; 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@@ -454,7 +454,8 @@ soup data generate --prompt "..." --provider server --api-base http://localhost: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` staysloopback-only. A private, link-local or reserved IP literal is refused on either scheme, so-address a server on your network by its hostname.+address a server on your network by its hostname. A host written only as numbers that is not a+valid IPv4 address (`10.0.0.256`, `4294967296`) is refused as well.### Multi-Provider Support@@ -530,7 +531,7 @@ soup data augment ./data/train.jsonl --strategy rephrase --count 2 \--provider ollama --model qwen2.5:0.5b --output ./data/train_local.jsonl```-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.+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 and a host written only as numbers that is not a valid IPv4 address (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 226984ca..1a56bd11 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. 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.+`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. A host written only as numbers that is not a valid IPv4 address (`10.0.0.256`, `4294967296`) is refused the same way.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).diff --git a/docs/serving-and-export.md b/docs/serving-and-export.mdindex d20f862a..bd77023e 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 / 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.+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`; a host written only as numbers that is not a valid IPv4 address is rejected too. 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 069f8aaa..4212b71f 100644--- a/docs/training.md+++ b/docs/training.md@@ -929,7 +929,8 @@ validated on SmolLM2-135M with a synthetic judge (not a production RLHF claim; #An `https://` judge URL uses `OPENAI_API_KEY` only when its host is `api.openai.com`; otherhosts are called as an OpenAI-compatible server without that key. An `online_dpo_judge` whosehost 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.+stays allowed); address an internal judge by its hostname. A host written only as numbers that+is not a valid IPv4 address (`10.0.0.256`, `4294967296`) is refused as well.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/utils/net_guard.py b/src/soup_cli/utils/net_guard.pyindex 437f770e..16a13d60 100644--- a/src/soup_cli/utils/net_guard.py+++ b/src/soup_cli/utils/net_guard.py@@ -149,7 +149,12 @@ def _inet_aton_part(part: str) -> int | None:base, digits = 8, part[1:]if not digits or not set(digits) <= _INET_ATON_DIGITS[base]:return None # includes a bare "0x", which needs at least one hex digit- return int(digits, base)+ try:+ return int(digits, base)+ except ValueError:+ # int() refuses decimal text longer than sys.get_int_max_str_digits()+ # (4300 digits by default). A number that long is far out of range.+ return Nonedef inet_aton(text: str) -> int | None:@@ -190,6 +195,58 @@ def inet_aton(text: str) -> int | None:return (packed << (8 * (5 - len(values)))) | last+# A host written as numbers only is not always an address under the grammar+# above: a number may be too large for its position (``4294967296``,+# ``10.0.0.256``), a ``0x`` may have no hex digit after it (``10.0x.0.1``), an+# octal part may hold an 8 (``08.0.0.1``), there may be five parts. C libraries+# do not all read such text the same way, so it is not treated as a hostname+# either: the two refusing predicates below refuse it. ``parse_ip_literal``+# still answers ``None`` for it, so the grammar itself is no wider.+++def _is_numeric_label(label: str) -> bool:+ """Whether ``label`` is written as a number: digits, or ``0x`` and hex digits.++ Wider than what :func:`_inet_aton_part` reads as one: any run of decimal+ digits counts (``08`` too), and so does a ``0x`` with no digit after it.+ """+ if label[:2] in ("0x", "0X"):+ return set(label[2:]) <= _INET_ATON_DIGITS[16]+ return bool(label) and set(label) <= _INET_ATON_DIGITS[10]+++def _is_all_numeric(host: str) -> bool:+ """Whether ``host`` is made of numeric labels only.++ Read the way :func:`parse_ip_literal` reads it: in each ASCII form a+ client may turn the host into, without trailing dots, up to the first C+ whitespace character.+ """+ for spelling in _ascii_spellings(host):+ text = spelling.rstrip(".")+ for i, ch in enumerate(text):+ if ch in _C_SPACE:+ text = text[:i]+ break+ if all(_is_numeric_label(label) for label in text.split(".")):+ return True+ return False+++def _is_one_space(host: str) -> bool:+ """Whether ``host`` is a single space and nothing else.++ Windows' C library reads that text as the unspecified address, so while+ the parser used that library the refusing predicates called such a host+ non-public on Windows. The parser now says it is no address, because+ nothing precedes the whitespace; the two predicates keep the old answer,+ on every platform. No other whitespace-only host was ever read as an+ address, so none is refused here. Read like :func:`_is_all_numeric`: in+ each ASCII form of the host, without trailing dots.+ """+ return any(spelling.rstrip(".") == " " for spelling in _ascii_spellings(host))++# IPv6 prefixes that carry an IPv4 address inside them. The inner address is# what the packet reaches, so it is classified too, whatever the interpreter's# ``ipaddress`` tables say about the outer prefix (6to4 counts as private only@@ -232,13 +289,20 @@ def is_private_or_link_local(host: str) -> bool: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``.++ Also ``True`` for a host made of numeric labels only that+ :func:`parse_ip_literal` does not read (``4294967296``, ``10.0x.0.1``):+ such a host is not treated as a hostname, see :func:`_is_all_numeric`.+ And for a host that is a single space, see :func:`_is_one_space`."""addr = parse_ip_literal(host)if addr is None:# Hostname — we don't resolve DNS here (the SDK does), so fall# back to "treat as public". A malicious DNS record pointing to# a private IP is out of scope for this local-tool threat model.- return False+ # A host written as numbers only is not a hostname, though, and+ # neither is a host that is one space.+ return _is_all_numeric(host) or _is_one_space(host)return is_non_public_address(addr)@@ -276,6 +340,12 @@ def refuse_private_ip_literal(host: str | None, *, label: str) -> None:name directly; it does not make internal services unreachable by name. Anempty or missing host passes too: the caller's scheme check owns that case.``label`` names the setting in the message.++ A host made of numeric labels only that is not a valid IPv4 literal is+ neither an address nor a hostname (see :func:`_is_all_numeric`): it is+ refused as well, with a message of its own that does not repeat the host.+ So is a host that is a single space (see :func:`_is_one_space`); the+ host is stripped first, so that is a space written inside brackets."""clean = (host or "").strip().lower().rstrip(".")if clean.startswith("[") and clean.endswith("]"):@@ -284,6 +354,16 @@ def refuse_private_ip_literal(host: str | None, *, label: str) -> None:returnaddr = parse_ip_literal(clean)if addr is None:+ if _is_all_numeric(clean):+ raise ValueError(+ f"{label}: an all-numeric host that is not a valid IPv4 address "+ "is not allowed (SSRF protection); use a valid IPv4 address or a hostname"+ )+ if _is_one_space(clean):+ raise ValueError(+ f"{label}: a host that is a single space is not allowed (SSRF protection); "+ "use a valid IPv4 address or a hostname"+ )returnmapped = getattr(addr, "ipv4_mapped", None)if (mapped if mapped is not None else addr).is_loopback:diff --git a/tests/test_issue1550_ip_literal_portable.py b/tests/test_issue1550_ip_literal_portable.pyindex c1d25845..cec11164 100644--- a/tests/test_issue1550_ip_literal_portable.py+++ b/tests/test_issue1550_ip_literal_portable.py@@ -231,3 +231,56 @@ def test_refuse_parses_once(monkeypatch: pytest.MonkeyPatch) -> None:with pytest.raises(ValueError):net_guard.refuse_private_ip_literal("10.0.0.1", label="x")assert calls == ["10.0.0.1"]+++# --- hosts ending in a character the stdlib IDNA codec folds to a space ------++# The stdlib ``idna`` codec (nameprep, NFKC) turns U+00A0 NO-BREAK SPACE and+# U+3000 IDEOGRAPHIC SPACE into an ASCII space, so such a host is read like the+# same host ending in " ": the address before the space, as the C parsers do.+IDNA_FOLDED_SPACE = [+ pytest.param("10.0.0.1\u00a0", "10.0.0.1", id="nbsp"),+ pytest.param("10.0.0.1\u3000", "10.0.0.1", id="ideographic-space"),+ pytest.param("10.1\u00a0", "10.0.0.1", id="nbsp-short-form"),+ pytest.param("167772161\u3000", "10.0.0.1", id="ideographic-space-decimal"),+ pytest.param("10.0.0.1\u00a0x", "10.0.0.1", id="nbsp-then-text"),+ pytest.param("10.0.0.1\u3000x", "10.0.0.1", id="ideographic-space-then-text"),+]++[email protected](("host", "prefix"), IDNA_FOLDED_SPACE)+def test_idna_folded_trailing_space_reads_as_prefix(host: str, prefix: str) -> None:+ """A host ending in U+00A0 / U+3000 reads as the address before it."""+ # The premise: the codec a client encodes the host with turns each of the+ # two characters into an ASCII space and changes nothing else.+ folded = host.replace("\u00a0", " ").replace("\u3000", " ")+ assert host.encode("idna").decode("ascii") == folded+ assert parse_ip_literal(host) == ipaddress.IPv4Address(prefix)+ assert is_private_or_link_local(host)+ with pytest.raises(ValueError, match="SSRF"):+ refuse_private_ip_literal(host, label="x")++[email protected]("host", ["127.0.0.1\u00a0", "127.0.0.1\u3000x"])+def test_idna_folded_trailing_space_keeps_loopback(host: str) -> None:+ """The same reading keeps a loopback address allowed."""+ assert parse_ip_literal(host) == ipaddress.IPv4Address("127.0.0.1")+ refuse_private_ip_literal(host, label="x")+++ "text",+ [+ "10.0.0.1\x1cx", # str.isspace() says yes; C isspace() says no+ "10.0.0.1\x1fx",+ "10.0.0.1\x85",+ "10.0.0.1\u00a0", # folded to a space by the codec, not by the parser+ "10.0.0.1\u3000",+ "10.0.0.1\u2028",+ ],+)+def test_only_c_whitespace_ends_the_text(text: str) -> None:+ """Only the six C whitespace characters end the text; after any other, it is no address."""+ from soup_cli.utils.net_guard import inet_aton++ assert inet_aton(text) is Nonediff --git a/tests/test_issue1550_numeric_host.py b/tests/test_issue1550_numeric_host.pynew file mode 100644index 00000000..9a627fbf--- /dev/null+++ b/tests/test_issue1550_numeric_host.py@@ -0,0 +1,585 @@+"""#1550 follow-up: a host written as numbers only is an IPv4 literal or it is refused.++``parse_ip_literal`` reads IPv4 spellings with one strict grammar on every+platform (#1562). C libraries do not all agree with that grammar on text that+looks like a number but is not an address under it: a number too large for its+position (``4294967296``, ``10.0.0.256``), a ``0x`` with no hex digit after it+(``10.0x.0.1``), an ``8`` in an octal part (``08.0.0.1``), a fifth part. Some+of them refuse such text and some read an address from it, so what a host like+that names would depend on the platform.++The two refusing predicates, ``is_private_or_link_local`` and+``refuse_private_ip_literal``, therefore never treat a host made only of+numeric labels as a hostname: it is a valid IPv4 literal, classified as before,+or it is refused. The parser is unchanged. It still answers ``None`` for such+text, so a caller that asks whether an address is loopback or local gets the+same answer as before.+"""++from __future__ import annotations++import ipaddress++import pytest+from pydantic import ValidationError++from soup_cli.utils import net_guard+from soup_cli.utils.net_guard import (+ inet_aton,+ is_private_or_link_local,+ parse_ip_literal,+ refuse_private_ip_literal,+)++_NUMERIC = (+ "an all-numeric host that is not a valid IPv4 address is not allowed (SSRF protection); "+ "use a valid IPv4 address or a hostname"+)+# How the non-public refusal starts. What follows it is not pinned in this file.+_NON_PUBLIC = "private/link-local/reserved IP hosts are not allowed (SSRF protection)"++# Every label is a number and the whole is not an IPv4 literal under the strict+# grammar. Plain ASCII, lower case, no whitespace: these go through URLs too.+NUMERIC_NOT_AN_ADDRESS = [+ # A number too large for its position.+ pytest.param("4294967296", id="one-part-2pow32"),+ pytest.param("4462739457", id="one-part-above-2pow32"),+ pytest.param("0x10a000001", id="one-part-hex-above-2pow32"),+ pytest.param("040000000000", id="one-part-octal-2pow32"),+ pytest.param("18446744073709719777", id="one-part-above-2pow64"),+ pytest.param("0x1000000000000000a", id="one-part-hex-above-2pow64"),+ pytest.param("10.18446744073709551617", id="last-part-above-2pow64"),+ pytest.param("10.4294967297", id="last-part-above-2pow32"),+ pytest.param("10.16777216", id="last-part-above-24-bits"),+ pytest.param("10.0.65536", id="last-part-above-16-bits"),+ pytest.param("10.0.0.256", id="last-part-above-8-bits"),+ pytest.param("256.0.0.1", id="first-part-above-8-bits"),+ pytest.param("4294967306.0.0.1", id="first-part-above-2pow32"),+ pytest.param("18446744073709551626.0.0.1", id="first-part-above-2pow64"),+ # A 0x prefix with no hex digit after it.+ pytest.param("0x.1", id="empty-hex-first-part"),+ pytest.param("0x.0", id="empty-hex-then-zero"),+ pytest.param("10.0x.0.1", id="empty-hex-inner-part"),+ pytest.param("0x.0x.0x.1", id="empty-hex-three-parts"),+ pytest.param("10.0x", id="empty-hex-last-part"),+ pytest.param("0x", id="bare-0x"),+ # An 8 or a 9 in a part that starts with 0.+ pytest.param("08.0.0.1", id="octal-with-8"),+ pytest.param("012.0.0.09", id="octal-with-9-last"),+ pytest.param("09", id="one-part-octal-with-9"),+ # More than four parts.+ pytest.param("1.2.3.4.5", id="five-parts"),+ pytest.param("10.0.0.0.1", id="five-parts-with-zero"),+]++# The same hosts in the other forms the predicates accept: a trailing dot,+# upper case, text after C whitespace, and the non-ASCII forms a client folds+# to ASCII before it connects (see ``net_guard._ascii_spellings``).+NUMERIC_NOT_AN_ADDRESS_OTHER_FORMS = [+ pytest.param("4462739457.", id="trailing-dot"),+ pytest.param("10.0x.0.1.", id="empty-hex-trailing-dot"),+ pytest.param("0X10A000001", id="upper-case-hex"),+ pytest.param("0X.1", id="upper-case-empty-hex"),+ pytest.param("4462739457 x", id="space-then-text"),+ pytest.param("10.0x.0.1\tx", id="tab-then-text"),+ pytest.param("4462739457\x0bx", id="vertical-tab-then-text"),+ pytest.param("0x.1 ", id="trailing-space"),+ pytest.param(+ "\uff14\uff14\uff16\uff12\uff17\uff13\uff19\uff14\uff15\uff17", id="fullwidth-digits"+ ),+ pytest.param("10\u300218446744073709551617", id="ideographic-full-stop"),+ pytest.param("0x\uff0e1", id="fullwidth-full-stop"),+ pytest.param("4462739457\u3000x", id="ideographic-space-then-text"),+ pytest.param("44627\u00ad39457", id="soft-hyphen"),+]++# At least one label is not a number: these are names, whatever else is in them.+HOSTNAMES = [+ pytest.param("api.example.com", id="plain"),+ pytest.param("cbc.ca", id="hex-letters-only"),+ pytest.param("db.de", id="hex-letters-only-short"),+ pytest.param("deadbeef", id="one-label-hex-letters"),+ pytest.param("cafe.babe", id="two-labels-hex-letters"),+ pytest.param("3f4e5a6b7c8d", id="hex-digits-no-prefix"),+ pytest.param("1a", id="digit-then-letter"),+ pytest.param("1e100.net", id="digit-led-domain"),+ pytest.param("0x.org", id="0x-under-a-name"),+ pytest.param("0xabc.de", id="hex-number-under-a-name"),+ pytest.param("0xdead.beef", id="hex-number-then-letters"),+ pytest.param("10.0.0.1.nip.io", id="address-under-a-name"),+ pytest.param("1.2.3.4.example.com", id="numbers-under-a-name"),+ pytest.param("4294967296.example.com", id="large-number-under-a-name"),+ pytest.param("0x10a000001.internal", id="large-hex-under-a-name"),+ pytest.param("10-0-0-1", id="hyphens"),+ pytest.param("1_0", id="underscore"),+ pytest.param("0b1010.0.0.1", id="binary-prefix"),+ pytest.param("0o12.0.0.1", id="python-octal-prefix"),+ pytest.param("0x0xa.1", id="two-hex-prefixes"),+ pytest.param("0x1g", id="hex-with-g"),+ pytest.param("10.0.0.1x", id="letter-after-address"),+ pytest.param("4462739457x", id="letter-after-number"),+ pytest.param("1..2", id="empty-inner-label"),+ pytest.param(".1", id="empty-first-label"),+ pytest.param("+1", id="plus-sign"),+ pytest.param("-1", id="minus-sign"),+ pytest.param("10.0.0.1%20x", id="percent-escape"),+ pytest.param("4462739457\x1cx", id="not-c-whitespace"),+ pytest.param("m\u00fcnchen.example", id="idn"),+ pytest.param("\u0661\u0660.0.0.1", id="arabic-indic-digits"),+]++LOOPBACK = [+ "localhost",+ "LOCALHOST",+ "localhost.",+ "127.0.0.1",+ "::1",+ "[::1]",+ "::ffff:127.0.0.1",+ "127.1",+ "127.0.1",+ "2130706433",+ "0x7f000001",+ "0x7f.1",+ "0177.0.0.1",+ "127.0.0.1 x",+ "127\u30020\u30020\u30021",+]++# Numeric spellings the strict grammar does read keep their own classification.+PUBLIC_NUMERIC = ["8.8.8.8", "134744072", "0x8080808", "010.010.010.010", "1.1"]+NON_PUBLIC_NUMERIC = ["10.0.0.1", "167772161", "0xa.1", "012.0.0.1", "0xffffffff", "0"]+++def _refusal(host: str) -> str:+ with pytest.raises(ValueError) as excinfo:+ refuse_private_ip_literal(host, label="x")+ return str(excinfo.value)+++# --- the rule ----------------------------------------------------------------++[email protected]("host", NUMERIC_NOT_AN_ADDRESS + NUMERIC_NOT_AN_ADDRESS_OTHER_FORMS)+def test_numeric_host_that_is_not_an_address_is_refused(host: str) -> None:+ """Both predicates refuse it, although the parser says it is no address."""+ assert parse_ip_literal(host) is None # the premise+ assert is_private_or_link_local(host) is True+ assert _refusal(host) == f"x: {_NUMERIC}"++[email protected]("host", ["4462739457", "0x.1", "10.0x.0.1"])+def test_numeric_host_is_refused_in_brackets_too(host: str) -> None:+ """``refuse_private_ip_literal`` takes the brackets off first, as it does for IPv6."""+ assert _refusal(f"[{host}]") == f"x: {_NUMERIC}"+++def test_the_refusal_does_not_repeat_the_host() -> None:+ """The message is fixed text: a caller may show it without echoing the endpoint."""+ message = _refusal("4462739457")+ assert message == f"x: {_NUMERIC}"+ assert "4462739457" not in message+ # The label is the only part that varies.+ with pytest.raises(ValueError) as excinfo:+ refuse_private_ip_literal("4462739457", label="judge URL")+ assert str(excinfo.value) == f"judge URL: {_NUMERIC}"+++def test_refuse_still_parses_once_for_a_numeric_host(monkeypatch: pytest.MonkeyPatch) -> None:+ """The extra check reuses the one parse; it does not parse again."""+ calls: list[str] = []+ real = net_guard.parse_ip_literal++ def counting(host: str):+ calls.append(host)+ return real(host)++ monkeypatch.setattr(net_guard, "parse_ip_literal", counting)+ with pytest.raises(ValueError, match="all-numeric"):+ net_guard.refuse_private_ip_literal("4462739457", label="x")+ assert calls == ["4462739457"]+++# --- what the rule leaves alone ---------------------------------------------++[email protected]("host", HOSTNAMES)+def test_host_with_a_label_that_is_not_a_number_stays_a_hostname(host: str) -> None:+ """A name is not refused, even one made only of digits, dots and a-f."""+ assert parse_ip_literal(host) is None+ assert is_private_or_link_local(host) is False+ refuse_private_ip_literal(host, label="x")++[email protected]("host", ["", ".", "..", "\t"])+def test_host_with_nothing_in_it_is_not_numeric(host: str) -> None:+ """No label at all is not a number either; an empty host is the caller's case."""+ assert is_private_or_link_local(host) is False+ refuse_private_ip_literal(host, label="x")+++def test_leading_space_is_not_skipped() -> None:+ """The text before the first C whitespace is empty, so there is no number to read."""+ assert parse_ip_literal(" 4462739457") is None+ assert is_private_or_link_local(" 4462739457") is False++[email protected]("host", LOOPBACK)+def test_loopback_stays_allowed(host: str) -> None:+ """Loopback names and every loopback spelling the parser reads still pass."""+ refuse_private_ip_literal(host, label="x")++[email protected]("host", PUBLIC_NUMERIC)+def test_public_numeric_spelling_stays_public(host: str) -> None:+ """A numeric host that IS an address is classified by that address."""+ assert parse_ip_literal(host) is not None+ assert is_private_or_link_local(host) is False+ refuse_private_ip_literal(host, label="x")++[email protected]("host", NON_PUBLIC_NUMERIC)+def test_non_public_numeric_spelling_keeps_its_own_message(host: str) -> None:+ """A non-public address is still reported as one, not as an invalid number."""+ assert parse_ip_literal(host) is not None+ assert is_private_or_link_local(host) is True+ message = _refusal(host)+ assert message.startswith(f"x: {_NON_PUBLIC}")+ assert "all-numeric" not in message+++# --- the parser and the callers that only read it are unchanged --------------++[email protected]("host", NUMERIC_NOT_AN_ADDRESS)+def test_the_parser_still_reads_no_address(host: str) -> None:+ """The rule lives in the refusing predicates; the grammar did not get wider."""+ assert inet_aton(host) is None+ assert parse_ip_literal(host) is None++[email protected]("host", NUMERIC_NOT_AN_ADDRESS)[email protected]("scheme", ["https", "http"])+def test_numeric_host_is_not_local_or_loopback(scheme: str, host: str) -> None:+ """Callers that ask "is this address local?" keep saying no."""+ from soup_cli.utils.ingest_pull import _is_loopback+ from soup_cli.utils.loop_stages import _endpoint_is_local++ assert _endpoint_is_local(f"{scheme}://{host}") is False+ assert _endpoint_is_local(f"{scheme}://{host}:8000/v1") is False+ assert _is_loopback(host) is False+++# --- through the callers ------------------------------------------------------++GATE_HOSTS = ["4462739457", "0x.1", "10.0x.0.1", "10.0.0.256"]++[email protected]("host", GATE_HOSTS)+def test_vllm_url_refuses_a_numeric_host(host: str) -> None:+ from soup_cli.data.providers.vllm import validate_vllm_url++ with pytest.raises(ValueError) as excinfo:+ validate_vllm_url(f"https://{host}")+ assert str(excinfo.value) == f"vLLM URL: {_NUMERIC}"+ validate_vllm_url("https://api.example.com")++[email protected]("host", GATE_HOSTS)+def test_judge_api_base_refuses_a_numeric_host(host: str) -> None:+ from soup_cli.eval.judge import validate_judge_api_base++ with pytest.raises(ValueError) as excinfo:+ validate_judge_api_base(f"https://{host}/v1")+ assert str(excinfo.value) == f"judge URL: {_NUMERIC}"+ validate_judge_api_base("https://api.example.com/v1")++[email protected]("host", GATE_HOSTS)+def test_gate_suite_refuses_a_numeric_judge_host(host: str) -> None:+ from soup_cli.eval.gate import GateTask++ def task(judge_model: str) -> GateTask:+ return GateTask(+ type="judge", name="t", threshold=0.5, prompts="p.jsonl", judge_model=judge_model+ )++ with pytest.raises(ValidationError, match="judge_model URL: an all-numeric host"):+ task(f"https://{host}/m")+ assert task("https://api.example.com/m").judge_model == "https://api.example.com/m"++[email protected]("host", GATE_HOSTS)[email protected]("scheme", ["https", "http"])+def test_online_dpo_judge_refuses_a_numeric_host(scheme: str, host: str) -> None:+ from soup_cli.config.schema import TrainingConfig++ with pytest.raises(ValidationError, match="online_dpo_judge: an all-numeric host"):+ TrainingConfig(online_dpo_judge=f"{scheme}://{host}/m")+ url = "https://api.example.com/m"+ assert TrainingConfig(online_dpo_judge=url).online_dpo_judge == url++[email protected]("host", GATE_HOSTS)+def test_webhook_refuses_a_numeric_host_unless_private_hosts_are_allowed(host: str) -> None:+ from soup_cli.utils.webhooks import validate_webhook_url++ url = f"https://{host}/hook"+ with pytest.raises(ValueError, match="private/link-local/reserved hosts are not allowed"):+ validate_webhook_url(url)+ # The opt-in that admits a private address admits this host as well.+ assert validate_webhook_url(url, allow_private_hosts=True) == url+ assert (+ validate_webhook_url("https://hooks.example.com/hook") == "https://hooks.example.com/hook"+ )++[email protected]("host", GATE_HOSTS)+def test_otlp_endpoint_refuses_a_numeric_host(host: str) -> None:+ from soup_cli.utils.tracing import validate_otlp_endpoint++ with pytest.raises(ValueError, match="is a private / link-local IP"):+ validate_otlp_endpoint(f"https://{host}:4317")+ assert (+ validate_otlp_endpoint("https://otel.example.com:4317") == "https://otel.example.com:4317"+ )++[email protected]("host", GATE_HOSTS)+def test_langfuse_host_check_counts_a_numeric_host_as_private(host: str) -> None:+ from soup_cli.utils.ingest_pull import _is_private++ assert _is_private(f"https://{host}") is True+ assert _is_private("https://cloud.example.com") is False++[email protected]("host", GATE_HOSTS)+def test_telemetry_refuses_a_numeric_host_without_a_lookup(+ monkeypatch: pytest.MonkeyPatch, host: str+) -> None:+ """The static tier decides: the host never reaches the resolver."""+ from soup_cli.utils import trackers++ looked_up: list[str] = []++ def resolver(name: str, **_kwargs: object) -> list[str]:+ looked_up.append(name)+ return ["93.184.216.34"]++ monkeypatch.setattr(trackers, "_resolve_host_ips", resolver)+ assert trackers._telemetry_endpoint_is_safe(f"https://{host}/i/v0/e/") is False+ assert looked_up == []+ # The same resolver is reached, and its public answer accepted, for a name.+ assert trackers._telemetry_endpoint_is_safe("https://telemetry.example.com/i/v0/e/") is True+ assert looked_up == ["telemetry.example.com"]+++def test_embedded_and_plain_addresses_are_untouched() -> None:+ """Sanity: the rule does not reach hosts the parser already reads."""+ assert parse_ip_literal("0xa.1") == ipaddress.IPv4Address("10.0.0.1")+ assert parse_ip_literal("::ffff:10.0.0.1") is not None+ assert _refusal("::ffff:10.0.0.1").startswith(f"x: {_NON_PUBLIC}")+++# --- a number longer than int() converts --------------------------------------++# int() refuses decimal text longer than sys.get_int_max_str_digits() with a+# ValueError. Such a number is far out of range: it is no address, and the+# parser says so with None, as it does for every other text it does not read.+LONG_DECIMAL = [+ pytest.param("9" * 4301, id="one-part-4301-digits"),+ pytest.param("9" * 20000, id="one-part-20000-digits"),+ pytest.param("10." + "9" * 5000, id="last-part-5000-digits"),+ pytest.param("9" * 5000 + ".0.0.1", id="first-part-5000-digits"),+]+++def default_int_limit():+ """Pin the interpreter's default limit, whatever the environment set."""+ import sys++ previous = sys.get_int_max_str_digits()+ sys.set_int_max_str_digits(4300)+ yield+ sys.set_int_max_str_digits(previous)++[email protected]("default_int_limit")[email protected]("host", LONG_DECIMAL)+def test_a_number_longer_than_int_converts_is_no_address_and_no_error(host: str) -> None:+ """The parser answers None; it does not let int()'s ValueError out."""+ assert inet_aton(host) is None+ assert parse_ip_literal(host) is None++[email protected]("default_int_limit")[email protected]("host", LONG_DECIMAL)+def test_a_very_long_numeric_host_is_refused_like_any_other(host: str) -> None:+ """Both predicates give their usual answer, with the usual message."""+ assert is_private_or_link_local(host) is True+ assert _refusal(host) == f"x: {_NUMERIC}"++[email protected]("default_int_limit")[email protected]("host", LONG_DECIMAL)+def test_a_very_long_numeric_host_does_not_raise_in_the_callers(+ monkeypatch: pytest.MonkeyPatch, host: str+) -> None:+ """Callers that return a bool keep returning one."""+ from soup_cli.utils import trackers+ from soup_cli.utils.ingest_pull import _is_loopback, _is_private+ from soup_cli.utils.loop_stages import _endpoint_is_local++ def resolver(name: str, **_kwargs: object) -> list[str]:+ raise AssertionError("the resolver must not be reached")++ monkeypatch.setattr(trackers, "_resolve_host_ips", resolver)+ assert _endpoint_is_local(f"https://{host}") is False+ assert _is_loopback(host) is False+ assert _is_private(f"https://{host}") is True+ assert trackers._telemetry_endpoint_is_safe(f"https://{host}/i/v0/e/") is False++[email protected]("default_int_limit")+def test_a_long_run_of_zeros_before_a_valid_number_still_reads() -> None:+ """Length alone refuses nothing: octal and hex text of any length converts."""+ assert inet_aton("0" * 5000 + "12") == 10+ assert inet_aton("0x" + "0" * 5000 + "a") == 10+ assert inet_aton("0x" + "f" * 5000) is None+ assert inet_aton("0" + "7" * 5000) is None+++# --- a host that is one space ---------------------------------------------------++# Windows' C library reads a host of exactly one space as the unspecified+# address, so while the parser used that library the refusing predicates called+# such a host non-public there. The pure-Python parser says it is no address:+# nothing precedes the whitespace. The predicates keep the old answer, on every+# platform, and nothing else about whitespace changes.+_ONE_SPACE = (+ "a host that is a single space is not allowed (SSRF protection); "+ "use a valid IPv4 address or a hostname"+)++# One space, in the forms the predicates read a host in: without trailing dots,+# and in the ASCII form a client folds a non-ASCII host to.+ONE_SPACE = [+ pytest.param(" ", id="space"),+ pytest.param(" .", id="space-trailing-dot"),+ pytest.param(" ..", id="space-two-trailing-dots"),+ pytest.param("\u00a0", id="nbsp"),+ pytest.param("\u3000", id="ideographic-space"),+ pytest.param("\u00a0.", id="nbsp-trailing-dot"),+]++# Hosts next to it that the C library never read as an address either.+NOT_ONE_SPACE = [+ pytest.param("", id="empty"),+ pytest.param("\t", id="tab"),+ pytest.param(" ", id="two-spaces"),+ pytest.param(" \t", id="space-tab"),+ pytest.param("\x0b", id="vertical-tab"),+ pytest.param(" x", id="space-then-letter"),+ pytest.param(". ", id="dot-then-space"),+ pytest.param(".. ", id="two-dots-then-space"),+ pytest.param(" 1", id="space-then-number"),+ pytest.param(" 10.0.0.1", id="space-then-address"),+ pytest.param("\n10.0.0.1", id="newline-then-address"),+]++[email protected]("host", ONE_SPACE)+def test_a_one_space_host_counts_as_non_public(host: str) -> None:+ """The predicate keeps the answer it gave on Windows; the parser reads nothing."""+ assert parse_ip_literal(host) is None+ assert is_private_or_link_local(host) is True++[email protected]("host", ["\u00a0", "\u3000"])+def test_the_two_folded_spaces_are_one_space_to_a_client(host: str) -> None:+ """The premise of the non-ASCII rows: the stdlib codec folds each to one space."""+ assert host.encode("idna").decode("ascii") == " "++[email protected]("host", NOT_ONE_SPACE)+def test_other_whitespace_hosts_are_not_refused_by_the_predicate(host: str) -> None:+ """Only the one-space host was ever read as an address; the rule adds nothing else."""+ assert is_private_or_link_local(host) is False+++def test_trailing_space_after_an_address_still_reads_as_the_address() -> None:+ """That is the parser's whitespace rule, and it is unchanged."""+ assert is_private_or_link_local("10.0.0.1 ") is True+ assert is_private_or_link_local("8.8.8.8 ") is False++[email protected]("host", [None, "", " ", "\t", " .", "\u00a0", " "])+def test_refuse_still_passes_a_host_that_is_empty_once_stripped(host: str | None) -> None:+ """``refuse_private_ip_literal`` strips first; an empty host is the caller's case."""+ refuse_private_ip_literal(host, label="x")+++def test_refuse_refuses_the_one_space_host_in_brackets() -> None:+ """Brackets keep the space from being stripped, so the host reaches the check."""+ message = _refusal("[ ]")+ assert message == f"x: {_ONE_SPACE}"+ assert "[" not in message++[email protected]("host", [" 1", " 10.0.0.1", "\n10.0.0.1", "10.0.0.1 "])+def test_refuse_reads_the_address_inside_surrounding_whitespace(host: str) -> None:+ """Stripped, then read: refused as the non-public address it is, as before."""+ assert _refusal(host).startswith(f"x: {_NON_PUBLIC}")++[email protected]("host", ONE_SPACE)+def test_the_parser_and_the_local_checks_do_not_read_a_one_space_host(host: str) -> None:+ """The rule is in the refusing predicates only."""+ from soup_cli.utils.ingest_pull import _is_loopback+ from soup_cli.utils.loop_stages import _endpoint_is_local++ assert inet_aton(host) is None+ assert parse_ip_literal(host) is None+ assert _is_loopback(host) is False+ assert _endpoint_is_local(f"https://{host}") is False+++def test_webhook_refuses_a_one_space_host_unless_private_hosts_are_allowed() -> None:+ from soup_cli.utils.webhooks import validate_webhook_url++ url = "https:// /hook"+ with pytest.raises(ValueError, match="private/link-local/reserved hosts are not allowed"):+ validate_webhook_url(url)+ assert validate_webhook_url(url, allow_private_hosts=True) == url+++def test_otlp_endpoint_refuses_a_one_space_host() -> None:+ from soup_cli.utils.tracing import validate_otlp_endpoint++ with pytest.raises(ValueError, match="is a private / link-local IP"):+ validate_otlp_endpoint("https:// :4317")+++def test_langfuse_host_check_counts_a_one_space_host_as_private() -> None:+ from soup_cli.utils.ingest_pull import _is_private++ assert _is_private("https:// ") is True+ assert _is_private("https:// ") is False+++def test_telemetry_refuses_a_one_space_host_without_a_lookup(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The static tier decides, as it did while the parser used the C library on Windows."""+ from soup_cli.utils import trackers++ looked_up: list[str] = []++ def resolver(name: str, **_kwargs: object) -> list[str]:+ looked_up.append(name)+ return ["93.184.216.34"]++ monkeypatch.setattr(trackers, "_resolve_host_ips", resolver)+ assert trackers._telemetry_endpoint_is_safe("https:// /i/v0/e/") is False+ assert looked_up == []