Jelajahi Sumber

feat: resolve which project a hostname names, refusing rather than guessing SV-132

First piece of per-project hostnames (the design is in
docs/superpowers/specs/2026-11-20-hostnames-tls-sni-design.md). Pure, links
only the core, and carries no TLS or routing yet - this is the tenancy
decision on its own, where the care belongs.

A hostname resolves to Admin, Global, Project or Unknown. EXACT MATCH ONLY: no
suffix match, no wildcard, no closest-parent. Each of those would make an
unregistered name resolve to whoever owns something above it, which is the
subdomain-takeover this type exists to refuse.

Three decisions are load-bearing and each has a test that goes red when it is
reverted:

- An UNKNOWN host is Unknown and never a project. Falsified by adding a
  closest-parent fallback: `evil.nt.kb.smartbotics.ai` then resolved to
  novitax, and exactly one test failed, naming the host and the project.
- A DEPLOYMENT name cannot be taken by a project. The admin and global names
  are inserted first, so a project claiming one is dropped. Without the
  precedence a project would have been handed the web UI and the docs
  catalogue - the surface withdrawn from the customer-facing name in 0.15.0
  after five hours.
- A host claimed by TWO projects goes to NEITHER. Falsifying this to
  first-claimant revealed something better than the argument for it: the
  winner was whichever project `unordered_map` iterated first, so
  last-writer-wins is not merely unsafe, it is NONDETERMINISTIC - the same
  stored config could serve a different tenant after a restart. Refusing both
  makes the misconfiguration a 404 on a name nobody can reach, which is
  visible and recoverable.

WILDCARDS ARE REFUSED IN THE REGISTRY, deliberately, and belong only in
certificate selection: `*.example.com` registered by a project would catch
every subdomain nobody had claimed YET, so the boundary would move whenever an
unrelated DNS record appeared. In cert selection a wrong match fails a
handshake; here it would serve data.

`normaliseHost` handles the spellings a caller controls, each an engineered
mismatch otherwise: case (DNS is case-insensitive), the port, an IPv6 literal
(truncating at the first colon turns `[::1]:8080` into `[`), and exactly one
trailing dot (`example.com.` is the same name; `example.com..` is not and must
not be normalised into one).

An empty registry means "no host gating", not "refuse everything". Without
that, shipping this would 404 every request on every existing deployment - an
outage caused by adding a control, which this repo has avoided once before by
defaulting network_egress to allow.

19 new tests, 1429/1429 pass serially, zero pending build steps before ctest.
fszontagh 6 hari lalu
induk
melakukan
ef25781b52

+ 196 - 0
docs/superpowers/specs/2026-11-20-hostnames-tls-sni-design.md

