فهرست منبع

feat(functions): guard ctx.fetch() egress against SSRF

A sandboxed user script runs on a host that sits next to
smartbotic-database on localhost and inside a private network. An
unguarded fetch() would turn "run my little JS function" into an
authenticated pivot: the database port, the cloud metadata service at
169.254.169.254, every other host on the LAN. Every rule here is load
bearing.

Two principles run through the file and must not be simplified away.

Fail closed: anything the guard cannot parse, resolve or classify is
blocked. A classifier that does not understand its input has not proved
the destination safe. inet_pton is deliberate - it rejects the obfuscated
spellings SSRF payloads lean on ("127.1", "0177.0.0.1", "2130706433"),
and unparseable means blocked.

Classify every address: a hostname can resolve to many, and an attacker
controls his own DNS. Checking only the first answer is a known bypass.
The classification loop is split out from the resolver so that rule is
testable without DNS.

Also closed: IPv4-mapped IPv6 (::ffff:127.0.0.1 reaches the same peer as
127.0.0.1), userinfo misdirection (http://trusted@10.0.0.1/ classifies as
10.0.0.1), the IPv6 prefixes that are other spellings of an IPv4
destination (NAT64, 6to4, ::/96), and control characters in a URL.

A custom blocklist REPLACES the defaults rather than extending them, so
an operator can deliberately widen egress; entries that do not parse are
reported for logging, because a typo in a blocklist is a hole in the
guard and must be visible.

Residual risk documented in the header, not papered over: the guard
resolves the name and the HTTP client resolves it again, so a hostile
0-TTL answer can differ the second time. Closing that needs ctx.fetch to
connect to the address this guard approved rather than to the name.

44 tests.
fszontagh 1 ماه پیش
والد
کامیت
731d716ae4
3فایلهای تغییر یافته به همراه1077 افزوده شده و 0 حذف شده
  1. 463 0
      src/functions/net_guard.cpp
  2. 157 0
      src/functions/net_guard.hpp
  3. 457 0
      tests/test_functions_net_guard.cpp

+ 463 - 0
src/functions/net_guard.cpp

