Procházet zdrojové kódy

fix: admin is reachable only on its own hostname, keyed on the connection SV-132

Owner's requirement, 2026-11-20: "admin only allowed to be accessed over
hostname using sb-prod-01.smartbotics.ai". Two defects stood in the way and
both were in code I shipped earlier today.

1. THE RECOVERY RULE READ THE HOST HEADER, WHICH THE CALLER CONTROLS. It
treated a bare address or `localhost` in `Host` as the operator's own access,
so an external client could send `Host: 127.0.0.1` to the public address and be
handed the admin surface - the web UI and the docs catalogue - on a deployment
whose entire point is to serve admin on one name. It is now keyed on
`Request::local_addr`, the interface the connection ARRIVED on, which an
outside client cannot forge: there is no route from the internet to our
loopback. `HostRegistry::resolve` goes back to exact-match and nothing else;
the exception lives at the one place that can see a connection.

2. A PROJECT HOSTNAME COULD REACH THE GLOBAL ADMIN ROUTES. Measured by the new
test rather than reasoned about: `/api/v1/keys` answered 200 on a tenant's
hostname, handing the key-management surface to a name meant to serve one
project's data. The old gate only excluded non-`/api/` paths, and the global
routes are under `/api/` too. They are admin-key-gated, so this was not an open
door - but the hostname is supposed to be the NARROWER boundary and was not.

The replacement is a WHITELIST, not a deny-list of the five global routes, and
that choice is load-bearing: a deny-list admits any route added in a later
release the moment the package upgrades, with nobody noticing. Same reasoning
that made the customer-facing nginx mount a whitelist in 0.15.0. The cost is
that a genuinely project-scoped resource added later must be listed here
deliberately, which is the point.

LOOPBACK RESCUES ONLY AN UNKNOWN HOST, narrowed after the first version
overrode everything. A request on loopback carrying a registered PROJECT
hostname is still that project's: the caller said which tenant they meant, and
discarding it would make the local surface behave differently from the public
one, so the two would need separate reasoning - which is how a tenancy rule
ends up tested in a shape nobody ships.

ONE OF MY INTEGRATION ASSERTIONS WAS WRONG AND IS NOW A COMMENT. It demanded
404 for an unregistered Host, from a fixture that connects over loopback -
i.e. testing the public refusal from a local socket, where the documented
answer is 200. It now asserts 200 and says why, with the public case pinned by
the unit test APUBLICAddressIsNOTLoopback where it can actually be measured.
A test that passes for the wrong reason is worse than no test.

Also fixed: a scripted edit of mine spanned two anchors and silently deleted
`mayClaimHostname` between them - the scripted-edit trap this repo already
records. Caught by the linker, restored, and the lesson is that the edit should
have asserted what it was REMOVING, not only what it was replacing.

Falsified both ways: letting every /api/ path through on a project host, and
letting loopback override a resolved name - each turns exactly the intended
test red, the second reporting "a project hostname served ANOTHER project".

1487/1487 serial, zero pending build steps.
fszontagh před 6 dny
rodič
revize
de2e6379dc

+ 15 - 3
api/llms.txt

@@ -54,9 +54,21 @@ not served on a project hostname.
 HOST GATING IS OFF until the deployment names itself (`admin_hostname` or
 `global_hostnames` in global settings). Until then project hostnames are stored
 and inert, and `GET .../settings/hostnames` reports `served: false` so the two
-states are distinguishable. A request whose Host is a bare IP address or
-`localhost` is treated as the admin surface, so configuring a hostname is not a
-one-way door.
+states are distinguishable. A request that ARRIVES ON THE LOOPBACK
+INTERFACE and carries no recognised Host is treated as the admin surface, so
+configuring a hostname is not a one-way door. That is keyed on the connection,
+never on the Host header - an external client can send `Host: 127.0.0.1`, but it
+cannot make its connection arrive on our loopback. Loopback rescues only an
+UNKNOWN host: a request carrying a registered project hostname stays scoped to
+that project even locally.
+
+**A project hostname serves that project and nothing else.** Not merely "no web
+UI": the global routes (`/api/v1/keys`, `/settings`, `/stats`, `/version`,
+`/admin/readonly`) are refused there too. The allowed surface is
+`/api/v1/projects/...`, the short forms under `collections`, `files`,
+`functions`, `relations`, `secrets`, `settings`, plus `/fn/*` and `/healthz`.
+It is a whitelist, so a route added in a later release is NOT exposed on tenant
+hostnames until it is added deliberately.
 
 - `GET /api/v1/projects/{p}/settings/hostnames` (admin) -> `{project, hostnames, served}`
 - `PUT /api/v1/projects/{p}/settings/hostnames` (admin) - body `{"hostnames":[{"host":"...","path_style":"short"|"full"}]}`

