Browse Source

feat: store per-project hostnames and keep the registry current SV-132

Second piece of #132. Hostnames now live in the per-project settings document
beside the embedding overrides, and the deployment's own names live in the
global one. The registry is rebuilt and swapped whenever either snapshot moves.

WHY THE PER-PROJECT DOCUMENT rather than a collection of its own: that document
already rides a subscribe stream, so a hostname added through the API reaches
the next request with no restart and no new machinery - the same mechanism an
embedding override uses.

THE REGISTRY IS REBUILT AT BOTH SWAP POINTS, and missing one is the entire
failure mode: a project adds a hostname, the project map swaps, and the registry
goes on answering from the global settings it was built with - a hostname that
exists in the stored document and 404s on the wire, with nothing connecting the
two. So `setSnapshot` and `reloadProjectsFromDb` both call it, under the lock
they already hold, and the registry is handed out as an immutable snapshot:
the half-applied state of a tenancy map is "this name belongs to nobody" for
some names and "to the previous owner" for others.

EVERY DROPPED HOSTNAME IS LOGGED BY NAME. A collision or a malformed entry is
otherwise completely silent, and this repo has twice paid for a refusal that
left no record - a three-day 403 only the access log knew about, and one failed
insert whose cause could not be closed at all.

BOTH DEPLOYMENT NAMES EMPTY MEANS HOST GATING IS OFF, and that is the default.
The test fixture, the devstack and any deployment behind someone else's proxy
all send a Host nobody registered; refusing those would be an outage caused by
ADDING a control, which `network_egress` defaulting to allow already avoided
once.

Serialisation decisions, each with a test that goes red when reverted:
- `hostnames` is always an ARRAY, even when empty, so "no hostnames" and "a
  server that does not know about hostnames" cannot look the same. Falsified by
  omitting the key when empty.
- The per-hostname style survives the round trip. Falsified by always writing
  "short": without it every hostname silently becomes the default shape after a
  restart.
- An UNKNOWN style reads as short rather than failing, because a document
  written by a newer server must not take a project offline - the same rule the
  function descriptor follows for an unknown key.
- A malformed entry is skipped without losing the rest of the document, so a
  typo in one hostname cannot cost a project its embedding overrides. Two layers
  refuse a bad name deliberately: this one protects the other settings, and
  hostnames.hpp stops it ever resolving.

5 new tests (24 in the file), 1434/1434 pass serially, zero pending build steps.
fszontagh 6 days ago
parent
commit
2f03888664
6 changed files with 184 additions and 0 deletions
  1. 37 0
      src/project_settings.cpp
  2. 16 0
      src/project_settings.hpp
  3. 14 0
      src/settings.hpp
  4. 37 0
      src/settings_store.cpp
  5. 16 0
      src/settings_store.hpp
  6. 64 0
      tests/test_hostnames.cpp

+ 37 - 0
src/project_settings.cpp