@@ -0,0 +1,463 @@
+#include "functions/net_guard.hpp"
+
+#include <arpa/inet.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <sys/socket.h>
+
+#include <algorithm>
+#include <cctype>
+#include <cstring>
+#include <mutex>
+
+namespace svapi::functions {
+namespace {
+
+// --- small helpers ---------------------------------------------------------
+
+std::string trim(const std::string& s) {
+    const auto notSpace = [](unsigned char c) { return std::isspace(c) == 0; };
+    auto b = std::find_if(s.begin(), s.end(), notSpace);
+    auto e = std::find_if(s.rbegin(), s.rend(), notSpace).base();
+    return (b < e) ? std::string(b, e) : std::string();
+}
+
+std::string toLower(std::string s) {
+    std::transform(s.begin(), s.end(), s.begin(),
+                   [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
+    return s;
+}
+
+bool allDigits(const std::string& s) {
+    return !s.empty() && std::all_of(s.begin(), s.end(),
+                                     [](unsigned char c) { return std::isdigit(c) != 0; });
+}
+
+/// A parsed IP literal: family plus the raw bytes (4 used for v4).
+struct RawAddr {
+    bool v4 = true;
+    std::array<std::uint8_t, 16> bytes{};
+};
+
+/// Parse a bare IP literal. inet_pton is deliberate: it accepts ONLY the
+/// canonical dotted-quad / RFC 4291 forms and rejects the obfuscated spellings
+/// that SSRF payloads lean on (shortened "127.1", octal "0177.0.0.1", hex
+/// "0x7f.0.0.1", the bare integer "2130706433"). Those all end up unparseable
+/// here, and unparseable means blocked, which is the behaviour we want.
+std::optional<RawAddr> parseIpLiteral(const std::string& ip) {
+    if (ip.empty()) return std::nullopt;
+    RawAddr out;
+    in_addr v4{};
+    if (::inet_pton(AF_INET, ip.c_str(), &v4) == 1) {
+        out.v4 = true;
+        std::memcpy(out.bytes.data(), &v4.s_addr, 4);
+        return out;
+    }
+    in6_addr v6{};
+    if (::inet_pton(AF_INET6, ip.c_str(), &v6) == 1) {
+        out.v4 = false;
+        std::memcpy(out.bytes.data(), v6.s6_addr, 16);
+        return out;
+    }
+    return std::nullopt;
+}
+
+/// Is this v6 address an IPv4-mapped one (::ffff:a.b.c.d)?
+bool isV4Mapped(const RawAddr& a) {
+    if (a.v4) return false;
+    for (int i = 0; i < 10; ++i) {
+        if (a.bytes[i] != 0) return false;
+    }
+    return a.bytes[10] == 0xff && a.bytes[11] == 0xff;
+}
+
+/// The embedded IPv4 address of a v4-mapped v6 address.
+RawAddr unmapV4(const RawAddr& a) {
+    RawAddr out;
+    out.v4 = true;
+    std::copy(a.bytes.begin() + 12, a.bytes.begin() + 16, out.bytes.begin());
+    return out;
+}
+
+void maskInPlace(std::array<std::uint8_t, 16>& bytes, int bits, bool v4) {
+    const int len = v4 ? 4 : 16;
+    for (int i = 0; i < len; ++i) {
+        const int consumed = i * 8;
+        if (bits >= consumed + 8) continue;
+        if (bits <= consumed) {
+            bytes[static_cast<std::size_t>(i)] = 0;
+        } else {
+            const int keep = bits - consumed;  // 1..7
+            const auto mask = static_cast<std::uint8_t>(0xffu << (8 - keep));
+            bytes[static_cast<std::size_t>(i)] &= mask;
+        }
+    }
+    for (int i = len; i < 16; ++i) bytes[static_cast<std::size_t>(i)] = 0;
+}
+
+bool prefixEqual(const std::array<std::uint8_t, 16>& a,
+                 const std::array<std::uint8_t, 16>& b, int bits) {
+    const int whole = bits / 8;
+    for (int i = 0; i < whole; ++i) {
+        if (a[static_cast<std::size_t>(i)] != b[static_cast<std::size_t>(i)]) return false;
+    }
+    const int rest = bits % 8;
+    if (rest != 0) {
+        const auto mask = static_cast<std::uint8_t>(0xffu << (8 - rest));
+        if ((a[static_cast<std::size_t>(whole)] & mask) !=
+            (b[static_cast<std::size_t>(whole)] & mask)) {
+            return false;
+        }
+    }
+    return true;
+}
+
+bool rangeContainsRaw(const CidrRange& r, const RawAddr& a) {
+    if (r.v4 != a.v4) return false;  // family mismatch: just not a member
+    return prefixEqual(r.addr, a.bytes, r.bits);
+}
+
+std::string cidrToString(const CidrRange& r) {
+    char buf[INET6_ADDRSTRLEN] = {0};
+    const char* p = r.v4 ? ::inet_ntop(AF_INET, r.addr.data(), buf, sizeof(buf))
+                         : ::inet_ntop(AF_INET6, r.addr.data(), buf, sizeof(buf));
+    std::string s = (p != nullptr) ? std::string(p) : std::string("?");
+    return s + "/" + std::to_string(r.bits);
+}
+
+bool hasControlChars(const std::string& s) {
+    return std::any_of(s.begin(), s.end(), [](unsigned char c) {
+        return c < 0x20 || c == 0x7f;
+    });
+}
+
+} // namespace
+
+// --- parseHttpUrl ----------------------------------------------------------
+
+std::optional<HttpUrlParts> parseHttpUrl(const std::string& url) {
+    const std::string raw = trim(url);
+    if (raw.empty()) return std::nullopt;
+    // A control character inside a URL is how a request gets smuggled past the
+    // host's own parser (CR/LF header injection), so refuse the URL instead of
+    // guessing which half is real.
+    if (hasControlChars(raw)) return std::nullopt;
+
+    const auto sep = raw.find("://");
+    if (sep == std::string::npos || sep == 0) return std::nullopt;
+    const std::string scheme = toLower(raw.substr(0, sep));
+    // http/https only. file:, gopher:, dict:, data: and friends each turn an
+    // SSRF into something worse (local file read, memcached/redis commands).
+    if (scheme != "http" && scheme != "https") return std::nullopt;
+
+    const std::string rest = raw.substr(sep + 3);
+    const auto pathStart = rest.find_first_of("/?#");
+    std::string authority = (pathStart == std::string::npos) ? rest : rest.substr(0, pathStart);
+    std::string path = (pathStart == std::string::npos) ? "/" : rest.substr(pathStart);
+    if (path.empty() || path.front() != '/') path = "/" + path;
+
+    // Drop userinfo: "http://expected-host@10.0.0.1/" must be classified as
+    // 10.0.0.1, which is the host that would actually be connected to.
+    const auto at = authority.rfind('@');
+    if (at != std::string::npos) authority = authority.substr(at + 1);
+    if (authority.empty()) return std::nullopt;
+
+    std::string host;
+    std::string portText;
+    if (authority.front() == '[') {
+        const auto close = authority.find(']');
+        if (close == std::string::npos) return std::nullopt;
+        // Brackets are URL syntax, not part of the address. Strip them so the
+        // host can be fed straight to inet_pton/getaddrinfo, both of which
+        // reject a bracketed literal.
+        host = authority.substr(1, close - 1);
+        const std::string after = authority.substr(close + 1);
+        if (!after.empty()) {
+            if (after.front() != ':') return std::nullopt;
+            portText = after.substr(1);
+        }
+    } else {
+        const auto colon = authority.find(':');
+        if (colon == std::string::npos) {
+            host = authority;
+        } else {
+            host = authority.substr(0, colon);
+            portText = authority.substr(colon + 1);
+            // A second colon means an unbracketed IPv6 literal, which is not a
+            // valid URL authority; parsing it as host:port would silently
+            // misclassify the destination.
+            if (portText.find(':') != std::string::npos) return std::nullopt;
+        }
+    }
+    if (host.empty()) return std::nullopt;
+
+    HttpUrlParts out;
+    out.scheme = scheme;
+    out.host = toLower(host);
+    out.path = path;
+    if (portText.empty()) {
+        // An empty but present ":" ("http://host:/x") is malformed.
+        if (authority.find(':') != std::string::npos && authority.back() == ':') {
+            return std::nullopt;
+        }
+        out.port = (scheme == "https") ? 443 : 80;
+    } else {
+        if (!allDigits(portText) || portText.size() > 5) return std::nullopt;
+        const long p = std::stol(portText);
+        if (p < 1 || p > 65535) return std::nullopt;
+        out.port = static_cast<int>(p);
+    }
+    return out;
+}
+
+// --- CIDR ------------------------------------------------------------------
+
+std::optional<CidrRange> parseCidr(const std::string& cidr) {
+    const std::string text = trim(cidr);
+    if (text.empty()) return std::nullopt;
+
+    std::string addrPart = text;
+    std::string bitsPart;
+    const auto slash = text.find('/');
+    if (slash != std::string::npos) {
+        addrPart = text.substr(0, slash);
+        bitsPart = text.substr(slash + 1);
+        // Reject a second slash rather than ignoring the tail: "10.0.0.0/8/8"
+        // is a config mistake, and a guard must not quietly accept nonsense.
+        if (bitsPart.find('/') != std::string::npos) return std::nullopt;
+    }
+
+    const auto addr = parseIpLiteral(trim(addrPart));
+    if (!addr) return std::nullopt;
+
+    CidrRange out;
+    out.v4 = addr->v4;
+    out.addr = addr->bytes;
+    const int maxBits = addr->v4 ? 32 : 128;
+    if (bitsPart.empty() && slash != std::string::npos) return std::nullopt;
+    if (slash == std::string::npos) {
+        out.bits = maxBits;  // a bare address is a host route
+    } else {
+        const std::string b = trim(bitsPart);
+        if (!allDigits(b) || b.size() > 3) return std::nullopt;
+        const int bits = std::stoi(b);
+        if (bits < 0 || bits > maxBits) return std::nullopt;
+        out.bits = bits;
+    }
+    // Host bits set in the input ("10.1.2.3/8") are masked off, not rejected:
+    // the operator meant the /8, and a range that matched nothing would be a
+    // silent hole in the blocklist.
+    maskInPlace(out.addr, out.bits, out.v4);
+    return out;
+}
+
+bool cidrContains(const CidrRange& range, const std::string& ip) {
+    const auto addr = parseIpLiteral(ip);
+    if (!addr) return false;
+    return rangeContainsRaw(range, *addr);
+}
+
+// --- SsrfPolicy ------------------------------------------------------------
+
+const std::vector<std::string>& SsrfPolicy::defaultBlockedCidrs() {
+    // Everything an egress guard must refuse by default. The IPv4 private and
+    // loopback space plus 169.254.0.0/16, which is where every cloud provider
+    // parks its credential-serving metadata service, and the IPv6 equivalents.
+    static const std::vector<std::string> kDefaults = {
+        // IPv4
+        "0.0.0.0/8",           // "this host on this network"
+        "10.0.0.0/8",          // RFC1918
+        "100.64.0.0/10",       // carrier-grade NAT
+        "127.0.0.0/8",         // loopback - blocks a function calling our own API
+        "169.254.0.0/16",      // link-local, incl. cloud metadata 169.254.169.254
+        "172.16.0.0/12",       // RFC1918
+        "192.0.0.0/24",        // IETF protocol assignments
+        "192.0.2.0/24",        // TEST-NET-1
+        "192.168.0.0/16",      // RFC1918
+        "198.18.0.0/15",       // benchmarking
+        "198.51.100.0/24",     // TEST-NET-2
+        "203.0.113.0/24",      // TEST-NET-3
+        "224.0.0.0/4",         // multicast
+        "240.0.0.0/4",         // reserved, incl. 255.255.255.255 broadcast
+        // IPv6
+        "::/96",               // unspecified, ::1, and the deprecated
+                               // IPv4-compatible form "::127.0.0.1"
+        "::1/128",             // loopback (also inside ::/96; kept explicit)
+        "64:ff9b::/96",        // NAT64 well-known prefix: another way to spell
+                               // an IPv4 destination
+        "64:ff9b:1::/48",      // NAT64 local-use prefix
+        "100::/64",            // discard-only
+        "2001:db8::/32",       // documentation
+        "2002::/16",           // 6to4, embeds an IPv4 address
+        "fc00::/7",            // unique local (covers fd00::/8)
+        "fe80::/10",           // link-local
+        "ff00::/8",            // multicast
+    };
+    return kDefaults;
+}
+
+SsrfPolicy SsrfPolicy::withDefaults() {
+    return fromStrings(defaultBlockedCidrs(), nullptr);
+}
+
+SsrfPolicy SsrfPolicy::fromStrings(const std::vector<std::string>& cidrs,
+                                   std::vector<std::string>* invalid) {
+    SsrfPolicy p;
+    p.ranges_.reserve(cidrs.size());
+    for (const auto& s : cidrs) {
+        if (trim(s).empty()) continue;  // blank lines in config are not errors
+        if (auto r = parseCidr(s)) {
+            p.ranges_.push_back(*r);
+        } else if (invalid != nullptr) {
+            // Reported rather than swallowed: a typo in the blocklist is a hole
+            // in the guard, and the operator has to be able to see it.
+            invalid->push_back(s);
+        }
+    }
+    return p;
+}
+
+std::optional<std::string> SsrfPolicy::blockedBy(const std::string& ip) const {
+    const auto addr = parseIpLiteral(ip);
+    if (!addr) return std::nullopt;  // callers of isBlocked() fail closed instead
+    for (const auto& r : ranges_) {
+        if (rangeContainsRaw(r, *addr)) return cidrToString(r);
+    }
+    // An IPv4-mapped IPv6 address (::ffff:127.0.0.1) reaches exactly the same
+    // peer as its embedded IPv4 address, and many stacks will happily connect
+    // to it. Checking only the v6 form is the classic bypass of a v4
+    // blocklist, so re-check the embedded address.
+    if (isV4Mapped(*addr)) {
+        const RawAddr inner = unmapV4(*addr);
+        for (const auto& r : ranges_) {
+            if (rangeContainsRaw(r, inner)) return cidrToString(r);
+        }
+    }
+    return std::nullopt;
+}
+
+bool SsrfPolicy::isBlocked(const std::string& ip) const {
+    if (!parseIpLiteral(ip)) {
+        // FAIL CLOSED. Not a valid IP literal means we could not classify the
+        // destination, and an unclassified destination has not been proved
+        // safe. Returning false here would re-open the guard to every
+        // obfuscated address form (decimal, octal, hex, bracketed) that
+        // inet_pton refuses to parse.
+        return true;
+    }
+    return blockedBy(ip).has_value();
+}
+
+// --- process-wide snapshot -------------------------------------------------
+
+namespace {
+
+std::mutex& policyMutex() {
+    static std::mutex m;
+    return m;
+}
+
+std::shared_ptr<const SsrfPolicy>& policySlot() {
+    static std::shared_ptr<const SsrfPolicy> slot =
+        std::make_shared<const SsrfPolicy>(SsrfPolicy::withDefaults());
+    return slot;
+}
+
+} // namespace
+
+std::shared_ptr<const SsrfPolicy> currentSsrfPolicy() {
+    // The lock is held only long enough to copy the shared_ptr; the caller then
+    // owns its snapshot and a concurrent replacement cannot pull it out from
+    // under an in-flight run.
+    std::lock_guard<std::mutex> lk(policyMutex());
+    return policySlot();
+}
+
+void setSsrfPolicy(std::shared_ptr<const SsrfPolicy> policy) {
+    // Never leave the slot empty: a null policy would block nothing, i.e. a
+    // failed settings reload would silently disable the guard.
+    if (!policy) policy = std::make_shared<const SsrfPolicy>(SsrfPolicy::withDefaults());
+    std::lock_guard<std::mutex> lk(policyMutex());
+    policySlot() = std::move(policy);
+}
+
+// --- host classification ---------------------------------------------------
+
+std::optional<std::string> blockReasonForAddresses(const std::string& host,
+                                                   const std::vector<std::string>& addresses,
+                                                   const SsrfPolicy& policy) {
+    if (addresses.empty()) {
+        return "host '" + host + "' did not resolve to any address; egress blocked";
+    }
+    // EVERY address, not just the first. An attacker controls the DNS for his
+    // own name and can return one public and one internal address (multi-A
+    // records, DNS rebinding); if any answer is internal the name is unsafe,
+    // because we cannot control which one the connect picks.
+    for (const auto& ip : addresses) {
+        if (const auto range = policy.blockedBy(ip)) {
+            return "host '" + host + "' resolves to " + ip + ", which is in the blocked range " +
+                   *range;
+        }
+        if (policy.isBlocked(ip)) {
+            // Reached when the address itself was unparseable: fail closed.
+            return "host '" + host + "' resolves to '" + ip +
+                   "', which could not be classified; egress blocked";
+        }
+    }
+    return std::nullopt;
+}
+
+std::optional<std::string> ssrfBlockReason(const std::string& host, const SsrfPolicy& policy) {
+    if (trim(host).empty()) return "empty host; egress blocked";
+
+    // A literal needs no DNS, and must not get any: resolving it could only
+    // introduce a difference between what we check and what we connect to.
+    if (parseIpLiteral(host)) {
+        if (const auto range = policy.blockedBy(host)) {
+            return "address " + host + " is in the blocked range " + *range;
+        }
+        return std::nullopt;
+    }
+
+    addrinfo hints{};
+    hints.ai_family = AF_UNSPEC;  // both families; a v6 answer is just as routable
+    hints.ai_socktype = SOCK_STREAM;
+    addrinfo* res = nullptr;
+    const int rc = ::getaddrinfo(host.c_str(), nullptr, &hints, &res);
+    if (rc != 0 || res == nullptr) {
+        if (res != nullptr) ::freeaddrinfo(res);
+        // Resolution failure blocks. An unresolved name has not been shown to
+        // point somewhere safe, and letting the HTTP client try anyway would
+        // move the decision to code that does no checking at all.
+        return "host '" + host + "' could not be resolved (" + ::gai_strerror(rc) +
+               "); egress blocked";
+    }
+
+    std::vector<std::string> addresses;
+    for (const addrinfo* ai = res; ai != nullptr; ai = ai->ai_next) {
+        char buf[INET6_ADDRSTRLEN] = {0};
+        const char* p = nullptr;
+        if (ai->ai_family == AF_INET) {
+            const auto* sa = reinterpret_cast<const sockaddr_in*>(ai->ai_addr);
+            p = ::inet_ntop(AF_INET, &sa->sin_addr, buf, sizeof(buf));
+        } else if (ai->ai_family == AF_INET6) {
+            const auto* sa = reinterpret_cast<const sockaddr_in6*>(ai->ai_addr);
+            p = ::inet_ntop(AF_INET6, &sa->sin6_addr, buf, sizeof(buf));
+        } else {
+            // An address family we cannot classify is not something we hand to
+            // a connect: fail closed on the whole host.
+            ::freeaddrinfo(res);
+            return "host '" + host + "' resolved to an unsupported address family; egress blocked";
+        }
+        if (p == nullptr) {
+            ::freeaddrinfo(res);
+            return "host '" + host + "' resolved to an address that could not be read; egress blocked";
+        }
+        addresses.emplace_back(p);
+    }
+    ::freeaddrinfo(res);
+
+    return blockReasonForAddresses(host, addresses, policy);
+}
+
+} // namespace svapi::functions

+ 157 - 0
src/functions/net_guard.hpp

@@ -0,0 +1,157 @@
+#pragma once
+
+// Egress guard for the function runtime's ctx.fetch().
+//
+// WHY this file exists at all: a sandboxed user script runs on a host that sits
+// next to smartbotic-database on localhost and inside a private network. An
+// unguarded fetch() would turn "run my little JS function" into an authenticated
+// pivot into the internal network (SSRF) - the database port, the cloud metadata
+// service at 169.254.169.254, every other host on the LAN. This module is the
+// control that prevents that, so every rule here is load bearing.
+//
+// Two principles run through the whole file and must not be "simplified" away:
+//
+//   1. FAIL CLOSED. Anything the guard cannot parse, resolve or classify is
+//      treated as blocked. A classifier that does not understand its input has
+//      not proved the destination safe.
+//   2. CLASSIFY EVERY ADDRESS. A hostname can resolve to many addresses, and an
+//      attacker controls his own DNS. Checking only the first answer is a known
+//      bypass (multi-A records, DNS rebinding).
+//
+// Residual risk this module does NOT remove: the classify-then-connect gap
+// (TOCTOU). The name is resolved here and resolved again by the HTTP client, so
+// a hostile DNS server with a 0-second TTL can answer differently the second
+// time. Closing that needs the caller to connect to the address this guard
+// approved (pinned IP + Host header), not to the name. See the note on
+// ssrfBlockReason().
+
+#include <array>
+#include <cstdint>
+#include <memory>
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace svapi::functions {
+
+/// The pieces of an absolute http/https URL that the guard needs.
+struct HttpUrlParts {
+    std::string scheme;  ///< "http" or "https", lower-cased
+    std::string host;    ///< lower-cased; IPv6 literals have the brackets REMOVED
+    int port = 0;        ///< explicit port, else 80/443
+    std::string path;    ///< path plus query and fragment; "/" when absent
+};
+
+/// Parse an absolute http/https URL.
+///
+/// Returns nullopt for anything else: a missing or unknown scheme (file:,
+/// gopher:, dict:, data: ... all of which are classic SSRF escalations), an
+/// empty host, a port that is not 1-65535, an unterminated IPv6 bracket, or a
+/// URL containing control characters (header/request smuggling).
+///
+/// Userinfo ("http://user:pass@host/") is stripped, because the host that gets
+/// classified must be the host that gets connected to.
+///
+/// An IPv6 literal arrives bracketed in a URL ("http://[::1]/") but inet_pton
+/// and getaddrinfo reject brackets, so `host` is stored WITHOUT them and can be
+/// passed straight to either.
+std::optional<HttpUrlParts> parseHttpUrl(const std::string& url);
+
+/// A CIDR range, stored family-tagged with the network address already masked.
+struct CidrRange {
+    bool v4 = true;                       ///< true: IPv4 (first 4 bytes of `addr`)
+    std::array<std::uint8_t, 16> addr{};  ///< network address, host bits zeroed
+    int bits = 0;                         ///< prefix length (0-32 for v4, 0-128 for v6)
+
+    bool isV4() const { return v4; }
+};
+
+/// Parse "10.0.0.0/8", "fc00::/7", or a bare address (treated as a host route,
+/// /32 or /128). Host bits set in the input are masked off rather than rejected,
+/// because "10.1.2.3/8" in a config file means the /8 and must not silently
+/// match nothing.
+std::optional<CidrRange> parseCidr(const std::string& cidr);
+
+/// Is `ip` (a bare IP literal, no brackets) inside `range`?
+///
+/// A family mismatch is simply "not a member", not an error: a blocklist mixes
+/// v4 and v6 ranges and every address is checked against all of them. An
+/// unparseable `ip` is likewise "not a member" here - this function answers only
+/// the membership question. Failing closed on garbage is SsrfPolicy::isBlocked's
+/// job, which is the function callers are supposed to use.
+bool cidrContains(const CidrRange& range, const std::string& ip);
+
+/// A set of blocked CIDR ranges plus the classification rules around it.
+class SsrfPolicy {
+public:
+    /// The built-in blocklist: loopback, RFC1918, link-local (cloud metadata),
+    /// carrier NAT, and the IPv6 equivalents, plus the deprecated IPv6
+    /// transition prefixes that are really just other spellings of an IPv4
+    /// address.
+    static const std::vector<std::string>& defaultBlockedCidrs();
+
+    /// Policy built from the built-in defaults.
+    static SsrfPolicy withDefaults();
+
+    /// Policy built from raw config strings. This REPLACES the defaults rather
+    /// than extending them, so an operator can deliberately widen egress.
+    /// Entries that do not parse are skipped and appended to `invalid` (when
+    /// non-null) so the caller can log them: a typo in the blocklist is a hole
+    /// in the guard and must be visible, not silent.
+    static SsrfPolicy fromStrings(const std::vector<std::string>& cidrs,
+                                  std::vector<std::string>* invalid);
+
+    /// Is this address literal blocked?
+    ///
+    /// Returns true - FAIL CLOSED - when `ip` is not a valid IP literal at all.
+    /// Callers use this as "may I connect here?", so an unparseable answer must
+    /// be "no". Do not change this to return false for unknown input.
+    ///
+    /// An IPv4-mapped IPv6 address (::ffff:127.0.0.1) is additionally checked as
+    /// its embedded IPv4 address; skipping that is the classic way a v4-only
+    /// blocklist gets walked around.
+    bool isBlocked(const std::string& ip) const;
+
+    /// Which range blocks `ip`, as CIDR text, or nullopt when nothing matches.
+    /// Unlike isBlocked() this returns nullopt for an unparseable literal, so
+    /// it is a reporting helper for logs and messages - security decisions go
+    /// through isBlocked(), which fails closed.
+    std::optional<std::string> blockedBy(const std::string& ip) const;
+
+    std::size_t size() const { return ranges_.size(); }
+
+private:
+    std::vector<CidrRange> ranges_;
+};
+
+/// The process-wide policy snapshot. Readers get a shared_ptr they own for the
+/// duration of a run, so a runtime replacement never invalidates a policy a
+/// request is already using and readers are never blocked behind a writer.
+std::shared_ptr<const SsrfPolicy> currentSsrfPolicy();
+
+/// Install a new snapshot (startup, or a settings hot-reload). Passing nullptr
+/// restores the built-in defaults - the cache never ends up empty, because an
+/// empty policy would allow everything.
+void setSsrfPolicy(std::shared_ptr<const SsrfPolicy> policy);
+
+/// Classify `host` (a name or a bare IP literal, no brackets) against `policy`.
+///
+/// Returns nullopt when the destination is allowed, or a human-readable reason
+/// when it is not. A literal IP is classified directly, with no DNS lookup. A
+/// name is resolved with getaddrinfo and EVERY returned address is classified;
+/// one blocked address blocks the host. Resolution failure, or a name that
+/// resolves to nothing, is also blocked (fail closed).
+///
+/// NOTE on TOCTOU: this validates the name, and the HTTP client will resolve it
+/// again. To close the rebinding window the caller should connect to the
+/// approved address rather than re-resolving the name.
+std::optional<std::string> ssrfBlockReason(const std::string& host, const SsrfPolicy& policy);
+
+/// The classification half of ssrfBlockReason, split out so the "check every
+/// address, not just the first" rule is testable without a resolver. `host` is
+/// only used in the message. An empty list is a resolution failure: blocked.
+std::optional<std::string> blockReasonForAddresses(const std::string& host,
+                                                   const std::vector<std::string>& addresses,
+                                                   const SsrfPolicy& policy);
+
+} // namespace svapi::functions

+ 457 - 0
tests/test_functions_net_guard.cpp

@@ -0,0 +1,457 @@
+#include <gtest/gtest.h>
+
+#include "functions/net_guard.hpp"
+
+#include <algorithm>
+#include <atomic>
+#include <memory>
+#include <string>
+#include <thread>
+#include <vector>
+
+using namespace svapi::functions;
+
+// ---------------------------------------------------------------------------
+// parseHttpUrl
+// ---------------------------------------------------------------------------
+
+TEST(ParseHttpUrl, PlainHttpGetsDefaultPortAndRootPath) {
+    auto u = parseHttpUrl("http://example.com");
+    ASSERT_TRUE(u.has_value());
+    EXPECT_EQ(u->scheme, "http");
+    EXPECT_EQ(u->host, "example.com");
+    EXPECT_EQ(u->port, 80);
+    EXPECT_EQ(u->path, "/");
+}
+
+TEST(ParseHttpUrl, HttpsDefaultPort) {
+    auto u = parseHttpUrl("https://example.com/a/b?q=1");
+    ASSERT_TRUE(u.has_value());
+    EXPECT_EQ(u->scheme, "https");
+    EXPECT_EQ(u->port, 443);
+    EXPECT_EQ(u->path, "/a/b?q=1");
+}
+
+TEST(ParseHttpUrl, ExplicitPortWins) {
+    auto u = parseHttpUrl("http://example.com:8080/x");
+    ASSERT_TRUE(u.has_value());
+    EXPECT_EQ(u->port, 8080);
+    EXPECT_EQ(u->host, "example.com");
+    EXPECT_EQ(u->path, "/x");
+}
+
+TEST(ParseHttpUrl, SchemeIsCaseInsensitiveAndNormalised) {
+    auto u = parseHttpUrl("HTTPS://Example.COM/");
+    ASSERT_TRUE(u.has_value());
+    EXPECT_EQ(u->scheme, "https");
+    // The host is lower-cased so the guard and the logs agree on one spelling.
+    EXPECT_EQ(u->host, "example.com");
+}
+
+TEST(ParseHttpUrl, UserinfoIsStrippedFromTheAuthority) {
+    // "http://user:pass@127.0.0.1/" must classify as 127.0.0.1, not as a host
+    // literally named "user:pass@127.0.0.1" that no blocklist would match.
+    auto u = parseHttpUrl("http://user:pass@127.0.0.1/x");
+    ASSERT_TRUE(u.has_value());
+    EXPECT_EQ(u->host, "127.0.0.1");
+    EXPECT_EQ(u->port, 80);
+}
+
+TEST(ParseHttpUrl, BracketedIpv6LiteralHasBracketsStripped) {
+    auto u = parseHttpUrl("http://[::1]/health");
+    ASSERT_TRUE(u.has_value());
+    // Stored unbracketed so it can go straight to inet_pton/getaddrinfo.
+    EXPECT_EQ(u->host, "::1");
+    EXPECT_EQ(u->port, 80);
+    EXPECT_EQ(u->path, "/health");
+}
+
+TEST(ParseHttpUrl, BracketedIpv6LiteralWithPort) {
+    auto u = parseHttpUrl("https://[fe80::1%25eth0]:9443/x");
+    ASSERT_TRUE(u.has_value());
+    EXPECT_EQ(u->host, "fe80::1%25eth0");
+    EXPECT_EQ(u->port, 9443);
+}
+
+TEST(ParseHttpUrl, RejectsNonHttpSchemes) {
+    EXPECT_FALSE(parseHttpUrl("file:///etc/passwd").has_value());
+    EXPECT_FALSE(parseHttpUrl("gopher://127.0.0.1:9004/_").has_value());
+    EXPECT_FALSE(parseHttpUrl("ftp://example.com/x").has_value());
+    EXPECT_FALSE(parseHttpUrl("data:text/plain,hi").has_value());
+    EXPECT_FALSE(parseHttpUrl("dict://127.0.0.1:11211/stat").has_value());
+}
+
+TEST(ParseHttpUrl, RejectsMissingScheme) {
+    EXPECT_FALSE(parseHttpUrl("example.com/x").has_value());
+    EXPECT_FALSE(parseHttpUrl("//example.com/x").has_value());
+    EXPECT_FALSE(parseHttpUrl("/relative/path").has_value());
+}
+
+TEST(ParseHttpUrl, RejectsEmptyHost) {
+    EXPECT_FALSE(parseHttpUrl("http://").has_value());
+    EXPECT_FALSE(parseHttpUrl("http:///path").has_value());
+    EXPECT_FALSE(parseHttpUrl("http://:8080/path").has_value());
+    EXPECT_FALSE(parseHttpUrl("http://[]/path").has_value());
+}
+
+TEST(ParseHttpUrl, RejectsBadPort) {
+    EXPECT_FALSE(parseHttpUrl("http://example.com:0/x").has_value());
+    EXPECT_FALSE(parseHttpUrl("http://example.com:70000/x").has_value());
+    EXPECT_FALSE(parseHttpUrl("http://example.com:abc/x").has_value());
+    EXPECT_FALSE(parseHttpUrl("http://example.com:/x").has_value());
+    EXPECT_FALSE(parseHttpUrl("http://example.com:80x/x").has_value());
+}
+
+TEST(ParseHttpUrl, RejectsUnterminatedIpv6Bracket) {
+    EXPECT_FALSE(parseHttpUrl("http://[::1/x").has_value());
+}
+
+TEST(ParseHttpUrl, RejectsEmptyAndWhitespaceInput) {
+    EXPECT_FALSE(parseHttpUrl("").has_value());
+    EXPECT_FALSE(parseHttpUrl("   ").has_value());
+    // Embedded control characters allow request smuggling against the host's
+    // own parser, so the guard refuses the URL rather than guessing.
+    EXPECT_FALSE(parseHttpUrl("http://exam\r\nple.com/x").has_value());
+    EXPECT_FALSE(parseHttpUrl("http://example.com/x\ny").has_value());
+}
+
+// ---------------------------------------------------------------------------
+// parseCidr / cidrContains
+// ---------------------------------------------------------------------------
+
+TEST(ParseCidr, Ipv4RangeParses) {
+    auto r = parseCidr("10.0.0.0/8");
+    ASSERT_TRUE(r.has_value());
+    EXPECT_TRUE(r->isV4());
+    EXPECT_EQ(r->bits, 8);
+}
+
+TEST(ParseCidr, Ipv6RangeParses) {
+    auto r = parseCidr("fc00::/7");
+    ASSERT_TRUE(r.has_value());
+    EXPECT_FALSE(r->isV4());
+    EXPECT_EQ(r->bits, 7);
+}
+
+TEST(ParseCidr, BareAddressIsAHostRoute) {
+    auto v4 = parseCidr("8.8.8.8");
+    ASSERT_TRUE(v4.has_value());
+    EXPECT_EQ(v4->bits, 32);
+    EXPECT_TRUE(cidrContains(*v4, "8.8.8.8"));
+    EXPECT_FALSE(cidrContains(*v4, "8.8.8.9"));
+
+    auto v6 = parseCidr("::1");
+    ASSERT_TRUE(v6.has_value());
+    EXPECT_EQ(v6->bits, 128);
+}
+
+TEST(ParseCidr, RejectsGarbage) {
+    EXPECT_FALSE(parseCidr("").has_value());
+    EXPECT_FALSE(parseCidr("not-an-ip/8").has_value());
+    EXPECT_FALSE(parseCidr("10.0.0.0/").has_value());
+    EXPECT_FALSE(parseCidr("10.0.0.0/33").has_value());
+    EXPECT_FALSE(parseCidr("10.0.0.0/-1").has_value());
+    EXPECT_FALSE(parseCidr("10.0.0.0/8/8").has_value());
+    EXPECT_FALSE(parseCidr("fc00::/129").has_value());
+    EXPECT_FALSE(parseCidr("10.0.0.0/eight").has_value());
+    EXPECT_FALSE(parseCidr("10.0.0.0/08x").has_value());
+    EXPECT_FALSE(parseCidr("[::1]/128").has_value());
+}
+
+TEST(CidrContains, Ipv4EdgesOfTheRange) {
+    auto r = parseCidr("172.16.0.0/12");
+    ASSERT_TRUE(r.has_value());
+    EXPECT_TRUE(cidrContains(*r, "172.16.0.0"));       // first address
+    EXPECT_TRUE(cidrContains(*r, "172.31.255.255"));   // last address
+    EXPECT_FALSE(cidrContains(*r, "172.15.255.255"));  // one below
+    EXPECT_FALSE(cidrContains(*r, "172.32.0.0"));      // one above
+}
+
+TEST(CidrContains, Ipv4SlashThirtyTwoAndSlashZero) {
+    auto host = parseCidr("192.0.2.5/32");
+    ASSERT_TRUE(host.has_value());
+    EXPECT_TRUE(cidrContains(*host, "192.0.2.5"));
+    EXPECT_FALSE(cidrContains(*host, "192.0.2.6"));
+
+    auto all = parseCidr("0.0.0.0/0");
+    ASSERT_TRUE(all.has_value());
+    EXPECT_TRUE(cidrContains(*all, "8.8.8.8"));
+    EXPECT_TRUE(cidrContains(*all, "255.255.255.255"));
+}
+
+TEST(CidrContains, Ipv6EdgesOfTheRange) {
+    auto r = parseCidr("fe80::/10");
+    ASSERT_TRUE(r.has_value());
+    EXPECT_TRUE(cidrContains(*r, "fe80::"));
+    EXPECT_TRUE(cidrContains(*r, "febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff"));
+    EXPECT_FALSE(cidrContains(*r, "fe7f:ffff:ffff:ffff:ffff:ffff:ffff:ffff"));
+    EXPECT_FALSE(cidrContains(*r, "fec0::"));
+}
+
+TEST(CidrContains, FamilyMismatchIsSimplyNotAMember) {
+    auto v4 = parseCidr("10.0.0.0/8");
+    auto v6 = parseCidr("fc00::/7");
+    ASSERT_TRUE(v4.has_value());
+    ASSERT_TRUE(v6.has_value());
+    EXPECT_FALSE(cidrContains(*v4, "fc00::1"));
+    EXPECT_FALSE(cidrContains(*v6, "10.0.0.1"));
+}
+
+TEST(CidrContains, NonLiteralAddressIsNotAMember) {
+    auto r = parseCidr("10.0.0.0/8");
+    ASSERT_TRUE(r.has_value());
+    // cidrContains answers only the membership question; failing closed on
+    // garbage is SsrfPolicy::isBlocked's job.
+    EXPECT_FALSE(cidrContains(*r, "nonsense"));
+    EXPECT_FALSE(cidrContains(*r, ""));
+}
+
+TEST(CidrContains, HostBitsSetInTheRangeStillMatchTheWholeNetwork) {
+    // "10.1.2.3/8" is sloppy but common in config; treat it as 10.0.0.0/8
+    // rather than silently matching nothing.
+    auto r = parseCidr("10.1.2.3/8");
+    ASSERT_TRUE(r.has_value());
+    EXPECT_TRUE(cidrContains(*r, "10.0.0.1"));
+    EXPECT_TRUE(cidrContains(*r, "10.255.255.254"));
+}
+
+// ---------------------------------------------------------------------------
+// SsrfPolicy
+// ---------------------------------------------------------------------------
+
+TEST(SsrfPolicy, DefaultsBlockEveryDocumentedRange) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    const char* blocked[] = {
+        "127.0.0.1",        // 127.0.0.0/8 loopback
+        "127.255.255.255",
+        "10.1.2.3",         // 10.0.0.0/8
+        "172.16.5.5",       // 172.16.0.0/12
+        "192.168.1.1",      // 192.168.0.0/16
+        "169.254.169.254",  // cloud metadata
+        "0.0.0.0",          // 0.0.0.0/8 "this host"
+        "100.64.0.1",       // carrier NAT
+        "::1",              // IPv6 loopback
+        "fc00::1",          // unique local
+        "fd12:3456::1",     // inside fc00::/7
+        "fe80::1",          // link local
+    };
+    for (const char* ip : blocked) {
+        EXPECT_TRUE(p.isBlocked(ip)) << "should be blocked: " << ip;
+    }
+}
+
+TEST(SsrfPolicy, PublicAddressesAreNotBlocked) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    const char* allowed[] = {
+        "8.8.8.8", "1.1.1.1", "93.184.216.34",
+        "172.15.0.1",   // just below 172.16.0.0/12
+        "172.32.0.1",   // just above
+        "100.63.255.255", "100.128.0.1",
+        "2606:4700:4700::1111",
+        "2001:4860:4860::8888",
+    };
+    for (const char* ip : allowed) {
+        EXPECT_FALSE(p.isBlocked(ip)) << "should be allowed: " << ip;
+    }
+}
+
+TEST(SsrfPolicy, Ipv4MappedIpv6BypassIsCaught) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    // ::ffff:127.0.0.1 is the classic blocklist bypass: an IPv6 literal whose
+    // embedded IPv4 is loopback. It must be classified as its IPv4 address.
+    EXPECT_TRUE(p.isBlocked("::ffff:127.0.0.1"));
+    EXPECT_TRUE(p.isBlocked("::ffff:10.0.0.1"));
+    EXPECT_TRUE(p.isBlocked("::ffff:169.254.169.254"));
+    EXPECT_TRUE(p.isBlocked("::ffff:7f00:1"));   // same address, hex form
+    EXPECT_TRUE(p.isBlocked("::ffff:a00:1"));    // ::ffff:10.0.0.1 in hex
+    // A mapped public address stays reachable - the unwrapping must not block
+    // everything it touches.
+    EXPECT_FALSE(p.isBlocked("::ffff:8.8.8.8"));
+}
+
+TEST(SsrfPolicy, Ipv4CompatibleAndNatSixtyFourLoopbackAreCaught) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    EXPECT_TRUE(p.isBlocked("::127.0.0.1"));      // deprecated v4-compatible form
+    EXPECT_TRUE(p.isBlocked("64:ff9b::7f00:1"));  // NAT64 well-known prefix
+}
+
+TEST(SsrfPolicy, UnspecifiedIpv6AndOtherReservedFormsAreBlocked) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    EXPECT_TRUE(p.isBlocked("::"));
+}
+
+TEST(SsrfPolicy, GarbageInputFailsClosed) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    // Anything that is not a valid IP literal is blocked: a classifier that
+    // cannot parse its input has not proved the destination safe. Do not
+    // "simplify" this to return false.
+    EXPECT_TRUE(p.isBlocked(""));
+    EXPECT_TRUE(p.isBlocked("example.com"));
+    EXPECT_TRUE(p.isBlocked("127.0.0.1.1"));
+    EXPECT_TRUE(p.isBlocked("127.1"));            // short form inet_pton rejects
+    EXPECT_TRUE(p.isBlocked("0x7f.0.0.1"));       // hex-octet obfuscation
+    EXPECT_TRUE(p.isBlocked("2130706433"));       // decimal-integer loopback
+    EXPECT_TRUE(p.isBlocked("[::1]"));            // brackets must be stripped first
+    EXPECT_TRUE(p.isBlocked(" 8.8.8.8"));
+    EXPECT_TRUE(p.isBlocked("8.8.8.8 "));
+}
+
+TEST(SsrfPolicy, EmptyPolicyBlocksNothingValidButStillFailsClosed) {
+    std::vector<std::string> bad;
+    const SsrfPolicy p = SsrfPolicy::fromStrings({}, &bad);
+    EXPECT_TRUE(bad.empty());
+    EXPECT_EQ(p.size(), 0u);
+    EXPECT_FALSE(p.isBlocked("127.0.0.1"));
+    // Even with no ranges, unparseable input is never declared safe.
+    EXPECT_TRUE(p.isBlocked("not-an-ip"));
+}
+
+TEST(SsrfPolicy, FromStringsReportsWhatItCouldNotParse) {
+    std::vector<std::string> bad;
+    const SsrfPolicy p = SsrfPolicy::fromStrings(
+        {"192.0.2.0/24", "junk/8", "fc00::/7", "10.0.0.0/99", "  "}, &bad);
+    EXPECT_EQ(p.size(), 2u);
+    // A blank entry is tolerated (blank lines in config), a malformed one is
+    // reported so the operator can see the hole in his blocklist.
+    ASSERT_EQ(bad.size(), 2u);
+    EXPECT_EQ(bad[0], "junk/8");
+    EXPECT_EQ(bad[1], "10.0.0.0/99");
+    EXPECT_TRUE(p.isBlocked("192.0.2.7"));
+    EXPECT_TRUE(p.isBlocked("fc00::9"));
+    // A custom list replaces the defaults; it does not extend them.
+    EXPECT_FALSE(p.isBlocked("127.0.0.1"));
+}
+
+TEST(SsrfPolicy, FromStringsToleratesSurroundingWhitespaceAndANullReport) {
+    const SsrfPolicy p = SsrfPolicy::fromStrings({" 192.0.2.0/24 ", "bogus"}, nullptr);
+    EXPECT_EQ(p.size(), 1u);
+    EXPECT_TRUE(p.isBlocked("192.0.2.1"));
+}
+
+TEST(SsrfPolicy, DefaultCidrListIsTheDocumentedMinimum) {
+    const auto& d = SsrfPolicy::defaultBlockedCidrs();
+    for (const char* want : {"127.0.0.0/8", "10.0.0.0/8", "172.16.0.0/12",
+                             "192.168.0.0/16", "169.254.0.0/16", "0.0.0.0/8",
+                             "100.64.0.0/10", "::1/128", "fc00::/7", "fe80::/10"}) {
+        EXPECT_NE(std::find(d.begin(), d.end(), std::string(want)), d.end())
+            << "default set is missing " << want;
+    }
+    // Every built-in string must itself parse, or the default policy silently
+    // has a hole in it.
+    for (const auto& s : d) {
+        EXPECT_TRUE(parseCidr(s).has_value()) << "unparseable default: " << s;
+    }
+}
+
+// ---------------------------------------------------------------------------
+// Process-wide policy cache
+// ---------------------------------------------------------------------------
+
+TEST(SsrfPolicyCache, DefaultsToTheBuiltInSet) {
+    auto p = currentSsrfPolicy();
+    ASSERT_TRUE(p != nullptr);
+    EXPECT_TRUE(p->isBlocked("127.0.0.1"));
+}
+
+TEST(SsrfPolicyCache, IsReplaceableAtRuntime) {
+    auto original = currentSsrfPolicy();
+    setSsrfPolicy(std::make_shared<const SsrfPolicy>(
+        SsrfPolicy::fromStrings({"192.0.2.0/24"}, nullptr)));
+    auto replaced = currentSsrfPolicy();
+    EXPECT_TRUE(replaced->isBlocked("192.0.2.1"));
+    EXPECT_FALSE(replaced->isBlocked("127.0.0.1"));
+    // The snapshot a reader already holds keeps working after the swap.
+    EXPECT_TRUE(original->isBlocked("127.0.0.1"));
+    setSsrfPolicy(original);
+    EXPECT_TRUE(currentSsrfPolicy()->isBlocked("127.0.0.1"));
+}
+
+TEST(SsrfPolicyCache, NullReplacementRestoresTheDefaults) {
+    setSsrfPolicy(nullptr);
+    auto p = currentSsrfPolicy();
+    ASSERT_TRUE(p != nullptr);
+    EXPECT_TRUE(p->isBlocked("169.254.169.254"));
+}
+
+TEST(SsrfPolicyCache, ConcurrentReadsAndSwapsAreSafe) {
+    auto original = currentSsrfPolicy();
+    std::atomic<bool> stop{false};
+    std::vector<std::thread> readers;
+    for (int i = 0; i < 4; ++i) {
+        readers.emplace_back([&] {
+            while (!stop.load()) {
+                auto snap = currentSsrfPolicy();
+                ASSERT_TRUE(snap != nullptr);
+                (void)snap->isBlocked("127.0.0.1");
+            }
+        });
+    }
+    for (int i = 0; i < 200; ++i) {
+        setSsrfPolicy(std::make_shared<const SsrfPolicy>(SsrfPolicy::withDefaults()));
+    }
+    stop.store(true);
+    for (auto& t : readers) t.join();
+    setSsrfPolicy(original);
+}
+
+// ---------------------------------------------------------------------------
+// ssrfBlockReason
+// ---------------------------------------------------------------------------
+
+TEST(SsrfBlockReason, LiteralIpIsClassifiedWithoutDns) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    auto why = ssrfBlockReason("127.0.0.1", p);
+    ASSERT_TRUE(why.has_value());
+    EXPECT_NE(why->find("127.0.0.1"), std::string::npos);
+
+    EXPECT_FALSE(ssrfBlockReason("8.8.8.8", p).has_value());
+    EXPECT_FALSE(ssrfBlockReason("2606:4700:4700::1111", p).has_value());
+}
+
+TEST(SsrfBlockReason, MappedLiteralIsBlocked) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    EXPECT_TRUE(ssrfBlockReason("::ffff:127.0.0.1", p).has_value());
+}
+
+TEST(SsrfBlockReason, EmptyHostIsBlocked) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    EXPECT_TRUE(ssrfBlockReason("", p).has_value());
+}
+
+TEST(SsrfBlockReason, LocalhostResolvesAndIsBlocked) {
+    // localhost resolves from /etc/hosts, so this exercises the getaddrinfo
+    // path without needing a network or live DNS.
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    auto why = ssrfBlockReason("localhost", p);
+    ASSERT_TRUE(why.has_value());
+    EXPECT_NE(why->find("localhost"), std::string::npos);
+}
+
+TEST(SsrfBlockReason, UnresolvableHostFailsClosed) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    // ".invalid" is reserved by RFC 2606 and never resolves, so no live DNS is
+    // consulted for a useful answer here. Resolution failure must block, not
+    // allow: an unresolved name has not been proved safe.
+    EXPECT_TRUE(ssrfBlockReason("nx.invalid", p).has_value());
+}
+
+TEST(SsrfBlockReason, EveryResolvedAddressIsClassifiedNotJustTheFirst) {
+    // Multi-A / DNS rebinding bypass: a name whose first address is public and
+    // whose second is internal must still be refused. The resolver is not
+    // involved for literals, so this drives the same classification loop over
+    // an explicit address list.
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    EXPECT_TRUE(blockReasonForAddresses("mixed.example", {"8.8.8.8", "10.0.0.5"}, p).has_value());
+    EXPECT_TRUE(blockReasonForAddresses("mixed.example", {"8.8.8.8", "::1"}, p).has_value());
+    EXPECT_FALSE(blockReasonForAddresses("ok.example", {"8.8.8.8", "1.1.1.1"}, p).has_value());
+    // No addresses at all is a resolution failure: fail closed.
+    EXPECT_TRUE(blockReasonForAddresses("empty.example", {}, p).has_value());
+}
+
+TEST(SsrfBlockReason, ReasonNamesTheOffendingAddressAndRange) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    auto why = blockReasonForAddresses("mixed.example", {"8.8.8.8", "10.0.0.5"}, p);
+    ASSERT_TRUE(why.has_value());
+    EXPECT_NE(why->find("10.0.0.5"), std::string::npos);
+    EXPECT_NE(why->find("mixed.example"), std::string::npos);
+}