+ 3 - 1
src/handlers/function_dispatch.cpp

@@ -250,7 +250,9 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
     {
         const auto reg = d.settings.hostRegistry();
         const bool gatingOn = reg && reg->gating();
-        const HostBinding host = reg ? reg->resolve(req.get_header_value("Host")) : HostBinding{};
+        HostBinding host = reg ? reg->resolve(req.get_header_value("Host")) : HostBinding{};
+        if (gatingOn && host.kind == HostKind::Unknown && isLoopbackAddress(req.local_addr))
+            host = HostBinding{HostKind::Admin, {}, PathStyle::Full};
         if (!resolveProject(project, host, gatingOn).ok) { sendNotFound(res); return; }
     }
 

+ 19 - 16
src/hostnames.cpp

@@ -125,22 +125,28 @@ HostRegistry HostRegistry::build(
     return r;
 }
 
-bool isDirectAddressHost(std::string_view hostHeader) {
-    const std::string h = normaliseHost(hostHeader);
-    if (h.empty()) return false;
-    if (h == "localhost") return true;
-    if (h.front() == '[') return true;               // an IPv6 literal
-    // An IPv4 literal: digits and dots only, and at least one dot. A real
-    // hostname cannot be all-numeric labels, so this cannot shadow a name
-    // somebody registered.
-    bool dot = false;
-    for (const char c : h) {
-        if (c == '.') { dot = true; continue; }
-        if (c < '0' || c > '9') return false;
+bool isLoopbackAddress(std::string_view localAddr) {
+    if (localAddr.empty()) return false;
+    // Exact forms only. No prefix matching: `127.0.0.1.evil.com` is a NAME, and
+    // a prefix test on "127." would also accept a hostname that merely starts
+    // that way if this were ever called with one by mistake.
+    if (localAddr == "::1" || localAddr == "[::1]") return true;
+    if (localAddr == "localhost") return true;
+    // The whole 127/8 range is loopback, not just 127.0.0.1.
+    if (localAddr.rfind("127.", 0) == 0) {
+        // Every remaining character must be a digit or a dot, so this cannot
+        // accept `127.example.com`.
+        for (const char c : localAddr.substr(4))
+            if ((c < '0' || c > '9') && c != '.') return false;
+        return true;
     }
-    return dot;
+    // An IPv4-mapped IPv6 loopback, which is what a dual-stack listener reports
+    // on some systems.
+    if (localAddr == "::ffff:127.0.0.1") return true;
+    return false;
 }
 
+
 HostClaimRefusal mayClaimHostname(
     std::string_view host, std::string_view project, const std::string& adminHost,
     const std::vector<std::string>& globalHosts,
@@ -164,9 +170,6 @@ HostClaimRefusal mayClaimHostname(
 
 HostBinding HostRegistry::resolve(std::string_view hostHeader) const {
     const std::string h = normaliseHost(hostHeader);
-    // The operator's own direct access, so configuring a hostname is not a
-    // one-way door. Checked BEFORE the map so it cannot be shadowed.
-    if (isDirectAddressHost(h)) return HostBinding{HostKind::Admin, {}, PathStyle::Full};
     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

+ 19 - 14
src/hostnames.hpp

@@ -134,22 +134,27 @@ private:
     bool gating_ = false;
 };
 
-/// Is this Host the operator reaching the service DIRECTLY - a bare IP literal
-/// or `localhost` - rather than by any configured name?
+/// Did this request arrive on the LOOPBACK interface?
 ///
-/// SUCH A REQUEST IS TREATED AS THE ADMIN SURFACE, and the reason is recovery:
-/// the moment a deployment names itself, every request carrying any other Host
-/// is refused, including the operator's own session over the address they have
-/// always used. Without this, configuring `admin_hostname` is a one-way door
-/// that can only be undone by editing the database by hand.
+/// Takes the connection's LOCAL address (`httplib::Request::local_addr`), NEVER
+/// the Host header, and that distinction is the whole point.
 ///
-/// It does NOT weaken the tenancy boundary, which is the thing to check before
-/// accepting it: a project hostname is a NAME, and an all-numeric label cannot
-/// be one, so this can never shadow a registered project hostname. What it does
-/// mean is that the admin surface is reachable on the raw address - acceptable
-/// only because this deployment's admin hostname is public by the owner's
-/// decision anyway, and worth revisiting if that ever changes.
-bool isDirectAddressHost(std::string_view hostHeader);
+/// THIS REPLACED A HEADER-BASED RULE THAT WAS WRONG. The first version asked
+/// whether the HOST HEADER was a bare address or `localhost`, and treated that
+/// as the operator's own access. The Host header is caller-controlled, so an
+/// external client could simply send `Host: 127.0.0.1` to the public address
+/// and be handed the admin surface - the web UI and the docs catalogue - on a
+/// deployment whose whole point was to serve admin on one name only. A
+/// connection cannot lie about which interface it arrived on: an outside
+/// client has no route to our loopback.
+///
+/// WHAT IT IS FOR is unchanged: recovery. Once a deployment names itself, every
+/// request carrying any other Host is refused, including the operator's own
+/// session. Without a way back in, configuring `admin_hostname` is a one-way
+/// door undoable only by editing the database by hand. Keyed on the interface,
+/// that way back is reachable only from the box itself - by ssh, which is how
+/// an operator fixing a mistake gets there anyway.
+bool isLoopbackAddress(std::string_view localAddr);
 
 /// The outcome of resolving which project a request is about.
 ///

+ 55 - 10
src/server.cpp

@@ -101,7 +101,19 @@ bool installSniHook(void* ctx) {
 std::string projectFor(ServerDeps& d, const httplib::Request& req, size_t group) {
     const auto reg = d.settings.hostRegistry();
     const bool gatingOn = reg && reg->gating();
-    const HostBinding host = reg ? reg->resolve(req.get_header_value("Host")) : HostBinding{};
+    HostBinding host = reg ? reg->resolve(req.get_header_value("Host")) : HostBinding{};
+    // LOOPBACK RESCUES ONLY AN UNKNOWN HOST. It must not override a name that
+    // resolves: a request on loopback carrying a registered PROJECT hostname is
+    // still that project's, because the caller told us which tenant they meant
+    // and discarding that would make the local surface behave differently from
+    // the public one - the two would then need separate reasoning, which is how
+    // a tenancy rule gets tested in a shape nobody ships.
+    //
+    // What it rescues is the case with no usable name at all: the operator
+    // connecting by address after the deployment named itself. Keyed on the
+    // INTERFACE, not the header, because the header is caller-controlled.
+    if (gatingOn && host.kind == HostKind::Unknown && isLoopbackAddress(req.local_addr))
+        host = HostBinding{HostKind::Admin, {}, PathStyle::Full};
 
     // An absent group is the short form. `req.matches` is sized by the pattern,
     // so a route whose optional project group did not participate yields an
@@ -363,7 +375,9 @@ void ApiServer::registerRoutes() {
         // behind someone else's proxy all send a Host nobody registered, and
         // refusing those would be an outage caused by ADDING a control.
         if (const auto reg = d_.settings.hostRegistry(); reg && reg->gating()) {
-            const HostBinding host = reg->resolve(req.get_header_value("Host"));
+            HostBinding host = reg->resolve(req.get_header_value("Host"));
+            if (host.kind == HostKind::Unknown && isLoopbackAddress(req.local_addr))
+                host = HostBinding{HostKind::Admin, {}, PathStyle::Full};
             if (host.kind == HostKind::Unknown) {
                 // 404, never a redirect and never a fallback to a default
                 // host: an unknown name is not a mistake we can correct for the
@@ -371,14 +385,45 @@ void ApiServer::registerRoutes() {
                 sendJson(res, 404, errorBody("not_found", "no such host"));
                 return httplib::Server::HandlerResponse::Handled;
             }
-            // A project hostname serves the API and functions only. `/healthz`
-            // stays reachable everywhere so an outside monitor needs no
-            // credential and no special name.
-            if (host.kind == HostKind::Project && req.method != "OPTIONS" &&
-                req.path.rfind("/api/", 0) != 0 && req.path.rfind("/fn/", 0) != 0 &&
-                req.path != "/healthz") {
-                sendJson(res, 404, errorBody("not_found", "not served on this host"));
-                return httplib::Server::HandlerResponse::Handled;
+            // A PROJECT HOSTNAME SERVES THAT PROJECT AND NOTHING ELSE.
+            //
+            // Not just "no web UI": the GLOBAL admin routes are under /api/
+            // too, and an earlier version of this gate let them through.
+            // Measured by the test beside it - `/api/v1/keys` answered 200 on a
+            // tenant's hostname, handing the key-management surface to a name
+            // whose whole purpose is to serve one project's data. They are
+            // admin-key-gated, so it was not an open door, but the hostname is
+            // meant to be the narrower boundary and was not.
+            //
+            // A WHITELIST, not a deny-list of the global routes, and that is
+            // the load-bearing choice: a deny-list would admit any route added
+            // in a later release the moment the package upgraded, with nobody
+            // noticing - the same reasoning that made the customer-facing nginx
+            // mount a whitelist. The cost is that a genuinely project-scoped
+            // resource added later must be added here deliberately, which is
+            // the point.
+            if (host.kind == HostKind::Project && req.method != "OPTIONS") {
+                static const char* kProjectResources[] = {
+                    "collections", "files", "functions", "relations", "secrets", "settings",
+                };
+                bool allowed = req.path == "/healthz" || req.path.rfind("/fn/", 0) == 0;
+                if (!allowed && req.path.rfind("/api/v1/projects/", 0) == 0) {
+                    // The full form. WHICH project it names is not decided
+                    // here - projectFor() refuses a mismatch per route, so this
+                    // gate stays about the SURFACE and the tenancy check stays
+                    // in one place.
+                    allowed = true;
+                }
+                if (!allowed && req.path.rfind("/api/v1/", 0) == 0) {
+                    const std::string rest = req.path.substr(8);
+                    const std::string first = rest.substr(0, rest.find('/'));
+                    for (const char* r : kProjectResources)
+                        if (first == r) { allowed = true; break; }
+                }
+                if (!allowed) {
+                    sendJson(res, 404, errorBody("not_found", "not served on this host"));
+                    return httplib::Server::HandlerResponse::Handled;
+                }
             }
         }
 

+ 56 - 2
tests/test_api_integration.cpp

@@ -5287,11 +5287,18 @@ TEST_F(ApiFixture, AProjectHostnameServesItsOWNProjectOnTheSHORTPathAndNOTAnothe
     EXPECT_EQ(shortOnAdmin->status, 404)
         << "a short path on the admin hostname resolved to some project: " << shortOnAdmin->body;
 
-    // (6) AN UNREGISTERED Host is refused outright, with a valid key.
+    // (6) AN UNREGISTERED Host over LOOPBACK is the RECOVERY path and answers
+    // normally - stated rather than asserted the other way, because the fixture
+    // connects over loopback and an assertion of 404 here would be testing the
+    // public behaviour from a local socket. The public refusal is pinned by the
+    // unit test APUBLICAddressIsNOTLoopback, which is where it can be measured.
     auto unknownHost = request("GET", "/api/v1/projects/" + project_ + "/collections", "", "", key,
                                {{"Host", "nobody.example.com"}});
     ASSERT_TRUE(unknownHost);
-    EXPECT_EQ(unknownHost->status, 404) << unknownHost->body;
+    EXPECT_EQ(unknownHost->status, 200)
+        << "loopback is the documented way back in after a deployment names itself; if this "
+           "ever 404s, an operator who mistypes admin_hostname is locked out with no remedy "
+           "but editing the database by hand: " << unknownHost->body;
 
     // (7) THE ADMIN SURFACE IS NARROWER on a project hostname: no web UI, no
     // docs catalogue - the surface withdrawn from the customer-facing name in
@@ -5368,6 +5375,53 @@ TEST_F(ApiFixture, AWildcardAndTheDeploymentsOwnNameAreRefusedWithTHEIROWNSlugs)
         << "a project claiming the admin hostname would be handed the web UI and the docs catalogue";
 }
 
+TEST_F(ApiFixture, TheADMINSurfaceIsReachableOnItsHOSTNAMEAndNotOnAnArbitraryHostHeader) {
+    // THE OWNER'S REQUIREMENT, 2026-11-20: "admin only allowed to be accessed
+    // over hostname using sb-prod-01.smartbotics.ai".
+    //
+    // The first version of the recovery rule read the HOST HEADER and treated a
+    // bare address or `localhost` as the operator's own access. The header is
+    // caller-controlled, so an external client could send `Host: 127.0.0.1` to
+    // the public address and be handed the admin surface. It is now keyed on
+    // the interface the connection ARRIVED on, which cannot be forged from
+    // outside.
+    //
+    // The fixture connects over loopback, so it cannot demonstrate the public
+    // case directly - what it CAN pin is that a forged Host alone does not
+    // confer anything, and that the named admin hostname works. The public case
+    // is covered by the unit test APUBLICAddressIsNOTLoopback.
+    HostGatingGuard guard{port_, adminKey_, project_};
+    ASSERT_EQ(admin().Put("/api/v1/settings",
+        nlohmann::json{{"admin_hostname", "sb-prod-01.smartbotics.ai"}}.dump(),
+        "application/json")->status, 200);
+
+    const std::string key = adminKey_;
+    // The named admin hostname reaches the admin surface.
+    auto named = request("GET", "/api/v1/keys", "", "", key,
+                         {{"Host", "sb-prod-01.smartbotics.ai"}});
+    ASSERT_TRUE(named);
+    EXPECT_EQ(named->status, 200) << named->body;
+
+    // An unregistered Host over LOOPBACK is admin BY DESIGN - that is the
+    // recovery path, and the fixture is on loopback, so this test cannot
+    // demonstrate the public refusal. Saying so here rather than asserting
+    // something that would pass for the wrong reason.
+    //
+    // What IS testable from here, and is the half that matters: loopback does
+    // NOT override a name that resolves. A request carrying a registered
+    // PROJECT hostname stays scoped to that project even on loopback, so the
+    // local surface and the public one follow one rule rather than two.
+    ASSERT_EQ(admin().Put(("/api/v1/projects/" + project_ + "/settings/hostnames").c_str(),
+        nlohmann::json{{"hostnames", {{{"host", "tenant.example.com"}, {"path_style", "short"}}}}}.dump(),
+        "application/json")->status, 200);
+    auto onProjectHost = request("GET", "/api/v1/keys", "", "", key,
+                                 {{"Host", "tenant.example.com"}});
+    ASSERT_TRUE(onProjectHost);
+    EXPECT_EQ(onProjectHost->status, 404)
+        << "a registered PROJECT hostname reached the admin key surface over loopback - the "
+           "loopback rescue is overriding a name that resolves: " << onProjectHost->body;
+}
+
 TEST_F(ApiFixture, TheGlobalStatsRouteSurvivesTheProjectRouteWideningBesideIt) {
     // A REGRESSION TEST FOR A COLLISION CLASS, not for one route.
     //

+ 32 - 30
tests/test_hostnames.cpp

@@ -459,7 +459,7 @@ TEST(MayClaimHostname, TheWriteTimeAnswerAGREESWithTheRegistrysOwnPrecedence) {
 // first customer hostname to a project turned gating on service-wide and
 // answered the operator's own next request with a 404.
 
-using svapi::isDirectAddressHost;
+using svapi::isLoopbackAddress;
 
 TEST(HostGating, APROJECTHostnameAloneDoesNOTTurnGatingOn) {
     // The defect. An admin adding a customer hostname must not lock themselves
@@ -478,38 +478,40 @@ TEST(HostGating, THEDEPLOYMENTNamingItselfIsWhatTurnsGatingOn) {
     EXPECT_FALSE(HostRegistry::build("", {}, {}, nullptr).gating());
 }
 
-TEST(HostGating, ABareAddressOrLocalhostIsTheOPERATORSOwnAccess) {
-    // Recovery: without this, setting admin_hostname is a one-way door that can
-    // only be undone by editing the database by hand.
-    for (const char* h : {"127.0.0.1", "127.0.0.1:8080", "10.0.0.5", "localhost",
-                          "localhost:8080", "[::1]", "[::1]:8080"}) {
-        EXPECT_TRUE(isDirectAddressHost(h)) << h;
-        const HostRegistry r = HostRegistry::build("admin.example.com", {}, {}, nullptr);
-        EXPECT_EQ(r.resolve(h).kind, HostKind::Admin) << h;
-    }
+TEST(HostGating, LoopbackIsRecognisedFromTheCONNECTIONAddress) {
+    // The way back in after a deployment names itself. Keyed on the interface
+    // the connection arrived on, which an outside client cannot forge.
+    for (const char* a : {"127.0.0.1", "127.0.0.53", "::1", "[::1]", "localhost",
+                          "::ffff:127.0.0.1"})
+        EXPECT_TRUE(isLoopbackAddress(a)) << a;
 }
 
-TEST(HostGating, ANameIsNOTADirectAddressHoweverNumericItLooks) {
-    // THE property that makes the recovery rule safe: it must never be able to
-    // shadow a hostname a project registered. A real hostname cannot be all
-    // numeric labels, so the two sets are disjoint by construction rather than
-    // by the order of a lookup.
-    for (const char* h : {"nt.kb.smartbotics.ai", "1.example.com", "123.456.example.com",
-                          "example.com", "v1.2.3.api.example.com"}) {
-        EXPECT_FALSE(isDirectAddressHost(h)) << h;
-    }
-    // And concretely: a project holding a numeric-looking name still gets it.
-    const HostRegistry r = HostRegistry::build(
-        "admin.example.com", {}, {{"novitax", {{"1.example.com", PathStyle::Short}}}}, nullptr);
-    EXPECT_EQ(r.resolve("1.example.com").project, "novitax")
-        << "the direct-address rule shadowed a registered project hostname";
+TEST(HostGating, APUBLICAddressIsNOTLoopback) {
+    // THE test this file exists for now. The previous version of this rule read
+    // the HOST HEADER, so an external client could send `Host: 127.0.0.1` to
+    // the public address and be handed the admin surface - the web UI and the
+    // docs catalogue - on a deployment whose whole point was to serve admin on
+    // one name only.
+    for (const char* a : {"85.155.246.191", "142.93.100.6", "10.0.0.5", "0.0.0.0",
+                          "", "127.example.com", "1270.0.0.1", "::2"})
+        EXPECT_FALSE(isLoopbackAddress(a)) << a << " was treated as loopback";
 }
 
-TEST(HostGating, AShortPathOnTheDirectAddressIsStillREFUSED) {
-    // The direct address is the ADMIN surface, so rule 4 applies to it exactly
-    // as to a named admin host - it is a way back IN, not a way around the
-    // tenancy rules.
+TEST(HostGating, TheREGISTRYNoLongerKnowsAboutAddressesAtAll) {
+    // resolve() is exact-match and nothing else now. A bare address resolves to
+    // Unknown like any unregistered name; the loopback exception lives at the
+    // one place that can see the connection, not in the pure lookup.
     const HostRegistry r = HostRegistry::build("admin.example.com", {}, {}, nullptr);
-    EXPECT_FALSE(resolveProject("", r.resolve("127.0.0.1"), true).ok);
-    EXPECT_TRUE(resolveProject("novitax", r.resolve("127.0.0.1"), true).ok);
+    EXPECT_EQ(r.resolve("127.0.0.1").kind, HostKind::Unknown);
+    EXPECT_EQ(r.resolve("localhost").kind, HostKind::Unknown);
+    EXPECT_EQ(r.resolve("admin.example.com").kind, HostKind::Admin);
+}
+
+TEST(HostGating, AShortPathOnTheLoopbackAdminSurfaceIsStillREFUSED) {
+    // Loopback is a way back IN, not a way around the tenancy rules: it yields
+    // the ADMIN binding, and rule 4 applies to that exactly as to a named admin
+    // host.
+    const HostBinding loopbackAdmin{HostKind::Admin, {}, PathStyle::Full};
+    EXPECT_FALSE(resolveProject("", loopbackAdmin, true).ok);
+    EXPECT_TRUE(resolveProject("novitax", loopbackAdmin, true).ok);
 }