@@ -0,0 +1,196 @@
+# Per-project hostnames, in-process TLS and SNI
+
+Replaces nginx. Lets a project own one or more customer-facing hostnames, with
+the admin surface on a hostname of its own.
+
+Owner's statement of the goal, 2026-11-20: *"vectorapi can handle multiple
+hostnames per project + one for the admin ui, so we can add custom user-facing
+hostnames per project (one or more, or use the global one)"*, and *"on the new
+machine I don't want to migrate with the old setups"* - so this ships BEFORE the
+move, and the new box gets this architecture rather than a copy of the old one.
+
+## What a hostname decides
+
+Three kinds, resolved from the `Host` header:
+
+| kind | serves | project in path |
+|---|---|---|
+| **admin** | everything: `/api/**`, `/fn/**`, the web UI, `/docs`, `/openapi.json` | required |
+| **global** | `/api/**`, `/fn/**`, `/healthz` for every project | required |
+| **project** | `/api/**` and `/fn/**` for THAT project, plus `/healthz` | per-hostname setting |
+| unknown | 404, and never falls through to a project | - |
+
+A project hostname serves no web UI and no `/docs`. That is not tidiness: the
+docs page renders the complete operation list including admin key management and
+project deletion, which is why it was withdrawn from the customer-facing name in
+0.15.0 after five hours. A per-project hostname is a narrower surface than that
+name, so it cannot carry a wider catalogue.
+
+## Path shape: configurable, short by default
+
+A hostname registration carries `path_style`:
+
+- `"short"` (DEFAULT) - `/api/v1/collections/kb/documents`; the project comes
+  from the hostname.
+- `"full"` - `/api/v1/projects/<p>/collections/kb/documents`, and `<p>` MUST
+  equal the hostname's project or the request is **404** (not 403: a project
+  hostname must not confirm that another project exists).
+
+Both shapes are served by ONE route pattern, not two. The project segment becomes
+an optional group, which leaves every later group at the same index:
+
+```
+/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/documents
+  /api/v1/projects/novitax/collections/kb/documents  -> [1]='novitax' [2]='kb'
+  /api/v1/collections/kb/documents                   -> [1]=''        [2]='kb'
+```
+
+Verified with a compiled `std::regex` probe before this was written down, because
+the whole design rests on it and "optional group keeps its index" is exactly the
+sort of thing that is true in one regex flavour and not another.
+
+**Why not rewrite the path at the edge instead.** That was the first design and it
+is impossible: `set_pre_routing_handler` takes `const Request&` in cpp-httplib
+0.59.0, so the path cannot be mutated before routing. Checked, not assumed.
+
+**Why not register two patterns per route.** 32 patterns would become 64, and
+every handler would need to know which form invoked it - a duplicate
+implementation of the one question that must never have two answers. This
+codebase already records what that costs (`unknownKeys()` called in one handler
+while six siblings stayed broken).
+
+## The project is resolved in exactly one place
+
+```cpp
+/// The project this request is about, from the path when present and from the
+/// hostname when not. THE tenancy decision, so it has one implementation.
+std::string projectFor(ServerDeps& d, const httplib::Request& req, size_t group);
+```
+
+Rules, in order:
+1. Path group non-empty + host is a **project** host -> must be equal, else 404.
+2. Path group non-empty + host is admin/global -> use it (today's behaviour).
+3. Path group EMPTY + host is a project host with `short` -> the host's project.
+4. Path group empty, any other case -> **404**. A short path on the global or
+   admin hostname names no project and must not fall back to a default.
+
+Rule 4 is the one that matters. A short path resolving to "some project" on a
+non-project hostname would be a cross-tenant hole wearing routing's clothes.
+
+## Where hostnames are stored
+
+In the per-project settings document (`project_<name>` in `vectorapi_settings`),
+beside the embedding overrides - so they inherit the existing subscribe stream and
+hot-reload with no new machinery:
+
+```json
+{ "hostnames": [ {"host": "nt.kb.smartbotics.ai", "path_style": "short"} ] }
+```
+
+The admin and global hostnames live in the GLOBAL settings document, because they
+are a property of the deployment rather than of a tenant.
+
+A **reverse index** (host -> {project, path_style}) is built when the snapshot is
+swapped, so request-time resolution is a hash lookup and never a scan.
+
+### Collisions are refused at write time, not resolved at read time
+
+`PUT /projects/{p}/settings/hostnames` refuses **422 `hostname_taken`** when
+another project, or the admin/global name, already claims it. Two projects
+claiming one hostname is a cross-tenant exposure, and the last-writer-wins
+resolution a read-time check would give is the worst possible answer.
+
+Admin-only, like the function policy and for the same reason: it decides what a
+tenant can reach.
+
+## TLS and SNI
+
+`ApiServer` holds `httplib::Server` by value today. It becomes
+`std::unique_ptr<httplib::Server>`, constructed as `SSLServer` when TLS is
+configured and `Server` when it is not - so the plain-HTTP path (tests, the
+devstack, a deployment behind someone else's proxy) is unchanged.
+
+`SSLServer(const tls::ContextSetupCallback&)` hands us the context;
+`ctx_t` is a `void*` that is an `SSL_CTX*` under the OpenSSL backend we compile
+with (`HTTPLIB_REQUIRE_OPENSSL ON`). We install
+`SSL_CTX_set_tlsext_servername_callback` and select a certificate per connection.
+
+### Certificates: a directory we watch, never a protocol we implement
+
+vectorapi does NOT speak ACME. An external client (lego / certbot / acme.sh)
+obtains and renews certificates with DNS-01 and writes them to
+`tls.cert_dir`; vectorapi loads what is there and reloads on change.
+
+The reasons are worth keeping: an ACME bug in our process is a live outage on
+every hostname at once; renewal scheduling is somebody else's tested code; and
+account-key handling is a credential we would rather not own. The cost is one
+more moving part in the deployment, which is a better trade than a protocol
+implementation we would maintain forever.
+
+**Wildcards are an OPTIMISATION, not an assumption.** `*.kb.smartbotics.ai`
+covers every project hostname under it, so adding a project hostname usually
+needs no new certificate at all - just a DNS record and a registry entry. But the
+owner's caution stands: *other domains may enter the system*. So selection is
+per-hostname over whatever certificates exist, with wildcard matching as one case
+and an exact match preferred over a wildcard. A hostname with no certificate is a
+refused TLS handshake, logged by name, never a fallback to the wrong certificate.
+
+### Reload must not drop connections
+
+The certificate map is a `shared_ptr<const CertMap>` swapped atomically, exactly
+as `SettingsStore` and `KeyStore` already do. The SNI callback reads the snapshot
+it was handed. Renewal every ~60 days across many hostnames makes reload routine
+rather than exceptional, so it has to be boring.
+
+## What else nginx was doing
+
+| nginx job | replacement |
+|---|---|
+| port 80 -> 443 redirect | vectorapi listens on 80 and redirects (except `/.well-known/acme-challenge/`, kept for HTTP-01 if ever needed) |
+| catch-all for an unknown Host | 404 from vectorapi, never falling through to a project |
+| whitelist on the customer name | the hostname kind table above, which is strictly narrower |
+| branded error pages | **lost, unavoidably** - see below |
+
+**The branded 502 cannot be replaced and that is a real cost.** With no proxy,
+when vectorapi is down there is nothing left to serve a friendly page: the
+connection is simply refused. Removing the proxy removes the only thing that was
+still standing in the case the page existed for. Stated plainly so nobody
+discovers it during an incident.
+
+## Testing
+
+Pure where it can be, because the tenancy decision must be testable without a
+socket:
+
+- `hostnames.hpp` - the reverse index and `resolveHost()`, pure. Unit-tested for:
+  exact match, wildcard match, unknown host, a project host with `full` whose
+  path names a different project (404), a short path on the global host (404).
+- `projectFor()` - the four rules above, each with its own test, and a
+  **falsification**: making rule 4 fall back to a default must turn the
+  cross-tenant test red.
+- Integration: two hostnames on one server, asserting a project host cannot read
+  another project AND that the admin host still can - the pairing, because a test
+  that only asserts refusal would pass against a server that refused everything.
+- TLS: an SNI handshake selecting between two certificates, plus a hostname with
+  no certificate being refused rather than served the wrong one.
+
+## Staging
+
+1. **Hostname registry + `projectFor()` + route widening**, still behind
+   whatever terminates TLS today. Fully testable, no TLS risk.
+2. **TLS + SNI in vectorapi**, plumbing only; certificates from a directory.
+3. **Deploy the new VM with this architecture**, no nginx.
+
+Stage 1 carries the tenancy boundary and is where the care goes. Stage 2 is
+plumbing on a library feature we have verified exists. Stage 3 is the move the
+owner wants done last.
+
+## Open questions
+
+- Should the admin hostname be reachable publicly at all, or bound to a VPN
+  interface? The web UI is the whole admin surface and today it sits behind a
+  hostname anyone can resolve.
+- Does a project hostname interact with a key's Origin allow-list? They are
+  different axes (who may call vs which browser origin), and conflating them
+  would repeat the collections-listing bug where one check was skipped because a
+  sibling appeared to cover it.

+ 1 - 0
src/CMakeLists.txt

@@ -7,6 +7,7 @@ add_library(vectorapi_core STATIC
     json_http.cpp
     filters.cpp
     client_ip.cpp
+    hostnames.cpp
     access_log.cpp
     request_trace.cpp
     vector_search.cpp

+ 134 - 0
src/hostnames.cpp

@@ -0,0 +1,134 @@
+#include "hostnames.hpp"
+
+#include <algorithm>
+#include <cctype>
+
+namespace svapi {
+namespace {
+
+char lower(char c) { return static_cast<char>(std::tolower(static_cast<unsigned char>(c))); }
+
+} // namespace
+
+std::string normaliseHost(std::string_view h) {
+    // Trim surrounding whitespace: a header value legitimately carries OWS.
+    while (!h.empty() && (h.front() == ' ' || h.front() == '\t')) h.remove_prefix(1);
+    while (!h.empty() && (h.back() == ' ' || h.back() == '\t')) h.remove_suffix(1);
+
+    // Strip the port. An IPv6 literal is bracketed and its address contains
+    // colons, so the port can only be what follows the CLOSING bracket -
+    // truncating at the first colon would turn `[::1]:8080` into `[`.
+    if (!h.empty() && h.front() == '[') {
+        const std::size_t close = h.find(']');
+        if (close != std::string_view::npos) {
+            h = h.substr(0, close + 1);  // keep the brackets; they are the literal
+        }
+    } else {
+        const std::size_t colon = h.find(':');
+        if (colon != std::string_view::npos) h = h.substr(0, colon);
+    }
+
+    // One trailing dot: `example.com.` is the fully-qualified spelling of the
+    // same name. Only one, so a pathological `example..` stays distinct and
+    // simply never matches anything rather than being normalised into a name
+    // somebody registered.
+    if (h.size() > 1 && h.back() == '.') h.remove_suffix(1);
+
+    std::string out(h);
+    std::transform(out.begin(), out.end(), out.begin(), lower);
+    return out;
+}
+
+bool validHostname(std::string_view host) {
+    if (host.empty() || host.size() > 253) return false;
+    // No wildcard, no scheme, no path, no port, no userinfo - a project
+    // registers a NAME, and every one of these would make the stored value mean
+    // something other than what the reader assumes.
+    for (const char c : host) {
+        const bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
+                        (c >= '0' && c <= '9') || c == '-' || c == '.';
+        if (!ok) return false;
+    }
+    // Label rules, enough to refuse the shapes that would confuse a comparison
+    // rather than to fully implement RFC 1035: no empty label (so no `a..b` and
+    // no leading or trailing dot), and no label starting or ending with '-'.
+    std::size_t start = 0;
+    while (start <= host.size()) {
+        const std::size_t dot = host.find('.', start);
+        const std::string_view label =
+            host.substr(start, dot == std::string_view::npos ? std::string_view::npos : dot - start);
+        if (label.empty() || label.size() > 63) return false;
+        if (label.front() == '-' || label.back() == '-') return false;
+        if (dot == std::string_view::npos) break;
+        start = dot + 1;
+    }
+    // At least one dot: a single-label name is a local alias, and registering
+    // one would make an intranet hostname resolve to a tenant.
+    return host.find('.') != std::string_view::npos;
+}
+
+HostRegistry HostRegistry::build(
+    const std::string& adminHost, const std::vector<std::string>& globalHosts,
+    const std::unordered_map<std::string, std::vector<HostEntry>>& byProject,
+    std::vector<std::string>* droppedOut) {
+    HostRegistry r;
+    const auto drop = [&](const std::string& h) {
+        if (droppedOut) droppedOut->push_back(h);
+    };
+
+    // The deployment's own names FIRST, so a project can never take one. See
+    // the header: the only safe resolution of that collision is the one that
+    // cannot hand an operator surface to a tenant.
+    if (!adminHost.empty()) {
+        const std::string h = normaliseHost(adminHost);
+        if (!h.empty()) r.map_[h] = HostBinding{HostKind::Admin, {}, PathStyle::Full};
+    }
+    for (const std::string& g : globalHosts) {
+        const std::string h = normaliseHost(g);
+        if (h.empty()) continue;
+        if (r.map_.count(h) != 0) { drop(h); continue; }  // already the admin name
+        r.map_[h] = HostBinding{HostKind::Global, {}, PathStyle::Full};
+    }
+
+    // Projects. A hostname claimed twice is removed from BOTH claimants, so the
+    // failure is "nobody can reach that name" rather than "the wrong tenant
+    // answers on it". Collected first and applied after, because the second
+    // claimant has to be able to retract the first.
+    std::unordered_map<std::string, std::string> claimant;  // host -> project
+    std::unordered_map<std::string, HostBinding> candidate;
+    std::vector<std::string> contested;
+    for (const auto& [project, entries] : byProject) {
+        for (const HostEntry& e : entries) {
+            const std::string h = normaliseHost(e.host);
+            if (h.empty() || !validHostname(h)) { drop(e.host); continue; }
+            if (r.map_.count(h) != 0) { drop(h); continue; }  // a deployment name
+            const auto it = claimant.find(h);
+            if (it != claimant.end()) {
+                if (it->second != project) contested.push_back(h);
+                // Same project listing one host twice is harmless; keep the
+                // first and say nothing.
+                continue;
+            }
+            claimant.emplace(h, project);
+            candidate[h] = HostBinding{HostKind::Project, project, e.pathStyle};
+        }
+    }
+    for (const std::string& h : contested) {
+        candidate.erase(h);
+        drop(h);
+    }
+    for (auto& [h, b] : candidate) r.map_.emplace(h, std::move(b));
+    return r;
+}
+
+HostBinding HostRegistry::resolve(std::string_view hostHeader) const {
+    const std::string h = normaliseHost(hostHeader);
+    const auto it = map_.find(h);
+    // EXACT MATCH ONLY. No suffix match, no wildcard, no "closest parent": each
+    // of those would make an unregistered name resolve to whoever owns
+    // something above it, which is precisely the fallback this type refuses.
+    if (it == map_.end()) return HostBinding{};
+    return it->second;
+}
+
+} // namespace svapi

+ 129 - 0
src/hostnames.hpp

@@ -0,0 +1,129 @@
+#pragma once
+
+#include <memory>
+#include <string>
+#include <string_view>
+#include <unordered_map>
+#include <vector>
+
+/// Which deployment surface a request's `Host` names, and which project it is
+/// about.
+///
+/// THIS IS A TENANCY BOUNDARY, not routing. A hostname that resolves to the
+/// wrong project hands one customer another customer's data, which is the worst
+/// failure this service has - so everything here is pure, exactly-matched, and
+/// refuses rather than guesses. The shape to keep in mind is the one this
+/// codebase has met before: `_files` is a pseudo-collection because a scope rule
+/// answers "may this principal touch that data", and a collection name is
+/// project-qualified because the separator decides whose row it is. A hostname
+/// is the same kind of thing wearing routing's clothes.
+namespace svapi {
+
+/// What a hostname is allowed to serve.
+enum class HostKind {
+    /// Not registered. 404, and NEVER a fallback to a project: an unknown host
+    /// resolving to "some project" is the hole this whole file exists to close.
+    Unknown,
+    /// The operator surface: every route, every project, plus the web UI and
+    /// the docs page.
+    Admin,
+    /// Every project's API and functions, project named in the path. What the
+    /// single customer-facing hostname does today.
+    Global,
+    /// Exactly one project's API and functions. No web UI, no docs.
+    Project,
+};
+
+/// Whether a project hostname expects the project in the path.
+enum class PathStyle {
+    /// `/api/v1/collections/...` - the project comes from the hostname.
+    /// The default, because a customer-facing hostname saying its own tenant's
+    /// name back to it is noise.
+    Short,
+    /// `/api/v1/projects/<p>/collections/...`, and `<p>` must be this
+    /// hostname's project.
+    Full,
+};
+
+struct HostBinding {
+    HostKind kind = HostKind::Unknown;
+    /// Set only when `kind == Project`.
+    std::string project;
+    /// Meaningful only when `kind == Project`.
+    PathStyle pathStyle = PathStyle::Short;
+};
+
+/// One registered hostname, as stored in settings.
+struct HostEntry {
+    std::string host;
+    PathStyle pathStyle = PathStyle::Short;
+};
+
+/// Lowercase, strip the port, strip one trailing dot.
+///
+/// The `Host` header is caller-controlled, so every normalisation here is a
+/// place a mismatch could be engineered:
+///   - CASE: DNS is case-insensitive, so `NT.KB.example` and `nt.kb.example`
+///     are one name. Comparing raw would let a caller miss a registry entry
+///     (harmless) or, with a sloppier comparison elsewhere, hit the wrong one.
+///   - PORT: `example:8443` is the same host as `example`. A deployment serving
+///     a non-443 port would otherwise register one spelling and receive the
+///     other.
+///   - IPv6: `[::1]:8080` keeps its brackets and loses only the port - the
+///     colons inside the brackets are part of the address, so a naive
+///     "truncate at the first colon" turns `[::1]` into `[`.
+///   - TRAILING DOT: `example.` is the fully-qualified spelling of `example`
+///     and resolves identically, so a client using it must not miss.
+std::string normaliseHost(std::string_view hostHeader);
+
+/// Host -> binding. Immutable once built; swapped as a whole under a
+/// `shared_ptr`, the same discipline SettingsStore and KeyStore use, so a
+/// reload cannot be observed half-applied by a request in flight.
+class HostRegistry {
+public:
+    HostRegistry() = default;
+
+    /// Build from the deployment's own names plus every project's.
+    ///
+    /// PRECEDENCE IS FIXED AND ADMIN WINS. If a project claims a hostname the
+    /// deployment already uses, the deployment keeps it and the project's claim
+    /// is dropped. That can only happen if a collision slipped past the
+    /// write-time check (an older row, a hand-edited document), and the safe
+    /// resolution is the one that cannot hand an operator surface to a tenant.
+    /// The admin/global names are checked first for the same reason.
+    ///
+    /// A hostname claimed by two PROJECTS is dropped from BOTH rather than
+    /// given to either. Last-writer-wins would silently move a tenancy
+    /// boundary; refusing both makes the misconfiguration visible as a 404 on a
+    /// name nobody can reach, which is recoverable, where serving the wrong
+    /// tenant is not.
+    static HostRegistry build(const std::string& adminHost,
+                              const std::vector<std::string>& globalHosts,
+                              const std::unordered_map<std::string, std::vector<HostEntry>>& byProject,
+                              std::vector<std::string>* droppedOut = nullptr);
+
+    /// The binding for a `Host` header value. Normalises first.
+    HostBinding resolve(std::string_view hostHeader) const;
+
+    /// True when nothing is registered at all - the ordinary case for a
+    /// deployment behind someone else's proxy, and the signal to skip host
+    /// gating entirely rather than 404 every request.
+    bool empty() const { return map_.empty(); }
+
+    std::size_t size() const { return map_.size(); }
+
+private:
+    std::unordered_map<std::string, HostBinding> map_;
+};
+
+/// Is this a hostname a project may register?
+///
+/// Deliberately strict, and WILDCARDS ARE REFUSED. A project registering
+/// `*.example.com` would catch every subdomain nobody had claimed yet,
+/// including ones a later project expects to own - a tenancy boundary that
+/// moves when an unrelated DNS record appears. Wildcards belong in CERTIFICATE
+/// selection, where matching the wrong one fails the handshake, not in the
+/// registry, where matching the wrong one serves data.
+bool validHostname(std::string_view host);
+
+} // namespace svapi

+ 6 - 0
tests/CMakeLists.txt

@@ -37,6 +37,12 @@ add_executable(test_client_ip test_client_ip.cpp)
 target_link_libraries(test_client_ip PRIVATE vectorapi_core GTest::gtest_main)
 gtest_discover_tests(test_client_ip)
 
+# Hostname resolution is PURE and links only the core: the tenancy decision must
+# be testable without a socket, a database or a certificate.
+add_executable(test_hostnames test_hostnames.cpp)
+target_link_libraries(test_hostnames PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_hostnames)
+
 add_executable(test_filters test_filters.cpp)
 target_link_libraries(test_filters PRIVATE vectorapi_core GTest::gtest_main)
 gtest_discover_tests(test_filters)

+ 216 - 0
tests/test_hostnames.cpp

@@ -0,0 +1,216 @@
+// Hostname resolution: which surface a `Host` names and whose project it is.
+//
+// This is a TENANCY BOUNDARY, so almost every test below is about what must NOT
+// resolve. A test suite for this that only checked the happy path would pass
+// just as well against a registry that answered "the first project it could
+// find" for every unknown name - which is the single failure that matters.
+#include <gtest/gtest.h>
+
+#include "hostnames.hpp"
+
+using svapi::HostBinding;
+using svapi::HostEntry;
+using svapi::HostKind;
+using svapi::HostRegistry;
+using svapi::normaliseHost;
+using svapi::PathStyle;
+using svapi::validHostname;
+
+namespace {
+
+HostRegistry twoTenants(std::vector<std::string>* dropped = nullptr) {
+    return HostRegistry::build(
+        "admin.smartbotics.ai", {"global-api-01.smartbotics.ai"},
+        {{"novitax", {{"nt.kb.smartbotics.ai", PathStyle::Short}}},
+         {"justice-pa", {{"pa.smartbotics.ai", PathStyle::Full},
+                         {"assistant.smartbotics.ai", PathStyle::Short}}}},
+        dropped);
+}
+
+} // namespace
+
+// --- normalisation: every arm is a spelling a caller controls ----------------
+
+TEST(NormaliseHost, LowercasesBecauseDnsIsCaseInsensitive) {
+    EXPECT_EQ(normaliseHost("NT.KB.Smartbotics.AI"), "nt.kb.smartbotics.ai");
+}
+
+TEST(NormaliseHost, StripsThePort) {
+    EXPECT_EQ(normaliseHost("example.com:8443"), "example.com");
+    EXPECT_EQ(normaliseHost("example.com:443"), "example.com");
+}
+
+TEST(NormaliseHost, AnIPv6LiteralKeepsItsAddressAndLosesOnlyThePort) {
+    // The trap: truncating at the FIRST colon turns `[::1]:8080` into `[`,
+    // which then matches nothing - or worse, matches a registry entry somebody
+    // created by pasting a bracket.
+    EXPECT_EQ(normaliseHost("[::1]:8080"), "[::1]");
+    EXPECT_EQ(normaliseHost("[2001:db8::5]"), "[2001:db8::5]");
+    EXPECT_EQ(normaliseHost("[2001:DB8::5]:443"), "[2001:db8::5]");
+}
+
+TEST(NormaliseHost, StripsExactlyOneTrailingDot) {
+    // `example.com.` is the fully-qualified spelling and resolves identically,
+    // so a client using it must not miss.
+    EXPECT_EQ(normaliseHost("example.com."), "example.com");
+    // But only one: `example.com..` is not a name anybody registered, and
+    // normalising it would invent a match.
+    EXPECT_EQ(normaliseHost("example.com.."), "example.com.");
+}
+
+TEST(NormaliseHost, TrimsTheOptionalWhitespaceAHeaderMayCarry) {
+    EXPECT_EQ(normaliseHost("  example.com\t"), "example.com");
+}
+
+// --- what a project may register --------------------------------------------
+
+TEST(ValidHostname, RefusesAWildcardOutright) {
+    // THE one that matters. `*.smartbotics.ai` would catch every subdomain
+    // nobody had claimed YET, so a tenancy boundary would move whenever an
+    // unrelated DNS record appeared. Wildcards belong in certificate selection,
+    // where the wrong match fails a handshake rather than serving data.
+    EXPECT_FALSE(validHostname("*.smartbotics.ai"));
+    EXPECT_FALSE(validHostname("*"));
+    EXPECT_FALSE(validHostname("nt.*.smartbotics.ai"));
+}
+
+TEST(ValidHostname, RefusesAnythingThatIsNotJustAName) {
+    EXPECT_FALSE(validHostname("https://nt.kb.smartbotics.ai"));
+    EXPECT_FALSE(validHostname("nt.kb.smartbotics.ai/admin"));
+    EXPECT_FALSE(validHostname("nt.kb.smartbotics.ai:8443"));
+    EXPECT_FALSE(validHostname("user@nt.kb.smartbotics.ai"));
+    EXPECT_FALSE(validHostname("nt kb.smartbotics.ai"));
+}
+
+TEST(ValidHostname, RefusesASingleLabelSoAnIntranetAliasCannotBecomeATenant) {
+    EXPECT_FALSE(validHostname("localhost"));
+    EXPECT_FALSE(validHostname("api"));
+    EXPECT_TRUE(validHostname("api.example.com"));
+}
+
+TEST(ValidHostname, RefusesMalformedLabels) {
+    EXPECT_FALSE(validHostname(""));
+    EXPECT_FALSE(validHostname(".example.com"));
+    EXPECT_FALSE(validHostname("example.com."));   // normalise first, then validate
+    EXPECT_FALSE(validHostname("a..b.com"));
+    EXPECT_FALSE(validHostname("-bad.example.com"));
+    EXPECT_FALSE(validHostname("bad-.example.com"));
+    EXPECT_FALSE(validHostname(std::string(254, 'a') + ".com"));
+}
+
+// --- resolution -------------------------------------------------------------
+
+TEST(HostRegistry, ResolvesEachKind) {
+    const HostRegistry r = twoTenants();
+    EXPECT_EQ(r.resolve("admin.smartbotics.ai").kind, HostKind::Admin);
+    EXPECT_EQ(r.resolve("global-api-01.smartbotics.ai").kind, HostKind::Global);
+
+    const HostBinding nt = r.resolve("nt.kb.smartbotics.ai");
+    EXPECT_EQ(nt.kind, HostKind::Project);
+    EXPECT_EQ(nt.project, "novitax");
+    EXPECT_EQ(nt.pathStyle, PathStyle::Short) << "short is the default shape";
+
+    const HostBinding pa = r.resolve("pa.smartbotics.ai");
+    EXPECT_EQ(pa.project, "justice-pa");
+    EXPECT_EQ(pa.pathStyle, PathStyle::Full) << "the per-hostname setting is honoured";
+}
+
+TEST(HostRegistry, OneProjectMayHoldSeveralHostnames) {
+    const HostRegistry r = twoTenants();
+    EXPECT_EQ(r.resolve("pa.smartbotics.ai").project, "justice-pa");
+    EXPECT_EQ(r.resolve("assistant.smartbotics.ai").project, "justice-pa");
+}
+
+TEST(HostRegistry, AnUnknownHostIsUNKNOWNAndNEVERAProject) {
+    // The failure this file exists to prevent. Note the second and third cases:
+    // a SUFFIX of a registered name and a PARENT of one must both miss, because
+    // a closest-parent match would hand every unclaimed subdomain to whoever
+    // owns something above it.
+    const HostRegistry r = twoTenants();
+    for (const char* h : {"nobody.example.com", "kb.smartbotics.ai", "smartbotics.ai",
+                          "evil.nt.kb.smartbotics.ai", "nt.kb.smartbotics.ai.evil.com", ""}) {
+        const HostBinding b = r.resolve(h);
+        EXPECT_EQ(b.kind, HostKind::Unknown) << h;
+        EXPECT_TRUE(b.project.empty()) << h << " resolved to project '" << b.project << "'";
+    }
+}
+
+TEST(HostRegistry, ResolutionIsCaseAndPortInsensitive) {
+    const HostRegistry r = twoTenants();
+    EXPECT_EQ(r.resolve("NT.KB.SMARTBOTICS.AI:8443").project, "novitax");
+    EXPECT_EQ(r.resolve("nt.kb.smartbotics.ai.").project, "novitax");
+}
+
+// --- collisions: the two directions, and they resolve differently -----------
+
+TEST(HostRegistry, ADeploymentNameCANNOTBeTakenByAProject) {
+    // A project claiming the admin hostname would hand it the web UI and the
+    // docs catalogue. The deployment keeps its name; the claim is dropped.
+    std::vector<std::string> dropped;
+    const HostRegistry r = HostRegistry::build(
+        "admin.smartbotics.ai", {"global.smartbotics.ai"},
+        {{"evil", {{"admin.smartbotics.ai", PathStyle::Short},
+                   {"global.smartbotics.ai", PathStyle::Short}}}},
+        &dropped);
+    EXPECT_EQ(r.resolve("admin.smartbotics.ai").kind, HostKind::Admin);
+    EXPECT_EQ(r.resolve("global.smartbotics.ai").kind, HostKind::Global);
+    EXPECT_TRUE(r.resolve("admin.smartbotics.ai").project.empty());
+    EXPECT_EQ(dropped.size(), 2u) << "both claims reported, so the operator can see them";
+}
+
+TEST(HostRegistry, AHostClaimedByTWOProjectsGoesToNEITHER) {
+    // Last-writer-wins would move a tenancy boundary silently. Refusing both
+    // makes it a 404 on a name nobody can reach - visible, and recoverable.
+    std::vector<std::string> dropped;
+    const HostRegistry r = HostRegistry::build(
+        "admin.example.com", {},
+        {{"alpha", {{"shared.example.com", PathStyle::Short}}},
+         {"beta", {{"shared.example.com", PathStyle::Short}}}},
+        &dropped);
+    const HostBinding b = r.resolve("shared.example.com");
+    EXPECT_EQ(b.kind, HostKind::Unknown);
+    EXPECT_TRUE(b.project.empty()) << "contested host served '" << b.project << "'";
+    EXPECT_EQ(dropped.size(), 1u);
+}
+
+TEST(HostRegistry, OneProjectListingTheSameHostTwiceIsHarmless) {
+    const HostRegistry r = HostRegistry::build(
+        "admin.example.com", {},
+        {{"alpha", {{"a.example.com", PathStyle::Short}, {"A.example.com.", PathStyle::Full}}}},
+        nullptr);
+    // Kept, and the FIRST entry's style wins - stated by a test so a later
+    // change to "last wins" is a deliberate decision rather than a surprise.
+    const HostBinding b = r.resolve("a.example.com");
+    EXPECT_EQ(b.project, "alpha");
+    EXPECT_EQ(b.pathStyle, PathStyle::Short);
+}
+
+TEST(HostRegistry, AnInvalidRegisteredHostIsDroppedRatherThanStored) {
+    std::vector<std::string> dropped;
+    const HostRegistry r = HostRegistry::build(
+        "admin.example.com", {},
+        {{"alpha", {{"*.example.com", PathStyle::Short}, {"localhost", PathStyle::Short}}}},
+        &dropped);
+    EXPECT_EQ(r.resolve("*.example.com").kind, HostKind::Unknown);
+    EXPECT_EQ(r.resolve("anything.example.com").kind, HostKind::Unknown)
+        << "a stored wildcard must not have become a live wildcard";
+    EXPECT_EQ(dropped.size(), 2u);
+}
+
+// --- empty: the ordinary case for a deployment behind someone else's proxy ---
+
+TEST(HostRegistry, NoHostnamesConfiguredMeansEmptyNotEverythingRefused) {
+    // The signal to skip host gating entirely. Without this, adding the feature
+    // would 404 every request on every existing deployment - an outage caused
+    // by shipping a control, which this codebase has done once already
+    // (network_egress defaulting to deny would have done exactly that).
+    const HostRegistry r = HostRegistry::build("", {}, {}, nullptr);
+    EXPECT_TRUE(r.empty());
+    EXPECT_EQ(r.resolve("anything.example.com").kind, HostKind::Unknown);
+}
+
+TEST(HostRegistry, SizeCountsEveryRegisteredName) {
+    const HostRegistry r = twoTenants();
+    EXPECT_EQ(r.size(), 5u) << "admin + global + 3 project hostnames";
+    EXPECT_FALSE(r.empty());
+}