@@ -26,6 +26,34 @@ ProjectSettings ProjectSettings::fromJson(const nlohmann::json& j) {
     // seeds both. The per-kind keys are read afterwards and win, which is what
     // lets a document written by a newer server still be understood when only
     // one kind is capped.
+    // Hostnames. A malformed entry is SKIPPED rather than failing the whole
+    // document: a project whose hostname list has one bad row must still get
+    // its embedding overrides, and the registry refuses a bad name again when
+    // it builds. Two layers rejecting the same thing is deliberate here -
+    // this one keeps a typo from costing a project its other settings, and
+    // hostnames.hpp keeps it from ever resolving.
+    if (j.contains("hostnames") && j.at("hostnames").is_array()) {
+        for (const auto& h : j.at("hostnames")) {
+            HostEntry e;
+            if (h.is_string()) {
+                // The bare-string spelling, so a hand-written document stays
+                // readable; it means the default style.
+                e.host = h.get<std::string>();
+            } else if (h.is_object()) {
+                e.host = h.value("host", std::string());
+                // Anything other than the two known spellings is SHORT, the
+                // documented default - not an error, because an unknown value
+                // in a stored document is a document written by a newer server
+                // and must not take a project offline.
+                e.pathStyle = h.value("path_style", std::string("short")) == "full"
+                                  ? PathStyle::Full
+                                  : PathStyle::Short;
+            } else {
+                continue;
+            }
+            if (!e.host.empty()) p.hostnames.push_back(std::move(e));
+        }
+    }
     if (j.contains("embedding_connect_timeout_sec") &&
         j.at("embedding_connect_timeout_sec").is_number_integer())
         p.embeddingConnectTimeoutSec = j.at("embedding_connect_timeout_sec").get<uint32_t>();
@@ -59,6 +87,15 @@ nlohmann::json ProjectSettings::toJson() const {
     // Written only when set, so round-tripping a project that never configured
     // one does not quietly pin today's built-in default into storage.
     if (defaultFunctionPolicy) j["default_function_policy"] = defaultFunctionPolicy->toJson();
+    // Always an ARRAY, even when empty, for the reason this codebase keeps
+    // relearning: "no hostnames" and "a server that does not know about
+    // hostnames" must not look the same to a reader.
+    nlohmann::json hosts = nlohmann::json::array();
+    for (const HostEntry& e : hostnames)
+        hosts.push_back({{"host", e.host},
+                         {"path_style", e.pathStyle == PathStyle::Full ? "full" : "short"}});
+    j["hostnames"] = std::move(hosts);
+
     if (embeddingConnectTimeoutSec) j["embedding_connect_timeout_sec"] = *embeddingConnectTimeoutSec;
     if (embeddingReadTimeoutSec) j["embedding_read_timeout_sec"] = *embeddingReadTimeoutSec;
     if (maxFunctionWallTimeHttpMs) j["max_function_wall_time_http_ms"] = *maxFunctionWallTimeHttpMs;

+ 16 - 0
src/project_settings.hpp

@@ -1,10 +1,12 @@
 #pragma once
 #include "functions/wall_budget.hpp"
 #include "apikey.hpp"
+#include "hostnames.hpp"
 #include <nlohmann/json.hpp>
 #include <cstdint>
 #include <optional>
 #include <string>
+#include <vector>
 
 namespace svapi {
 
@@ -38,6 +40,20 @@ struct ProjectSettings {
     /// only tighten. They exist because a latency-critical project needs a
     /// strict connect timeout while another legitimately wants a generous one,
     /// and the global setting cannot serve both without one of them suffering.
+    /// Customer-facing hostnames this project answers on.
+    ///
+    /// A TENANCY BOUNDARY, not a convenience: a request arriving on one of
+    /// these is scoped to THIS project, so a hostname stored against the wrong
+    /// project serves one customer another customer's data. Hence the
+    /// write-time collision check on the route that sets them, the exact-match
+    /// resolution in hostnames.hpp, and the refusal of wildcards there.
+    ///
+    /// Stored here rather than in a collection of their own so they ride the
+    /// subscribe stream this document already has - a hostname added through
+    /// the API reaches the next request without a restart, by the same
+    /// mechanism an embedding override does.
+    std::vector<HostEntry> hostnames;
+
     std::optional<uint32_t> embeddingConnectTimeoutSec;
     std::optional<uint32_t> embeddingReadTimeoutSec;
 

+ 14 - 0
src/settings.hpp

@@ -82,6 +82,20 @@ struct Settings {
 
     /// Extra CIDRs a function's ctx.fetch may not reach. ADDED to the built-in
     /// defaults, never substituted for them - see SsrfPolicy::fromSettings.
+    /// The deployment's own hostnames, as opposed to a project's.
+    ///
+    /// `adminHostname` serves everything including the web UI and /docs;
+    /// `globalHostnames` serve every project's API with the project named in
+    /// the path, which is what the single customer-facing name does today.
+    ///
+    /// BOTH EMPTY MEANS HOST GATING IS OFF, which is the default and must stay
+    /// so: a deployment behind someone else's proxy, the test fixture and the
+    /// devstack all send a Host nobody registered, and refusing those would be
+    /// an outage caused by adding a control. network_egress defaults to allow
+    /// for exactly the same reason.
+    std::string adminHostname;
+    std::vector<std::string> globalHostnames;
+
     std::vector<std::string> functionEgressBlockedCidrs;
     /// Explicit opt-out letting a function reach private and loopback
     /// addresses. Leaves the cloud metadata endpoint and link-local blocked

+ 37 - 0
src/settings_store.cpp

@@ -49,6 +49,7 @@ void SettingsStore::reloadProjectsFromDb() {
     }
     std::lock_guard<std::mutex> lk(m_);
     projects_ = m;
+    rebuildHostRegistryLocked();
 }
 
 std::shared_ptr<const ProjectSettings>
@@ -98,6 +99,42 @@ void SettingsStore::setSnapshot(Settings s) {
     auto p = std::make_shared<const Settings>(std::move(s));
     std::lock_guard<std::mutex> lk(m_);
     snap_ = p;
+    // The registry depends on BOTH snapshots, so it is rebuilt wherever either
+    // moves. Missing one of the two sites is the whole failure mode: a project
+    // adds a hostname, the project map swaps, and the registry still answers
+    // from the global settings it was built with - a hostname that exists in
+    // the document and 404s on the wire.
+    rebuildHostRegistryLocked();
+}
+
+void SettingsStore::rebuildHostRegistryLocked() {
+    std::unordered_map<std::string, std::vector<HostEntry>> byProject;
+    if (projects_)
+        for (const auto& [name, ps] : *projects_)
+            if (ps && !ps->hostnames.empty()) byProject[name] = ps->hostnames;
+
+    std::vector<std::string> dropped;
+    auto r = std::make_shared<const HostRegistry>(HostRegistry::build(
+        snap_ ? snap_->adminHostname : std::string(),
+        snap_ ? snap_->globalHostnames : std::vector<std::string>(), byProject, &dropped));
+
+    // Every dropped hostname is logged by NAME. A collision or a malformed
+    // entry is otherwise completely silent - the stored document says the
+    // project owns the name and the wire says 404, with nothing connecting the
+    // two. This codebase has twice paid for a refusal that left no record.
+    for (const std::string& h : dropped)
+        spdlog::warn("hostname '{}' is registered but NOT served: it collides with another "
+                     "project or with the deployment's own name, or it is not a valid hostname",
+                     h);
+    if (!dropped.empty())
+        spdlog::warn("{} registered hostname(s) are not served; the rest of the registry is "
+                     "unaffected ({} name(s) live)", dropped.size(), r->size());
+    hosts_ = std::move(r);
+}
+
+std::shared_ptr<const HostRegistry> SettingsStore::hostRegistry() const {
+    std::lock_guard<std::mutex> lk(m_);
+    return hosts_;
 }
 
 std::shared_ptr<const Settings> SettingsStore::snapshot() const {

+ 16 - 0
src/settings_store.hpp

@@ -1,6 +1,7 @@
 #pragma once
 #include "db_gateway.hpp"
 #include "project_settings.hpp"
+#include "hostnames.hpp"
 #include "settings.hpp"
 #include <memory>
 #include <mutex>
@@ -46,6 +47,16 @@ public:
     /// Per-project embedding overrides, or nullptr when the project inherits
     /// everything (thread-safe, lock-free after copy).
     std::shared_ptr<const ProjectSettings> projectSnapshot(const std::string& project) const;
+    /// Host -> project, rebuilt whenever the global settings or any project
+    /// document changes, and handed out as an immutable snapshot.
+    ///
+    /// A snapshot rather than a live structure for the reason every other
+    /// snapshot here is one: a request resolving its hostname must not be able
+    /// to observe a reload half-applied, because the half-applied state of a
+    /// tenancy map is "this name belongs to nobody" for some names and "to the
+    /// previous owner" for others.
+    std::shared_ptr<const HostRegistry> hostRegistry() const;
+
 
     /// Persist one project's overrides (`p.project` names it) and refresh the
     /// project snapshot. Returns true on success.
@@ -81,6 +92,11 @@ private:
     mutable std::mutex m_;
     std::shared_ptr<const Settings> snap_;
     std::shared_ptr<const ProjectMap> projects_ = std::make_shared<const ProjectMap>();
+    std::shared_ptr<const HostRegistry> hosts_ = std::make_shared<const HostRegistry>();
+    /// Rebuild `hosts_` from the current global + project snapshots. Callers
+    /// already hold `m_`.
+    void rebuildHostRegistryLocked();
+
     std::shared_ptr<void> sub_;
 };
 

+ 64 - 0
tests/test_hostnames.cpp

@@ -214,3 +214,67 @@ TEST(HostRegistry, SizeCountsEveryRegisteredName) {
     EXPECT_EQ(r.size(), 5u) << "admin + global + 3 project hostnames";
     EXPECT_FALSE(r.empty());
 }
+
+// --- serialisation: a hostname has to survive the document round trip -------
+//
+// These live here rather than in test_stores.cpp because they are pure: the
+// store's job is tested there, and what a STORED document means is tested here.
+
+#include "project_settings.hpp"
+
+using svapi::ProjectSettings;
+
+TEST(ProjectSettingsHostnames, RoundTripsHostAndStyle) {
+    ProjectSettings p;
+    p.project = "novitax";
+    p.hostnames = {{"nt.kb.smartbotics.ai", PathStyle::Short},
+                   {"portal.novitax.example", PathStyle::Full}};
+    const ProjectSettings back = ProjectSettings::fromJson(p.toJson());
+    ASSERT_EQ(back.hostnames.size(), 2u);
+    EXPECT_EQ(back.hostnames[0].host, "nt.kb.smartbotics.ai");
+    EXPECT_EQ(back.hostnames[0].pathStyle, PathStyle::Short);
+    EXPECT_EQ(back.hostnames[1].host, "portal.novitax.example");
+    EXPECT_EQ(back.hostnames[1].pathStyle, PathStyle::Full)
+        << "the per-hostname style must survive storage, or every hostname silently "
+           "becomes the default shape after a restart";
+}
+
+TEST(ProjectSettingsHostnames, EmittedAsAnArrayEvenWhenEmpty) {
+    // "No hostnames" and "a server that does not know about hostnames" must not
+    // look the same to a reader - this file's most repeated trap.
+    const nlohmann::json j = ProjectSettings{}.toJson();
+    ASSERT_TRUE(j.contains("hostnames"));
+    EXPECT_TRUE(j.at("hostnames").is_array());
+    EXPECT_TRUE(j.at("hostnames").empty());
+}
+
+TEST(ProjectSettingsHostnames, AcceptsTheBareStringSpellingAndDefaultsToShort) {
+    // So a hand-written document stays readable.
+    const nlohmann::json j = {{"project", "p"}, {"hostnames", {"a.example.com"}}};
+    const ProjectSettings p = ProjectSettings::fromJson(j);
+    ASSERT_EQ(p.hostnames.size(), 1u);
+    EXPECT_EQ(p.hostnames[0].host, "a.example.com");
+    EXPECT_EQ(p.hostnames[0].pathStyle, PathStyle::Short);
+}
+
+TEST(ProjectSettingsHostnames, AnUnknownStyleIsShortRatherThanAnError) {
+    // A document written by a NEWER server must not take a project offline -
+    // the same forward-compatibility rule the function descriptor follows for
+    // an unknown key.
+    const nlohmann::json j = {{"project", "p"},
+                              {"hostnames", {{{"host", "a.example.com"}, {"path_style", "sideways"}}}}};
+    const ProjectSettings p = ProjectSettings::fromJson(j);
+    ASSERT_EQ(p.hostnames.size(), 1u);
+    EXPECT_EQ(p.hostnames[0].pathStyle, PathStyle::Short);
+}
+
+TEST(ProjectSettingsHostnames, AMalformedEntryIsSkippedWithoutLosingTheRest) {
+    // A typo in one hostname must not cost the project its embedding overrides.
+    const nlohmann::json j = {{"project", "p"},
+                              {"default_embedding_model", "m"},
+                              {"hostnames", {7, nlohmann::json::object(), "ok.example.com"}}};
+    const ProjectSettings p = ProjectSettings::fromJson(j);
+    EXPECT_EQ(p.defaultEmbeddingModel, "m") << "the rest of the document survived";
+    ASSERT_EQ(p.hostnames.size(), 1u);
+    EXPECT_EQ(p.hostnames[0].host, "ok.example.com");
+}