Ver código fonte

feat: serve a project on its own hostname, with the short path form SV-132

Completes Stage 1 of #132: the hostname registry is in force, 30 project-scoped
route patterns accept both URL shapes, every project read goes through one
resolver, and an admin route registers hostnames with write-time collision
refusal. No TLS yet - this works behind whatever terminates it today.

ONE PATTERN SERVES BOTH SHAPES. `/api/v1/projects/([^/]+)/x` becomes
`/api/v1(?:/projects/([^/]+))?/x`, which keeps every later capture group at the
same index, so 30 patterns were widened rather than 60 registered. Two routes
are DELIBERATELY left narrow because their short shape collides with an
existing route, and the second was found by a reviewer rather than by me:
  - the bare `/api/v1/projects/([^/]+)` - its short shape is the literal
    `/api/v1`
  - `/api/v1/projects/([^/]+)/stats` - its short shape is `/api/v1/stats`, the
    GLOBAL admin stats route registered 11 lines below it, which widening makes
    unreachable. Proven in the real router, not inferred from registration
    order.
Both still resolve through projectFor(), because a narrow pattern is not a
reason to skip the tenancy check. A class-wide sweep over the 30 widened
patterns against all 5 global routes finds no further collision - and it ran
with 30 non-zero inputs, because an earlier version of that sweep reported
"0 collisions" from "0 patterns found" and could not have failed.

GATING IS THE DEPLOYMENT'S DECISION, AND KEYING IT WRONG WAS A REAL DEFECT AN
INTEGRATION TEST FOUND. It was first keyed on "the registry is non-empty",
which means an admin attaching the first customer hostname to a project turns
gating on service-wide - and their own next request, carrying whatever Host
they have always used, is answered 404. An operator locking themselves out of
the admin UI by adding a customer's hostname, with nothing connecting the two.
It is now keyed on the deployment having named ITSELF, so the order is safe:
the deployment names itself first, and project hostnames are stored but INERT
until it does. `served` on the hostnames route reports which state you are in,
because a list that looked identical in force and out of force would be the
most misleading thing that route could return.

A BARE IP OR `localhost` IS THE ADMIN SURFACE, so configuring a hostname is not
a one-way door undoable only by hand-editing the database. It cannot shadow a
registered name - a hostname cannot be all-numeric labels, so the two sets are
disjoint by construction rather than by lookup order, and a test pins that with
a project holding `1.example.com`. Rule 4 still applies to it: a short path on
the direct address is refused.

`hasAnyOverrides()` NOW COUNTS HOSTNAMES. Without that, a project whose only
override is a hostname list has its settings document deleted by the very PUT
that wrote it - a 200 followed by the hostname silently not existing, whose
symptom looks like the registry failing to reload.

/fn is constrained by a project hostname too, but through the pure resolver
rather than projectFor(): that surface is unauthenticated with its own refusal
discipline, and routing it through the ApiError path would answer in a
different shape from every other refusal there. Its path stays FULL form - a
short form is genuinely ambiguous against `/fn/([^/]+)((?:/.*)?)`, since
`/fn/kb-search` could be project `kb-search` or the short form, and guessing on
an unauthenticated surface is the fallback this work exists to remove. Deferred,
not forgotten.

Three refusal slugs rather than one, because the remedies differ: invalid_hostname
(change the value), hostname_taken (negotiate for the name), hostname_reserved
(you cannot have it). An unknown `path_style` is REFUSED in a request but falls
back to short when READING a stored document - a newer server's document must
not take a project offline, while a typo must never be accepted as a shape the
caller did not ask for.

Tests: 45 pure (hostnames) + 5 integration, 1460/1460 serial, zero pending
build steps. The integration tests are PAIRINGS throughout, because a test that
only asserted the refusal would pass against a server that refused everything -
the cross-tenant case holds the admin key CONSTANT and asserts 404 on the
project hostname and 200 on the admin hostname, so it is the hostname refusing
and not the authorization. Nine deliberate falsifications, each turning the
intended test red: closest-parent fallback (`evil.nt.kb...` resolved to
novitax), first-claimant on collision, no deployment precedence, rule 4
falling back on a project host, rule 4 falling back on admin/global, loose
rule-1 comparison, inferring gating instead of passing it, gating keyed on
emptiness, and a direct-address rule loose enough to shadow a name.
fszontagh 6 dias atrás
pai
commit
fa818902d0

+ 38 - 0
api/llms.txt

@@ -7,6 +7,44 @@
 > keys additionally manage projects and keys. Auth: `Authorization: Bearer <KEY>`.
 > Machine-readable spec: `/openapi.json` (OpenAPI 3.1).
 
+
+## Hostnames: the short path form
+
+Every project-scoped route accepts TWO shapes:
+
+    /api/v1/projects/<project>/collections/<c>/documents     (always works)
+    /api/v1/collections/<c>/documents                        (project from the Host header)
+
+The short form works ONLY on a hostname registered to a project. On the admin or
+global hostname a short path names no project and answers **404** - it does not
+fall back to a default.
+
+A project hostname serves `/api/*`, `/fn/*` and `/healthz` for ITS project only.
+Naming a different project in the path there answers **404**, not 403: a project
+hostname must not confirm that another project exists. The web UI and `/docs` are
+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.
+
+- `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"}]}`
+
+`path_style` defaults to `"short"`. **The PUT REPLACES the whole list**, like the
+key-scope PATCH - a partial list silently drops the rest, and merging would make
+removing a hostname impossible. Read the current list, edit it, send it whole.
+
+Refusals are three distinct slugs because the remedies differ (all 422):
+`invalid_hostname` (change the value - a wildcard, port, scheme, path or
+single-label name is refused; a wildcard belongs in a certificate, not here),
+`hostname_taken` (another project holds it), `hostname_reserved` (it is the
+deployment's own admin or global name). Re-claiming a hostname your own project
+already holds is accepted, so saving an unchanged list is idempotent.
+
 ## Projects
 
 Requires a valid key. Admin-only operations are noted.

+ 32 - 3
docs/superpowers/specs/2026-11-20-hostnames-tls-sni-design.md

@@ -185,11 +185,40 @@ 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.
 
+## Found while implementing Stage 1
+
+**The bare `/api/v1/projects/([^/]+)` pattern must NOT be widened.** Project
+CRUD (GET and DELETE a project) uses it, and
+`/api/v1(?:/projects/([^/]+))?` also matches the literal path `/api/v1`, so
+widening it hijacks an unrelated path. Project-level CRUD stays full-form only,
+which is right on its own terms too: creating and deleting a project is an
+operation on the tenant, not within it.
+
+**`gatingOn` is an explicit parameter of `resolveProject()`, not inferred.** A
+deployment with no hostnames configured resolves every Host to `Unknown`, and so
+does a configured deployment receiving an unregistered hostname - one value, two
+opposite correct answers. Inferring would make the safe answer depend on a gate
+running in another function, which is the shape of this repo's most expensive
+bugs. A test asserts both directions of that ambiguity.
+
+**A host claimed by two projects goes to NEITHER, and falsifying that produced a
+better reason than the one it was written for.** Keeping the first claimant
+instead showed the winner was whichever project `unordered_map` iterated first,
+so last-writer-wins is not merely unsafe - it is NONDETERMINISTIC, and the same
+stored config could serve a different tenant after a restart.
+
+**An empty registry means gating is OFF, not "refuse everything".** Otherwise
+this feature would 404 every request on every existing deployment, the test
+fixture and the devstack included - an outage caused by adding a control, which
+`network_egress` defaulting to allow already avoided once here.
+
 ## 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.
+- ~~Should the admin hostname be reachable publicly at all?~~ **ANSWERED by the
+  owner, 2026-11-20: public is fine**, with the URL being the only additional
+  factor ("at least only know where to find who knows the url to it"). So the
+  hostname-kind table stands as written - the admin name carries the web UI and
+  the docs catalogue, and a project name carries neither.
 - 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

+ 8 - 8
src/handlers/collection_schema.cpp

@@ -94,10 +94,10 @@ void registerCollectionSchemaRoutes(ApiServer& s) {
     // must satisfy to write, so anyone who may read the collection may read
     // what shape it expects. Withholding it would make a 422 unexplainable to
     // the one principal most likely to hit it.
-    svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/schema)",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/schema)",
             [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        std::string project = req.matches[1], name = req.matches[2];
+        std::string project = projectFor(*d, req, 1), name = req.matches[2];
         requireCapability(*d, k, req, project, name, KeyOp::Read);
         requireSchemaSupport(*d);
         if (!d->registry.get(project, name))
@@ -134,10 +134,10 @@ void registerCollectionSchemaRoutes(ApiServer& s) {
     // tenant's own collection, the same category as an index, and not a
     // security boundary. (Function POLICY is admin-only because it governs
     // what one project may take from a runner every project shares.)
-    svr.Put(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/schema)",
+    svr.Put(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/schema)",
             [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        std::string project = req.matches[1], name = req.matches[2];
+        std::string project = projectFor(*d, req, 1), name = req.matches[2];
         requireProjectManage(k, project);
         requireSchemaSupport(*d);
         if (!d->registry.get(project, name))
@@ -200,10 +200,10 @@ void registerCollectionSchemaRoutes(ApiServer& s) {
     });
 
     // Remove the schema; writes stop being validated.
-    svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/schema)",
+    svr.Delete(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/schema)",
                [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        std::string project = req.matches[1], name = req.matches[2];
+        std::string project = projectFor(*d, req, 1), name = req.matches[2];
         requireProjectManage(k, project);
         requireSchemaSupport(*d);
         if (!d->registry.get(project, name))
@@ -225,10 +225,10 @@ void registerCollectionSchemaRoutes(ApiServer& s) {
     // reason: lengths and ranges are only described, not enforced, so applying
     // this unseen would arm something that looks stricter than what it
     // actually checks. The caller edits and then PUTs.
-    svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/schema/suggest)",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/schema/suggest)",
             [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        std::string project = req.matches[1], name = req.matches[2];
+        std::string project = projectFor(*d, req, 1), name = req.matches[2];
         requireProjectManage(k, project);
         requireSchemaSupport(*d);
         // `limit` is the obvious guess for the sample size and would be

+ 8 - 8
src/handlers/collections.cpp

@@ -48,8 +48,8 @@ bool anythingAttachedTo(DbGateway& db, const std::string& qc) {
 void registerCollectionRoutes(ApiServer& s) {
     auto& svr = s.raw(); ServerDeps* d = &s.deps();
 
-    svr.Post(R"(/api/v1/projects/([^/]+)/collections)", [d](const httplib::Request& req, httplib::Response& res) {
-        ApiKey k = requireKey(*d, req); std::string project = req.matches[1];
+    svr.Post(R"(/api/v1(?:/projects/([^/]+))?/collections)", [d](const httplib::Request& req, httplib::Response& res) {
+        ApiKey k = requireKey(*d, req); std::string project = projectFor(*d, req, 1);
         requireProjectManage(k, project);
         d->db.ensureProject(project); d->registry.ensure(project);
         auto body = bodyJson(req);
@@ -79,8 +79,8 @@ void registerCollectionRoutes(ApiServer& s) {
         sendJson(res, 201, {{"name", name}, {"kind", kind}, {"vector_dimension", dim}});
     });
 
-    svr.Get(R"(/api/v1/projects/([^/]+)/collections)", [d](const httplib::Request& req, httplib::Response& res) {
-        ApiKey k = requireKey(*d, req); std::string project = req.matches[1];
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/collections)", [d](const httplib::Request& req, httplib::Response& res) {
+        ApiKey k = requireKey(*d, req); std::string project = projectFor(*d, req, 1);
         // Project ACCESS, not project-manage: enumerating is not managing.
         // A scoped key could already read every document in a collection but
         // could not learn that the collection existed, which forced a consumer
@@ -194,8 +194,8 @@ void registerCollectionRoutes(ApiServer& s) {
         sendJson(res, 200, {{"collections", out}, {"scope_filtered", scoped}});
     });
 
-    svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
-        ApiKey k = requireKey(*d, req); std::string project = req.matches[1], name = req.matches[2];
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
+        ApiKey k = requireKey(*d, req); std::string project = projectFor(*d, req, 1), name = req.matches[2];
         // Project ACCESS, matching the LIST route above: a scoped key that can
         // enumerate collections must also be able to read one's metadata, or it
         // can see a name and nothing about it. Create, alter and drop stay
@@ -225,8 +225,8 @@ void registerCollectionRoutes(ApiServer& s) {
         sendJson(res, 200, e);
     });
 
-    svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
-        ApiKey k = requireKey(*d, req); std::string project = req.matches[1], name = req.matches[2];
+    svr.Delete(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
+        ApiKey k = requireKey(*d, req); std::string project = projectFor(*d, req, 1), name = req.matches[2];
         requireProjectManage(k, project);
         if (!d->registry.get(project, name)) throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
         const std::string qc = qualify(project, name);

+ 8 - 8
src/handlers/documents.cpp

@@ -42,7 +42,7 @@ struct Target {
 Target authorized(ServerDeps* d, const httplib::Request& req, int projIdx, int collIdx, KeyOp op) {
     Target t;
     t.key = requireKey(*d, req);
-    t.project = req.matches[projIdx];
+    t.project = projectFor(*d, req, (size_t)projIdx);
     t.name = req.matches[collIdx];
     requireCapability(*d, t.key, req, t.project, t.name, op);
     t.qualified = qualify(t.project, t.name);
@@ -111,7 +111,7 @@ ApiError conditionalFailure(const smartbotic::database::Client::FailureDetail& d
 void registerDocumentRoutes(ApiServer& s) {
     auto& svr = s.raw(); ServerDeps* d = &s.deps();
 
-    svr.Post(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents)", [d](const httplib::Request& req, httplib::Response& res) {
+    svr.Post(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/documents)", [d](const httplib::Request& req, httplib::Response& res) {
         Target t = scoped(d, req, 1, 2, KeyOp::Insert);
         auto body = bodyJson(req);
         std::string id = body.value("id", "");
@@ -225,7 +225,7 @@ void registerDocumentRoutes(ApiServer& s) {
         sendJson(res, 201, {{"id", newId}});
     });
 
-    svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
         Target t = scoped(d, req, 1, 2, KeyOp::Read);
         auto doc = d->db.client().get(t.qualified, req.matches[3]);
         if (!doc) throw ApiError(ErrCode::NotFound, "not_found", "no such document");
@@ -239,7 +239,7 @@ void registerDocumentRoutes(ApiServer& s) {
         sendJson(res, 200, *doc);
     });
 
-    svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents)", [d](const httplib::Request& req, httplib::Response& res) {
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/documents)", [d](const httplib::Request& req, httplib::Response& res) {
         Target t = scoped(d, req, 1, 2, KeyOp::List);
         // The sibling routes' spellings are the ones worth refusing here:
         // `order=desc` is how the index-values route says it and `q=` is how
@@ -312,7 +312,7 @@ void registerDocumentRoutes(ApiServer& s) {
                             {"total", page.totalCount}});
     });
 
-    svr.Patch(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
+    svr.Patch(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
         Target t = scoped(d, req, 1, 2, KeyOp::Update);
         std::string id = req.matches[3];
         const auto ttl = ttlParam(req);
@@ -381,7 +381,7 @@ void registerDocumentRoutes(ApiServer& s) {
         sendJson(res, 200, {{"id", id}, {"version", newVersion}});
     });
 
-    svr.Put(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
+    svr.Put(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
         // AUTHORIZE first, then the REQUEST, then the RESOURCE - see
         // `authorized()` above. The parameter refusal below must come before
         // the collection's 404, or the same refused parameter answers 422 on a
@@ -556,7 +556,7 @@ void registerDocumentRoutes(ApiServer& s) {
     // own: a key that may replace a document may already set any number to any
     // value, so increment grants no power `update` did not, and inventing an op
     // would silently strip the ability from every scope already granting it.
-    svr.Post(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+)/increment)",
+    svr.Post(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/documents/([^/]+)/increment)",
              [d](const httplib::Request& req, httplib::Response& res) {
         Target t = scoped(d, req, 1, 2, KeyOp::Update);
         const std::string id = req.matches[3];
@@ -581,7 +581,7 @@ void registerDocumentRoutes(ApiServer& s) {
         sendJson(res, 200, {{"id", id}, {"values", *values}});
     });
 
-    svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
+    svr.Delete(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
         Target t = scoped(d, req, 1, 2, KeyOp::Delete);
         std::string id = req.matches[3];
         smartbotic::database::Client::Failure failure;

+ 2 - 2
src/handlers/export.cpp

@@ -208,10 +208,10 @@ void registerExportRoutes(ApiServer& s) {
     auto& svr = s.raw();
     ServerDeps* d = &s.deps();
 
-    svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/export)",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/export)",
             [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey key = requireKey(*d, req);
-        const std::string project = req.matches[1], name = req.matches[2];
+        const std::string project = projectFor(*d, req, 1), name = req.matches[2];
         // BOTH ops: this enumerates the collection AND returns every document
         // body. A key granted only `list` can already learn the ids; it must
         // not get the contents, and a key granted only `read` must not get an

+ 10 - 10
src/handlers/files.cpp

@@ -47,10 +47,10 @@ void registerFileRoutes(ApiServer& s) {
 
     // List. Newest first; `limit` is clamped rather than refused, because a
     // caller asking for everything wants as much as we will give, not an error.
-    svr.Get(R"(/api/v1/projects/([^/]+)/files)",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/files)",
             [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        const std::string project = req.matches[1];
+        const std::string project = projectFor(*d, req, 1);
         requireFileRead(*d, k, req, project, KeyOp::List);
 
         auto parseUInt = [](const std::string& v, const char* what) -> uint32_t {
@@ -97,10 +97,10 @@ void registerFileRoutes(ApiServer& s) {
 
     // Download. Answers with the stored bytes and the stored content type, not
     // JSON: a caller fetching an image wants an image.
-    svr.Get(R"(/api/v1/projects/([^/]+)/files/([^/]+))",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/files/([^/]+))",
             [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        const std::string project = req.matches[1], name = req.matches[2];
+        const std::string project = projectFor(*d, req, 1), name = req.matches[2];
         requireFileRead(*d, k, req, project, KeyOp::Read);
         requireUsableName(name);
 
@@ -121,10 +121,10 @@ void registerFileRoutes(ApiServer& s) {
 
     // Metadata without the bytes, for a caller that only wants to know whether
     // a file is there and how big it is.
-    svr.Get(R"(/api/v1/projects/([^/]+)/files/([^/]+)/info)",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/files/([^/]+)/info)",
             [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        const std::string project = req.matches[1], name = req.matches[2];
+        const std::string project = projectFor(*d, req, 1), name = req.matches[2];
         requireFileRead(*d, k, req, project, KeyOp::Read);
         requireUsableName(name);
 
@@ -137,10 +137,10 @@ void registerFileRoutes(ApiServer& s) {
     // Upload, replacing whatever that name held. The raw request body is the
     // content - not base64, not a JSON wrapper - because a file is bytes and
     // wrapping them would cost a third of the payload for nothing.
-    svr.Put(R"(/api/v1/projects/([^/]+)/files/([^/]+))",
+    svr.Put(R"(/api/v1(?:/projects/([^/]+))?/files/([^/]+))",
             [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        const std::string project = req.matches[1], name = req.matches[2];
+        const std::string project = projectFor(*d, req, 1), name = req.matches[2];
         // Project-manage, not a scope rule: replacing a tenant's asset is a
         // management act, and a scoped key exists to be narrower than that.
         requireProjectManage(k, project);
@@ -170,10 +170,10 @@ void registerFileRoutes(ApiServer& s) {
         sendJson(res, existed ? 200 : 201, stored.toJson());
     });
 
-    svr.Delete(R"(/api/v1/projects/([^/]+)/files/([^/]+))",
+    svr.Delete(R"(/api/v1(?:/projects/([^/]+))?/files/([^/]+))",
                [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        const std::string project = req.matches[1], name = req.matches[2];
+        const std::string project = projectFor(*d, req, 1), name = req.matches[2];
         requireProjectManage(k, project);
         requireUsableName(name);
 

+ 20 - 0
src/handlers/function_dispatch.cpp

@@ -234,6 +234,26 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
 
     if (!safeProjectSegment(project) || hasDotDotSegment(path)) { sendNotFound(res); return; }
 
+    // A PROJECT HOSTNAME CONSTRAINS /fn TOO, and this route resolves it with
+    // the pure helper rather than projectFor() on purpose: projectFor throws an
+    // ApiError, and this surface is UNAUTHENTICATED with its own deliberate
+    // refusal discipline - a 404 that discloses nothing, and function error
+    // text that never reaches the caller. Routing it through the ApiError path
+    // would answer in a different shape from every other refusal here.
+    //
+    // Note the path keeps its FULL form: `/fn/<project>/<rest>`. A short form
+    // is genuinely ambiguous against this pattern - `/fn/kb-search` could be
+    // project `kb-search` with no rest, or the short form with rest
+    // `/kb-search` - and guessing between those on an unauthenticated surface
+    // is exactly the kind of fallback the hostname work exists to remove. It
+    // is deferred rather than forgotten.
+    {
+        const auto reg = d.settings.hostRegistry();
+        const bool gatingOn = reg && reg->gating();
+        const HostBinding host = reg ? reg->resolve(req.get_header_value("Host")) : HostBinding{};
+        if (!resolveProject(project, host, gatingOn).ok) { sendNotFound(res); return; }
+    }
+
     // The project must exist before anything qualifies a collection with it, so
     // a crafted segment cannot conjure a registry read in a namespace of its
     // own. Cached, but a miss is re-verified against the database before this

+ 18 - 18
src/handlers/functions.cpp

@@ -187,9 +187,9 @@ nlohmann::json runEnvelope(const std::string& runId, const RunnerRunResult& r) {
 void registerFunctionRoutes(ApiServer& s) {
     auto& svr = s.raw(); ServerDeps* d = &s.deps();
 
-    svr.Get(R"(/api/v1/projects/([^/]+)/functions)",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/functions)",
             [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1];
+        std::string project = projectFor(*d, req, 1);
         requireProjectManage(requireKey(*d, req), project);
         d->functions.ensure(project);
         nlohmann::json arr = nlohmann::json::array();
@@ -214,9 +214,9 @@ void registerFunctionRoutes(ApiServer& s) {
                   {"runs_kept", d->functionRuns.keepPerFunction()}});
     });
 
-    svr.Post(R"(/api/v1/projects/([^/]+)/functions)",
+    svr.Post(R"(/api/v1(?:/projects/([^/]+))?/functions)",
              [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1];
+        std::string project = projectFor(*d, req, 1);
         requireProjectManage(requireKey(*d, req), project);
         FunctionRecord incoming = validateOnRunner(*d, codePush(bodyJson(req)));
         // POST creates. An id that already exists is a genuine conflict, and
@@ -231,18 +231,18 @@ void registerFunctionRoutes(ApiServer& s) {
         sendJson(res, 201, stored.toSummaryJson());
     });
 
-    svr.Get(R"(/api/v1/projects/([^/]+)/functions/([^/]+))",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/functions/([^/]+))",
             [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1], id = req.matches[2];
+        std::string project = projectFor(*d, req, 1), id = req.matches[2];
         requireProjectManage(requireKey(*d, req), project);
         auto fn = d->functions.get(project, id);
         if (!fn) throw ApiError(ErrCode::NotFound, "not_found", "no such function");
         sendJson(res, 200, fn->toJson());   // the single-function view carries the source
     });
 
-    svr.Put(R"(/api/v1/projects/([^/]+)/functions/([^/]+))",
+    svr.Put(R"(/api/v1(?:/projects/([^/]+))?/functions/([^/]+))",
             [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1], id = req.matches[2];
+        std::string project = projectFor(*d, req, 1), id = req.matches[2];
         requireProjectManage(requireKey(*d, req), project);
         FunctionRecord incoming = validateOnRunner(*d, codePush(bodyJson(req)));
         // The id lives in the source, so the URL cannot rename a function. Say
@@ -262,9 +262,9 @@ void registerFunctionRoutes(ApiServer& s) {
         sendJson(res, existed ? 200 : 201, stored.toSummaryJson());
     });
 
-    svr.Delete(R"(/api/v1/projects/([^/]+)/functions/([^/]+))",
+    svr.Delete(R"(/api/v1(?:/projects/([^/]+))?/functions/([^/]+))",
                [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1], id = req.matches[2];
+        std::string project = projectFor(*d, req, 1), id = req.matches[2];
         requireProjectManage(requireKey(*d, req), project);
         if (!d->functions.remove(project, id))
             throw ApiError(ErrCode::NotFound, "not_found", "no such function");
@@ -273,9 +273,9 @@ void registerFunctionRoutes(ApiServer& s) {
 
     // ADMIN ONLY, and the only route that changes a policy. Developers push
     // code, admins grant what it may touch - the same split keys already have.
-    svr.Put(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/policy)",
+    svr.Put(R"(/api/v1(?:/projects/([^/]+))?/functions/([^/]+)/policy)",
             [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1], id = req.matches[2];
+        std::string project = projectFor(*d, req, 1), id = req.matches[2];
         requireAdmin(requireKey(*d, req));
         KeyScope policy = parsePolicy(bodyJson(req));
         if (!d->functions.setPolicy(project, id, policy))
@@ -285,9 +285,9 @@ void registerFunctionRoutes(ApiServer& s) {
         sendJson(res, 200, fn->toSummaryJson());
     });
 
-    svr.Put(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/enabled)",
+    svr.Put(R"(/api/v1(?:/projects/([^/]+))?/functions/([^/]+)/enabled)",
             [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1], id = req.matches[2];
+        std::string project = projectFor(*d, req, 1), id = req.matches[2];
         requireProjectManage(requireKey(*d, req), project);
         auto body = bodyJson(req);
         if (!body.contains("enabled") || !body["enabled"].is_boolean())
@@ -297,9 +297,9 @@ void registerFunctionRoutes(ApiServer& s) {
         sendJson(res, 200, {{"function_id", id}, {"enabled", body["enabled"].get<bool>()}});
     });
 
-    svr.Post(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/invoke)",
+    svr.Post(R"(/api/v1(?:/projects/([^/]+))?/functions/([^/]+)/invoke)",
              [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1], id = req.matches[2];
+        std::string project = projectFor(*d, req, 1), id = req.matches[2];
         requireProjectManage(requireKey(*d, req), project);
 
         // Authorize, then the REQUEST, then the resource - the one ordering
@@ -362,9 +362,9 @@ void registerFunctionRoutes(ApiServer& s) {
         sendJson(res, 200, runEnvelope(runId, r));
     });
 
-    svr.Get(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/logs)",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/functions/([^/]+)/logs)",
             [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1], id = req.matches[2];
+        std::string project = projectFor(*d, req, 1), id = req.matches[2];
         requireProjectManage(requireKey(*d, req), project);
         // The run log takes `limit` and NOTHING else. `status`/`state` are the
         // ones worth naming, because filtering a run log to the failures is

+ 10 - 10
src/handlers/indexes.cpp

@@ -76,10 +76,10 @@ void registerIndexRoutes(ApiServer& s) {
     // duplicate all of that and leave a caller two places to look for "what
     // does this collection enforce". The two spellings are mutually exclusive -
     // see parseIndexRequest().
-    svr.Post(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/indexes)",
+    svr.Post(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/indexes)",
              [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        std::string project = req.matches[1], coll = req.matches[2];
+        std::string project = projectFor(*d, req, 1), coll = req.matches[2];
         requireProjectManage(k, project);
         const IndexRequest want = parseIndexRequest(bodyJson(req));
 
@@ -131,10 +131,10 @@ void registerIndexRoutes(ApiServer& s) {
                             {"rows_indexed", rows}, {"already_existed", alreadyExisted}});
     });
 
-    svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/indexes)",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/indexes)",
             [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        std::string project = req.matches[1], coll = req.matches[2];
+        std::string project = projectFor(*d, req, 1), coll = req.matches[2];
         requireProjectAccess(k, project);
 
         const std::string qc = qualify(project, coll);
@@ -179,10 +179,10 @@ void registerIndexRoutes(ApiServer& s) {
     // real field of that name. On the collection-level path rather than under
     // `/indexes/{field}`, so it cannot be confused with the single-field drop.
     // An empty `fields` is a 422, never "drop everything".
-    svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/indexes)",
+    svr.Delete(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/indexes)",
                [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        std::string project = req.matches[1], coll = req.matches[2];
+        std::string project = projectFor(*d, req, 1), coll = req.matches[2];
         requireProjectManage(k, project);
 
         std::vector<std::string> raw;
@@ -214,10 +214,10 @@ void registerIndexRoutes(ApiServer& s) {
     // Distinct values of an indexed field, with counts. Index-dependent by
     // design: returns an empty list for an unindexed field and for array-valued
     // fields, whose index keys are elements rather than values.
-    svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/indexes/([^/]+)/values)",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/indexes/([^/]+)/values)",
             [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        std::string project = req.matches[1], coll = req.matches[2], field = req.matches[3];
+        std::string project = projectFor(*d, req, 1), coll = req.matches[2], field = req.matches[3];
         requireCapability(*d, k, req, project, coll, KeyOp::Read);
 
         // REFUSE a parameter a caller sends EXPECTING AN EFFECT that this route
@@ -270,10 +270,10 @@ void registerIndexRoutes(ApiServer& s) {
         sendJson(res, 200, body);
     });
 
-    svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/indexes/([^/]+))",
+    svr.Delete(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/indexes/([^/]+))",
                [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        std::string project = req.matches[1], coll = req.matches[2], field = req.matches[3];
+        std::string project = projectFor(*d, req, 1), coll = req.matches[2], field = req.matches[3];
         requireProjectManage(k, project);
         // Idempotent, and `false` is a failed call rather than a missing index -
         // see the composite drop above for why that is not a 404.

+ 8 - 8
src/handlers/project_secrets.cpp

@@ -52,9 +52,9 @@ std::string secretNameParam(const httplib::Request& req) {
 void registerProjectSecretRoutes(ApiServer& s) {
     auto& svr = s.raw(); ServerDeps* d = &s.deps();
 
-    svr.Get(R"(/api/v1/projects/([^/]+)/secrets)",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/secrets)",
             [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1];
+        std::string project = projectFor(*d, req, 1);
         requireProjectManage(requireKey(*d, req), project);
         requireExistingProject(d, project);
 
@@ -71,9 +71,9 @@ void registerProjectSecretRoutes(ApiServer& s) {
                             {"max_value_bytes", kMaxSecretValueBytes}});
     });
 
-    svr.Get(R"(/api/v1/projects/([^/]+)/secrets/([^/]+))",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/secrets/([^/]+))",
             [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1];
+        std::string project = projectFor(*d, req, 1);
         requireProjectManage(requireKey(*d, req), project);
         requireExistingProject(d, project);
         const std::string name = secretNameParam(req);
@@ -84,9 +84,9 @@ void registerProjectSecretRoutes(ApiServer& s) {
         sendJson(res, 200, row->summaryJson());
     });
 
-    svr.Put(R"(/api/v1/projects/([^/]+)/secrets/([^/]+))",
+    svr.Put(R"(/api/v1(?:/projects/([^/]+))?/secrets/([^/]+))",
             [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1];
+        std::string project = projectFor(*d, req, 1);
         requireAdmin(requireKey(*d, req));
         requireExistingProject(d, project);
         const std::string name = secretNameParam(req);
@@ -122,9 +122,9 @@ void registerProjectSecretRoutes(ApiServer& s) {
         sendJson(res, created ? 201 : 200, stored.summaryJson());
     });
 
-    svr.Delete(R"(/api/v1/projects/([^/]+)/secrets/([^/]+))",
+    svr.Delete(R"(/api/v1(?:/projects/([^/]+))?/secrets/([^/]+))",
                [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1];
+        std::string project = projectFor(*d, req, 1);
         requireAdmin(requireKey(*d, req));
         requireExistingProject(d, project);
         const std::string name = secretNameParam(req);

+ 127 - 10
src/handlers/project_settings.cpp

@@ -138,18 +138,18 @@ std::optional<int64_t> capFromJson(const nlohmann::json& v, const char* what) {
 void registerProjectSettingsRoutes(ApiServer& s) {
     auto& svr = s.raw(); ServerDeps* d = &s.deps();
 
-    svr.Get(R"(/api/v1/projects/([^/]+)/settings/embeddings)",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/settings/embeddings)",
             [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1];
+        std::string project = projectFor(*d, req, 1);
         requireProjectManage(requireKey(*d, req), project);
         auto global = d->settings.snapshot();
         auto proj   = d->settings.projectSnapshot(project);
         sendJson(res, 200, viewJson(*global, proj.get()));
     });
 
-    svr.Put(R"(/api/v1/projects/([^/]+)/settings/embeddings)",
+    svr.Put(R"(/api/v1(?:/projects/([^/]+))?/settings/embeddings)",
             [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1];
+        std::string project = projectFor(*d, req, 1);
         requireProjectManage(requireKey(*d, req), project);
         auto body = bodyJson(req);
 
@@ -192,17 +192,17 @@ void registerProjectSettingsRoutes(ApiServer& s) {
     // the one thing standing between one tenant's `timeoutMs: 120000` and every
     // other tenant's share of the runner pool, so the party it constrains must
     // not be the party who sets it.
-    svr.Get(R"(/api/v1/projects/([^/]+)/settings/functions)",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/settings/functions)",
             [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1];
+        std::string project = projectFor(*d, req, 1);
         requireAdmin(requireKey(*d, req));
         auto proj = d->settings.projectSnapshot(project);
         sendJson(res, 200, budgetJson(proj.get()));
     });
 
-    svr.Put(R"(/api/v1/projects/([^/]+)/settings/functions)",
+    svr.Put(R"(/api/v1(?:/projects/([^/]+))?/settings/functions)",
             [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1];
+        std::string project = projectFor(*d, req, 1);
         requireAdmin(requireKey(*d, req));
         auto body = bodyJson(req);
 
@@ -252,9 +252,126 @@ void registerProjectSettingsRoutes(ApiServer& s) {
         sendJson(res, 200, budgetJson(proj.get()));
     });
 
-    svr.Delete(R"(/api/v1/projects/([^/]+)/settings/embeddings)",
+    // ---- hostnames -------------------------------------------------------
+    //
+    // ADMIN ONLY, like the function policy and for the same reason: it decides
+    // what a tenant can reach. A project-manage key must not be able to attach
+    // a hostname to its own project, because the hostname IS the tenancy
+    // boundary for every caller who uses the short path form.
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/settings/hostnames)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = projectFor(*d, req, 1);
+        requireAdmin(requireKey(*d, req));
+        auto proj = d->settings.projectSnapshot(project);
+        nlohmann::json hosts = nlohmann::json::array();
+        if (proj)
+            for (const HostEntry& e : proj->hostnames)
+                hosts.push_back({{"host", e.host},
+                                 {"path_style", e.pathStyle == PathStyle::Full ? "full" : "short"}});
+        // Always an array, and `served` says whether the registry is actually
+        // gating - because with no deployment hostnames configured a project
+        // hostname is stored and NOT in force, and a list that looked identical
+        // either way would be the most misleading thing this route could
+        // return.
+        const auto reg = d->settings.hostRegistry();
+        sendJson(res, 200, {{"project", project},
+                            {"hostnames", std::move(hosts)},
+                            {"served", (bool)(reg && reg->gating())}});
+    });
+
+    svr.Put(R"(/api/v1(?:/projects/([^/]+))?/settings/hostnames)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = projectFor(*d, req, 1);
+        requireAdmin(requireKey(*d, req));
+        auto body = bodyJson(req);
+        if (!body.contains("hostnames") || !body.at("hostnames").is_array())
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "hostnames must be an array of {host, path_style}");
+
+        // REPLACES the whole list, like the key scope PATCH, and the cost is
+        // the same: a caller sending a partial list silently drops the rest.
+        // Said in the API docs rather than guessed at here, because merging
+        // would make REMOVING a hostname impossible.
+        std::vector<HostEntry> wanted;
+        for (const auto& h : body.at("hostnames")) {
+            HostEntry e;
+            if (h.is_string()) e.host = h.get<std::string>();
+            else if (h.is_object()) {
+                e.host = h.value("host", std::string());
+                const std::string style = h.value("path_style", std::string("short"));
+                // An unknown style is REFUSED here, unlike when READING a
+                // stored document where it falls back to short. The two differ
+                // on purpose: a stored document may have been written by a
+                // newer server and must not take a project offline, whereas a
+                // typo in a REQUEST must never be accepted as a shape the
+                // caller did not ask for.
+                if (style != "short" && style != "full")
+                    throw ApiError(ErrCode::Unprocessable, "validation",
+                                   "path_style must be 'short' or 'full'; got '" + style + "'");
+                e.pathStyle = style == "full" ? PathStyle::Full : PathStyle::Short;
+            } else {
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "each hostname must be a string or {host, path_style}");
+            }
+            wanted.push_back(std::move(e));
+        }
+
+        // COLLISIONS ARE REFUSED AT WRITE TIME. The registry also resolves them
+        // - it must, since a document can be hand-edited - but the only
+        // resolution available to it is "serve neither", which turns a typo
+        // into an outage for whichever project held the name FIRST. Refusing
+        // the write costs the second caller a 422 they can act on.
+        auto snap = d->settings.snapshot();
+        std::unordered_map<std::string, std::vector<HostEntry>> byProject;
+        for (const std::string& p : d->db.listProjects())
+            if (auto ps = d->settings.projectSnapshot(p); ps && !ps->hostnames.empty())
+                byProject[p] = ps->hostnames;
+
+        for (const HostEntry& e : wanted) {
+            const HostClaimRefusal why = mayClaimHostname(
+                e.host, project, snap->adminHostname, snap->globalHostnames, byProject);
+            if (why == HostClaimRefusal::None) continue;
+            // Three distinct slugs, because the remedies are different: Invalid
+            // means change the value, Taken means negotiate for the name,
+            // Reserved means you cannot have it at all. Folding them into one
+            // would send a caller looking for the wrong fix.
+            if (why == HostClaimRefusal::Invalid)
+                throw ApiError(ErrCode::Unprocessable, "invalid_hostname",
+                               "'" + e.host + "' is not a hostname this service will serve: "
+                               "a wildcard, a port, a scheme, a path or a single-label name is "
+                               "refused, and a wildcard belongs in a certificate rather than here");
+            if (why == HostClaimRefusal::Reserved)
+                throw ApiError(ErrCode::Unprocessable, "hostname_reserved",
+                               "'" + e.host + "' is this deployment's own admin or global "
+                               "hostname and cannot be claimed by a project");
+            throw ApiError(ErrCode::Unprocessable, "hostname_taken",
+                           "'" + e.host + "' is already registered to another project");
+        }
+
+        auto current = d->settings.projectSnapshot(project);
+        ProjectSettings updated = current ? *current : ProjectSettings{};
+        updated.project = project;
+        updated.hostnames = std::move(wanted);
+
+        if (!updated.hasAnyOverrides()) d->settings.removeProject(project);
+        else if (!d->settings.saveProject(updated))
+            throw ApiError(ErrCode::Unavailable, "db_error", "could not save project settings");
+
+        auto proj = d->settings.projectSnapshot(project);
+        nlohmann::json hosts = nlohmann::json::array();
+        if (proj)
+            for (const HostEntry& e : proj->hostnames)
+                hosts.push_back({{"host", e.host},
+                                 {"path_style", e.pathStyle == PathStyle::Full ? "full" : "short"}});
+        const auto reg = d->settings.hostRegistry();
+        sendJson(res, 200, {{"project", project},
+                            {"hostnames", std::move(hosts)},
+                            {"served", (bool)(reg && reg->gating())}});
+    });
+
+    svr.Delete(R"(/api/v1(?:/projects/([^/]+))?/settings/embeddings)",
                [d](const httplib::Request& req, httplib::Response& res) {
-        std::string project = req.matches[1];
+        std::string project = projectFor(*d, req, 1);
         requireProjectManage(requireKey(*d, req), project);
 
         // Clears the EMBEDDING fields only. This used to call removeProject(),

+ 9 - 2
src/handlers/projects.cpp

@@ -31,7 +31,12 @@ void registerProjectRoutes(ApiServer& s) {
 
     svr.Get(R"(/api/v1/projects/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        std::string project = req.matches[1];
+        // NOT widened: the short shape of this route is the literal `/api/v1`,
+        // which would hijack an unrelated path. Project CRUD is an operation on
+        // the tenant rather than within it, so the full form is the only one
+        // that makes sense here anyway - but it still resolves through
+        // projectFor, so a project hostname cannot read another project.
+        std::string project = projectFor(*d, req, 1);
         requireProjectAccess(k, project);
         auto all = d->db.listProjects();
         if (std::find(all.begin(), all.end(), project) == all.end())
@@ -41,7 +46,9 @@ void registerProjectRoutes(ApiServer& s) {
 
     svr.Delete(R"(/api/v1/projects/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req); requireAdmin(k);
-        std::string project = req.matches[1];
+        // See the GET above for why this pattern stays full-form. The tenancy
+        // check matters more here than anywhere: this route DELETES a project.
+        std::string project = projectFor(*d, req, 1);
         if (project == "default") throw ApiError(ErrCode::Unprocessable, "protected", "cannot drop the default project");
         for (const auto& m : d->registry.list(project))
             d->db.client().dropCollection(qualify(project, m.name));

+ 12 - 12
src/handlers/relations.cpp

@@ -47,9 +47,9 @@ nlohmann::json impactsJson(const std::string& project,
 void registerRelationRoutes(ApiServer& s) {
     auto& svr = s.raw(); ServerDeps* d = &s.deps();
 
-    svr.Post(R"(/api/v1/projects/([^/]+)/relations)",
+    svr.Post(R"(/api/v1(?:/projects/([^/]+))?/relations)",
              [d](const httplib::Request& req, httplib::Response& res) {
-        ApiKey k = requireKey(*d, req); std::string project = req.matches[1];
+        ApiKey k = requireKey(*d, req); std::string project = projectFor(*d, req, 1);
         requireAdmin(k); requireProjectAccess(k, project);
         auto body = bodyJson(req);
         std::string name  = body.is_object() ? body.value("name", "") : std::string(),
@@ -78,9 +78,9 @@ void registerRelationRoutes(ApiServer& s) {
                             {"validate_on_write", validateOnWrite}});
     });
 
-    svr.Get(R"(/api/v1/projects/([^/]+)/relations)",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/relations)",
             [d](const httplib::Request& req, httplib::Response& res) {
-        ApiKey k = requireKey(*d, req); std::string project = req.matches[1];
+        ApiKey k = requireKey(*d, req); std::string project = projectFor(*d, req, 1);
         requireAdmin(k); requireProjectAccess(k, project);
         auto defs = d->db.client().listRelations(project);
         nlohmann::json out = nlohmann::json::array();
@@ -88,30 +88,30 @@ void registerRelationRoutes(ApiServer& s) {
         sendJson(res, 200, {{"relations", out}});
     });
 
-    svr.Get(R"(/api/v1/projects/([^/]+)/relations/([^/]+))",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/relations/([^/]+))",
             [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        std::string project = req.matches[1], name = req.matches[2];
+        std::string project = projectFor(*d, req, 1), name = req.matches[2];
         requireAdmin(k); requireProjectAccess(k, project);
         auto info = d->db.client().getRelationInfo(qualify(project, name));
         if (!info) throw ApiError(ErrCode::NotFound, "not_found", "relation not found");
         sendJson(res, 200, relJson(project, *info));
     });
 
-    svr.Delete(R"(/api/v1/projects/([^/]+)/relations/([^/]+))",
+    svr.Delete(R"(/api/v1(?:/projects/([^/]+))?/relations/([^/]+))",
                [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        std::string project = req.matches[1], name = req.matches[2];
+        std::string project = projectFor(*d, req, 1), name = req.matches[2];
         requireAdmin(k); requireProjectAccess(k, project);
         if (!d->db.client().dropRelation(qualify(project, name)))
             throw ApiError(ErrCode::NotFound, "not_found", "relation not found");
         sendJson(res, 200, {{"dropped", name}});
     });
 
-    svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+)/delete-impact)",
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/documents/([^/]+)/delete-impact)",
             [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        std::string project = req.matches[1], coll = req.matches[2], id = req.matches[3];
+        std::string project = projectFor(*d, req, 1), coll = req.matches[2], id = req.matches[3];
         // Read-only: changes nothing, but child counts and sample ids are facts
         // about data, so it follows the collection's read grant.
         requireCapability(*d, k, req, project, coll, KeyOp::Read);
@@ -121,10 +121,10 @@ void registerRelationRoutes(ApiServer& s) {
                             {"impacts", impactsJson(project, r)}});
     });
 
-    svr.Put(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/relations-enforced)",
+    svr.Put(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/relations-enforced)",
             [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
-        std::string project = req.matches[1], coll = req.matches[2];
+        std::string project = projectFor(*d, req, 1), coll = req.matches[2];
         requireAdmin(k); requireProjectAccess(k, project);
         auto body = bodyJson(req);
         if (!body.is_object() || !body.contains("enforced") || !body["enforced"].is_boolean())

+ 45 - 0
src/handlers/settings.cpp

@@ -1,3 +1,4 @@
+#include "hostnames.hpp"
 #include "errors.hpp"
 #include "functions/net_guard.hpp"
 #include "json_http.hpp"
@@ -73,6 +74,50 @@ void registerSettingsRoutes(ApiServer& s) {
                                "client_ip_header_is_list must be a boolean");
             updated.clientIpHeaderIsList = body["client_ip_header_is_list"].get<bool>();
         }
+        // THE DEPLOYMENT'S OWN HOSTNAMES. Validated at the door for the same
+        // reason the CIDR list is: a malformed one here is silently dropped by
+        // HostRegistry::build, and the symptom would be the admin UI 404ing on
+        // the name an operator just configured with no clue why.
+        //
+        // SETTING EITHER OF THESE TURNS HOST GATING ON SERVICE-WIDE, which is
+        // the one genuinely dangerous thing on this route: from that moment
+        // every request carrying an unregistered Host answers 404, including
+        // the operator's own next request if they got the name wrong. That is
+        // why `admin_hostname` is refused when it is not a hostname we would
+        // serve, rather than stored and ignored.
+        if (body.contains("admin_hostname")) {
+            if (!body["admin_hostname"].is_string())
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "admin_hostname must be a string; \"\" disables it");
+            const std::string h = body["admin_hostname"].get<std::string>();
+            if (!h.empty() && !validHostname(normaliseHost(h)))
+                throw ApiError(ErrCode::Unprocessable, "invalid_hostname",
+                               "admin_hostname '" + h + "' is not a hostname this service will "
+                               "serve: no wildcard, port, scheme, path or single-label name",
+                               {{"host", h}});
+            updated.adminHostname = h.empty() ? "" : normaliseHost(h);
+        }
+        if (body.contains("global_hostnames")) {
+            if (!body["global_hostnames"].is_array())
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "global_hostnames must be an array of hostname strings; "
+                               "an empty array means none");
+            std::vector<std::string> hosts;
+            for (const auto& v : body["global_hostnames"]) {
+                if (!v.is_string())
+                    throw ApiError(ErrCode::Unprocessable, "validation",
+                                   "every global_hostnames entry must be a string");
+                const std::string h = normaliseHost(v.get<std::string>());
+                if (!validHostname(h))
+                    throw ApiError(ErrCode::Unprocessable, "invalid_hostname",
+                                   "global_hostnames entry '" + v.get<std::string>() +
+                                       "' is not a hostname this service will serve",
+                                   {{"host", v.get<std::string>()}});
+                hosts.push_back(h);
+            }
+            updated.globalHostnames = std::move(hosts);
+        }
+
         if (body.contains("trusted_proxy_cidrs")) {
             // VALIDATED HERE AND TOLERATED AT RUNTIME, deliberately in both
             // directions. A typo refused at the door is one an operator fixes

+ 11 - 1
src/handlers/stats.cpp

@@ -9,7 +9,17 @@ void registerStatsRoutes(ApiServer& s) {
 
     // Per-project stats (any key granted the project).
     svr.Get(R"(/api/v1/projects/([^/]+)/stats)", [d](const httplib::Request& req, httplib::Response& res) {
-        ApiKey k = requireKey(*d, req); std::string project = req.matches[1];
+        // NOT widened to the optional-project form, deliberately: the short
+        // shape of this route is `/api/v1/stats`, which is the GLOBAL
+        // admin-only stats route registered below - widening would make this
+        // handler swallow it and the global route unreachable. Verified in the
+        // real router, not inferred from registration order.
+        //
+        // It still resolves through projectFor, because the pattern being
+        // narrow is not a reason to skip the tenancy check: without it a
+        // project hostname could read ANOTHER project's stats whenever the
+        // caller's key happened to grant both.
+        ApiKey k = requireKey(*d, req); std::string project = projectFor(*d, req, 1);
         requireProjectAccess(k, project);
         auto cols = d->registry.list(project);
         uint64_t docs = 0;

+ 3 - 3
src/handlers/vectors.cpp

@@ -32,7 +32,7 @@ std::vector<smartbotic::database::Client::Filter> parseSearchFilters(const nlohm
 CollectionMeta requireVectorCollection(ServerDeps* d, const httplib::Request& req,
                                         std::string& projectOut, std::string& nameOut, KeyOp op) {
     ApiKey k = requireKey(*d, req);
-    projectOut = req.matches[1]; nameOut = req.matches[2];
+    projectOut = projectFor(*d, req, 1); nameOut = req.matches[2];
     requireCapability(*d, k, req, projectOut, nameOut, op);
     auto m = d->registry.get(projectOut, nameOut);
     if (!m) throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
@@ -89,7 +89,7 @@ std::vector<float> resolveVector(ServerDeps* d, const std::string& project,
 void registerVectorRoutes(ApiServer& s) {
     auto& svr = s.raw(); ServerDeps* d = &s.deps();
 
-    svr.Post(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/vectors)", [d](const httplib::Request& req, httplib::Response& res) {
+    svr.Post(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/vectors)", [d](const httplib::Request& req, httplib::Response& res) {
         std::string project, name; CollectionMeta meta = requireVectorCollection(d, req, project, name, KeyOp::Insert);
         auto body = bodyJson(req);
         std::vector<float> vec = resolveVector(d, project, meta, body, "vector", "text", wantsNoStore(req));
@@ -107,7 +107,7 @@ void registerVectorRoutes(ApiServer& s) {
         sendJson(res, 201, {{"id", newId}});
     });
 
-    svr.Post(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/search)", [d](const httplib::Request& req, httplib::Response& res) {
+    svr.Post(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/search)", [d](const httplib::Request& req, httplib::Response& res) {
         std::string project, name; CollectionMeta meta = requireVectorCollection(d, req, project, name, KeyOp::Search);
         auto body = bodyJson(req);
         std::vector<float> q = resolveVector(d, project, meta, body, "query_vector", "query_text", wantsNoStore(req));

+ 87 - 0
src/hostnames.cpp

@@ -118,11 +118,55 @@ HostRegistry HostRegistry::build(
         drop(h);
     }
     for (auto& [h, b] : candidate) r.map_.emplace(h, std::move(b));
+
+    // Gating is the DEPLOYMENT's decision, not a side effect of a project
+    // registering a name. See HostRegistry::gating().
+    r.gating_ = !adminHost.empty() || !globalHosts.empty();
     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;
+    }
+    return dot;
+}
+
+HostClaimRefusal mayClaimHostname(
+    std::string_view host, std::string_view project, const std::string& adminHost,
+    const std::vector<std::string>& globalHosts,
+    const std::unordered_map<std::string, std::vector<HostEntry>>& byProject) {
+    const std::string h = normaliseHost(host);
+    if (h.empty() || !validHostname(h)) return HostClaimRefusal::Invalid;
+
+    // The deployment's own names first, matching the registry's own precedence
+    // so the write-time answer and the read-time answer cannot disagree.
+    if (!adminHost.empty() && normaliseHost(adminHost) == h) return HostClaimRefusal::Reserved;
+    for (const std::string& g : globalHosts)
+        if (normaliseHost(g) == h) return HostClaimRefusal::Reserved;
+
+    for (const auto& [owner, entries] : byProject) {
+        if (owner == project) continue;  // re-claiming one's own is idempotent
+        for (const HostEntry& e : entries)
+            if (normaliseHost(e.host) == h) return HostClaimRefusal::Taken;
+    }
+    return HostClaimRefusal::None;
+}
+
 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
@@ -131,4 +175,47 @@ HostBinding HostRegistry::resolve(std::string_view hostHeader) const {
     return it->second;
 }
 
+ProjectResolution resolveProject(std::string_view pathProject, const HostBinding& host,
+                                 bool gatingOn) {
+    const bool havePath = !pathProject.empty();
+
+    if (!gatingOn) {
+        // No hostnames configured anywhere: the Host header decides nothing and
+        // the path is the only source, exactly as before this feature existed.
+        // A short path here names no project and is refused - it is not a
+        // request this deployment can serve, rather than one to guess at.
+        if (havePath) return {true, std::string(pathProject)};
+        return {};
+    }
+
+    // Gating is on, so an unregistered Host is refused here as well as at the
+    // pre-routing gate. Deliberately redundant: the gate is the one that
+    // answers 404 cheaply, and this is the one that cannot be bypassed by a
+    // route added later that forgets about it.
+    if (host.kind == HostKind::Unknown) return {};
+
+    if (havePath) {
+        if (host.kind == HostKind::Project) {
+            // Rule 1. The comparison is on the already-normalised project name
+            // from the registry against the raw path segment, so it is exact:
+            // a project hostname serves ONE project and naming another in the
+            // path is not a request it can satisfy.
+            if (pathProject == host.project) return {true, host.project};
+            return {};
+        }
+        return {true, std::string(pathProject)};  // rule 2
+    }
+
+    // Rule 3: the short form, which only a project hostname can complete.
+    if (host.kind == HostKind::Project && host.pathStyle == PathStyle::Short)
+        return {true, host.project};
+
+    // Rule 4. Includes a project hostname configured for the FULL style whose
+    // caller used the short one - refusing rather than accepting both shapes,
+    // because a hostname that answers to either makes `path_style` a hint
+    // instead of a setting, and an operator who chose `full` did so to keep the
+    // project visible in their own logs and proxies.
+    return {};
+}
+
 } // namespace svapi

+ 103 - 3
src/hostnames.hpp

@@ -105,17 +105,117 @@ public:
     /// 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.
+    /// True when nothing is registered at all.
     bool empty() const { return map_.empty(); }
 
+    /// IS HOST GATING IN FORCE? Driven by whether the DEPLOYMENT declared its
+    /// own identity (an admin or a global hostname), NEVER by a project having
+    /// registered one.
+    ///
+    /// THIS DISTINCTION WAS A DEFECT FOUND BY A TEST, and it was the dangerous
+    /// kind. Keying gating on "the registry is non-empty" means an admin who
+    /// attaches the first customer hostname to a project turns gating on for
+    /// the whole service - and their own next request, which carries whatever
+    /// Host they have always used, is answered 404. In production that is an
+    /// operator locking themselves out of the admin UI by adding a customer's
+    /// hostname, with no indication that the two were connected.
+    ///
+    /// Keyed this way the order is safe and matches how an operator thinks: the
+    /// deployment names itself first (and can then reach itself by that name),
+    /// and project hostnames are stored but INERT until it does - which is what
+    /// the `served` field on the hostnames route reports, so the state is
+    /// visible rather than mysterious.
+    bool gating() const { return gating_; }
+
     std::size_t size() const { return map_.size(); }
 
 private:
     std::unordered_map<std::string, HostBinding> map_;
+    bool gating_ = false;
+};
+
+/// Is this Host the operator reaching the service DIRECTLY - a bare IP literal
+/// or `localhost` - rather than by any configured name?
+///
+/// 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.
+///
+/// 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);
+
+/// The outcome of resolving which project a request is about.
+///
+/// A struct rather than an empty string meaning "no", because "" is also a
+/// legal-looking project name in a path and the two must not be one value.
+struct ProjectResolution {
+    bool ok = false;
+    std::string project;
 };
 
+/// WHICH PROJECT THIS REQUEST IS ABOUT. The tenancy decision, pure, so it can
+/// be tested exhaustively without a socket.
+///
+/// `pathProject` is the optional `/projects/<p>` segment - empty when the
+/// caller used the short form. `host` is what the Host header resolved to.
+///
+/// `gatingOn` IS AN EXPLICIT PARAMETER AND NOT INFERRED FROM `host`, which is
+/// the single most important thing about this signature. A deployment with no
+/// hostnames configured resolves EVERY Host to Unknown, and so does a
+/// configured deployment receiving a hostname nobody registered - the same
+/// value, two opposite meanings. Inferring would make the safe answer depend on
+/// a gate running in another function, and this codebase's most expensive bugs
+/// are all that shape: a check that lived in a function the route did not call,
+/// a premise held somewhere nothing enforced it. Passing it in means the
+/// decision carries its own context.
+///
+/// The rules, in order:
+///   1. path + project host      -> must MATCH, else refuse (404, never 403:
+///                                  a project hostname must not confirm that
+///                                  another project exists)
+///   2. path + admin/global host -> the path (today's behaviour, unchanged)
+///   3. no path + project host with `short` -> the host's project
+///   4. anything else            -> REFUSE
+///
+/// Rule 4 is the load-bearing one. A short path on the admin or global
+/// hostname names no project at all, and falling back to a default there would
+/// be a cross-tenant hole wearing routing's clothes.
+ProjectResolution resolveProject(std::string_view pathProject, const HostBinding& host,
+                                 bool gatingOn);
+
+/// Why a hostname may not be registered. `None` means it is acceptable.
+enum class HostClaimRefusal {
+    None,
+    Invalid,     ///< not a hostname we will serve (wildcard, port, single label, ...)
+    Taken,       ///< another project already holds it
+    Reserved,    ///< it is the deployment's own admin or global name
+};
+
+/// May `project` claim `host`, given what is already registered?
+///
+/// COLLISIONS ARE REFUSED AT WRITE TIME, NOT RESOLVED AT READ TIME, and that
+/// ordering is the whole point. `HostRegistry::build` also handles a collision
+/// - it has to, because a stored document can always be edited by hand - but
+/// the resolution available to it is "serve neither", which turns a typo into
+/// an outage for the project that had the name FIRST. Refusing the write costs
+/// the second project a 422 it can act on immediately.
+///
+/// A project RE-claiming a hostname it already holds is `None`, not `Taken`, so
+/// that writing a project's hostname list back unchanged is idempotent - the
+/// web UI reads the list, edits one entry and PUTs the whole thing, and a
+/// self-collision would make saving fail the second time.
+HostClaimRefusal mayClaimHostname(std::string_view host, std::string_view project,
+                                  const std::string& adminHost,
+                                  const std::vector<std::string>& globalHosts,
+                                  const std::unordered_map<std::string, std::vector<HostEntry>>& byProject);
+
 /// Is this a hostname a project may register?
 ///
 /// Deliberately strict, and WILDCARDS ARE REFUSED. A project registering

+ 7 - 1
src/project_settings.hpp

@@ -110,8 +110,14 @@ struct ProjectSettings {
     bool hasAnyOverrides() const {
         return hasEmbeddingOverrides() || defaultFunctionPolicy.has_value() ||
                maxFunctionWallTimeHttpMs.has_value() || maxFunctionWallTimeJobMs.has_value() ||
-               functionNetworkEgress.has_value();
+               functionNetworkEgress.has_value() || !hostnames.empty();
     }
+    // `hostnames` MUST be counted here. The settings PUTs call
+    // removeProject() when nothing is overridden, so without this a project
+    // whose ONLY override is a hostname list would have its document deleted
+    // by the very request that set it - a 200 followed by the hostname
+    // silently not existing. The failure would look like the registry not
+    // reloading, which is the wrong place to go looking.
 
     /// A project base URL must carry its own API key, otherwise the global
     /// credential would be sent to a foreign endpoint. A project key without a

+ 54 - 0
src/server.cpp

@@ -15,6 +15,25 @@
 
 namespace svapi {
 
+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{};
+
+    // 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
+    // empty string - but the size is guarded anyway, because a route registered
+    // WITHOUT the group would otherwise read past the end, and that failure
+    // would be a crash where this one is a 404.
+    const std::string pathProject =
+        group < req.matches.size() ? std::string(req.matches[group]) : std::string();
+
+    const ProjectResolution r = resolveProject(pathProject, host, gatingOn);
+    if (!r.ok)
+        throw ApiError(ErrCode::NotFound, "not_found", "no such project on this hostname");
+    return r.project;
+}
+
 ApiServer::ApiServer(ServerDeps deps) : d_(std::move(deps)) {}
 
 static bool keyExpired(const ApiKey& k) {
@@ -217,6 +236,41 @@ void ApiServer::registerRoutes() {
         // START of the request: zero the clock and forget the previous
         // request's slug. See access_log.hpp on why that ordering matters.
         beginRequestTrace();
+
+        // HOST GATE. Runs before everything, including authentication.
+        //
+        // It exists for the surfaces projectFor() cannot reach: the global
+        // routes that name no project (/api/v1/keys, /settings, /stats,
+        // /version), the web UI and the docs catalogue. Without it a project
+        // hostname would serve the admin UI and the complete operation list -
+        // which is precisely the surface withdrawn from the customer-facing
+        // name in 0.15.0 after five hours, for the reason that it publishes a
+        // catalogue of what to come back and try.
+        //
+        // SKIPPED ENTIRELY WHEN NOTHING IS REGISTERED, which is the default and
+        // every deployment today: the test fixture, the devstack and anything
+        // 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"));
+            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
+                // caller, and guessing is how one tenant answers for another.
+                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;
+            }
+        }
+
         if (req.method != "OPTIONS" && req.path.rfind("/api/", 0) == 0) {
             if (!resolveKey(d_, req)) {
                 sendJson(res, 401, errorBody("unauthorized", "missing or invalid credentials"));

+ 20 - 0
src/server.hpp

@@ -53,6 +53,26 @@ struct ServerDeps {
     FunctionJobQueue* jobs = nullptr;
 };
 
+/// WHICH PROJECT THIS REQUEST IS ABOUT. Call this instead of reading
+/// `req.matches[n]` for a project, everywhere, with no exceptions.
+///
+/// `group` is the optional `/projects/<p>` capture group, EMPTY when the caller
+/// used the short form on a project hostname. The decision is the pure
+/// `resolveProject()` in hostnames.hpp; this pulls the Host header and the
+/// registry snapshot out of the request and raises the refusal.
+///
+/// It THROWS rather than returning an empty string, because a handler that
+/// forgot to check would otherwise qualify a collection as `:name` and reach
+/// the database with a project nobody named. Refusing at the one place that
+/// knows is the only version of this a route added later cannot get wrong.
+///
+/// The refusal is 404 and NOT 403, deliberately: a project hostname must not
+/// confirm that another project exists - the same reasoning that keeps an
+/// out-of-scope collection ABSENT from the collections listing rather than
+/// refused there.
+std::string projectFor(ServerDeps& d, const httplib::Request& req, size_t group);
+
+
 class ApiServer {
 public:
     explicit ApiServer(ServerDeps deps);

+ 8 - 0
src/settings.cpp

@@ -20,6 +20,12 @@ Settings Settings::fromJson(const nlohmann::json& j) {
     s.captchaReadTimeoutSec      = j.value("captcha_read_timeout_sec",     s.captchaReadTimeoutSec);
     s.clientIpHeader             = j.value("client_ip_header",             s.clientIpHeader);
     s.clientIpHeaderIsList       = j.value("client_ip_header_is_list",     s.clientIpHeaderIsList);
+    s.adminHostname = j.value("admin_hostname", s.adminHostname);
+    if (j.contains("global_hostnames") && j["global_hostnames"].is_array()) {
+        s.globalHostnames.clear();
+        for (const auto& v : j["global_hostnames"])
+            if (v.is_string()) s.globalHostnames.push_back(v.get<std::string>());
+    }
     if (j.contains("trusted_proxy_cidrs") && j["trusted_proxy_cidrs"].is_array()) {
         std::vector<std::string> out;
         for (const auto& v : j["trusted_proxy_cidrs"])
@@ -61,6 +67,8 @@ nlohmann::json Settings::toJson() const {
             {"captcha_read_timeout_sec",   captchaReadTimeoutSec},
             {"client_ip_header",           clientIpHeader},
             {"client_ip_header_is_list",   clientIpHeaderIsList},
+            {"admin_hostname",             adminHostname},
+            {"global_hostnames",           globalHostnames},
             {"trusted_proxy_cidrs",        trustedProxyCidrs},
             {"embedding_cache_size",        embeddingCacheSize},
             {"embedding_cache_ttl_sec",     embeddingCacheTtlSec},

+ 235 - 0
tests/test_api_integration.cpp

@@ -5160,3 +5160,238 @@ TEST_F(ApiFixture, ThePagingFieldsArePRESENTEvenWhenNothingMatches) {
     EXPECT_FALSE(body["has_more"].get<bool>());
     EXPECT_TRUE(body["documents"].empty());
 }
+
+// ===========================================================================
+// PER-PROJECT HOSTNAMES (SV-132). The tenancy boundary, end to end.
+//
+// Everything above this point exercises the FULL path form on a Host nobody
+// registered, which is every deployment today. These tests are the only place
+// the SHORT form and the host gate are exercised at all, so they are written as
+// PAIRINGS throughout: a test that only asserted the refusal would pass just as
+// well against a server that refused everything, which is a strictly worse
+// defect than the one being prevented.
+//
+// Each test restores the empty registry on the way out, because host gating is
+// SERVICE-WIDE and a leaked hostname would 404 every later test in this serial
+// suite - and the failure would look like the later test's own bug.
+// ===========================================================================
+
+namespace {
+
+// RAII: put the registry back to EMPTY however the test leaves.
+//
+// Host gating is SERVICE-WIDE, so a leaked hostname would 404 every later test
+// in this serial suite - and the failure would surface as the later test's own
+// bug, in a different file, with nothing pointing here. It takes the port and
+// key as values rather than the fixture because the fixture's members are
+// protected and this has to live outside the class.
+struct HostGatingGuard {
+    int port;
+    std::string key;
+    std::string project;
+    ~HostGatingGuard() {
+        httplib::Client c("127.0.0.1", port);
+        c.set_default_headers({{"Authorization", "Bearer " + key}});
+        (void)c.Put(("/api/v1/projects/" + project + "/settings/hostnames").c_str(),
+                    nlohmann::json{{"hostnames", nlohmann::json::array()}}.dump(),
+                    "application/json");
+        (void)c.Put("/api/v1/settings",
+                    nlohmann::json{{"admin_hostname", ""},
+                                   {"global_hostnames", nlohmann::json::array()}}.dump(),
+                    "application/json");
+    }
+};
+
+} // namespace
+
+TEST_F(ApiFixture, AProjectHostnameIsStoredAndTheRouteSaysWhetherItIsSERVED) {
+    HostGatingGuard guard{port_, adminKey_, project_};
+    const std::string base = "/api/v1/projects/" + project_ + "/settings/hostnames";
+
+    // Stored while gating is OFF: `served` is the field that stops the list
+    // looking identical in force and not in force.
+    auto put = admin().Put(base.c_str(),
+        nlohmann::json{{"hostnames", {{{"host", "tenant.example.com"}, {"path_style", "short"}}}}}.dump(),
+        "application/json");
+    ASSERT_TRUE(put); ASSERT_EQ(put->status, 200) << put->body;
+    auto j = nlohmann::json::parse(put->body);
+    ASSERT_EQ(j.at("hostnames").size(), 1u);
+    EXPECT_EQ(j.at("hostnames")[0].at("host"), "tenant.example.com");
+    EXPECT_EQ(j.at("hostnames")[0].at("path_style"), "short");
+    EXPECT_FALSE(j.at("served").get<bool>()) << "no deployment hostname is set, so nothing is gated yet";
+
+    // It SURVIVES, which is the regression this pins: hasAnyOverrides() has to
+    // count hostnames, or the PUT's own removeProject() deletes the document it
+    // just wrote and the hostname silently does not exist.
+    auto get = admin().Get(base.c_str());
+    ASSERT_EQ(get->status, 200);
+    ASSERT_EQ(nlohmann::json::parse(get->body).at("hostnames").size(), 1u)
+        << "the hostname did not survive the write - hasAnyOverrides() is probably ignoring it";
+}
+
+TEST_F(ApiFixture, AProjectHostnameServesItsOWNProjectOnTheSHORTPathAndNOTAnotherProjects) {
+    HostGatingGuard guard{port_, adminKey_, project_};
+    const std::string other = "svapitest_otherhost";
+    db_->dropProject(other);
+    ASSERT_EQ(admin().Post("/api/v1/projects", nlohmann::json{{"name", other}}.dump(),
+                           "application/json")->status, 201);
+
+    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);
+    // Turning gating ON is a separate step, and it is what makes the rest real.
+    ASSERT_EQ(admin().Put("/api/v1/settings",
+        nlohmann::json{{"admin_hostname", "admin.example.com"}}.dump(), "application/json")->status, 200);
+
+    const std::string key = adminKey_;
+
+    // (1) THE SHORT FORM WORKS on the project hostname, and resolves to that
+    // project. This is the arm nothing else in the suite covers.
+    auto shortForm = request("GET", "/api/v1/collections", "", "", key,
+                             {{"Host", "tenant.example.com"}});
+    ASSERT_TRUE(shortForm);
+    EXPECT_EQ(shortForm->status, 200) << "the short form did not resolve: " << shortForm->body;
+
+    // (2) THE FULL FORM naming its OWN project also works there.
+    auto ownFull = request("GET", "/api/v1/projects/" + project_ + "/collections", "", "", key,
+                           {{"Host", "tenant.example.com"}});
+    ASSERT_TRUE(ownFull);
+    EXPECT_EQ(ownFull->status, 200) << ownFull->body;
+
+    // (3) THE CROSS-TENANT REFUSAL - the whole point. The SAME admin key, which
+    // is granted every project, naming ANOTHER project on this hostname. The
+    // key is deliberately held constant so this cannot pass for the wrong
+    // reason: it is the hostname refusing, not the authorization.
+    auto crossTenant = request("GET", "/api/v1/projects/" + other + "/collections", "", "", key,
+                               {{"Host", "tenant.example.com"}});
+    ASSERT_TRUE(crossTenant);
+    EXPECT_EQ(crossTenant->status, 404)
+        << "a project hostname served ANOTHER project to a key that happens to hold both: "
+        << crossTenant->body;
+
+    // (4) THE PAIRING for (3): the same request on the ADMIN hostname works.
+    // Without this, (3) would pass against a server that had simply broken the
+    // route for everyone.
+    auto adminHost = request("GET", "/api/v1/projects/" + other + "/collections", "", "", key,
+                             {{"Host", "admin.example.com"}});
+    ASSERT_TRUE(adminHost);
+    EXPECT_EQ(adminHost->status, 200)
+        << "the admin hostname must still reach every project: " << adminHost->body;
+
+    // (5) A SHORT path on the ADMIN hostname names NO project and is refused -
+    // rule 4, the load-bearing one. Falling back to a default here would be the
+    // cross-tenant hole wearing routing's clothes.
+    auto shortOnAdmin = request("GET", "/api/v1/collections", "", "", key,
+                                {{"Host", "admin.example.com"}});
+    ASSERT_TRUE(shortOnAdmin);
+    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.
+    auto unknownHost = request("GET", "/api/v1/projects/" + project_ + "/collections", "", "", key,
+                               {{"Host", "nobody.example.com"}});
+    ASSERT_TRUE(unknownHost);
+    EXPECT_EQ(unknownHost->status, 404) << 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
+    // 0.15.0 because it publishes a list of what to come back and try. Paired
+    // against the admin hostname so this cannot pass by everything 404ing.
+    auto docsOnProject = request("GET", "/docs", "", "", key, {{"Host", "tenant.example.com"}});
+    ASSERT_TRUE(docsOnProject);
+    EXPECT_EQ(docsOnProject->status, 404) << "the docs catalogue is served on a project hostname";
+    auto healthOnProject = request("GET", "/healthz", "", "", key, {{"Host", "tenant.example.com"}});
+    ASSERT_TRUE(healthOnProject);
+    EXPECT_EQ(healthOnProject->status, 200)
+        << "/healthz must stay reachable everywhere so a monitor needs no credential";
+
+    db_->dropProject(other);
+}
+
+TEST_F(ApiFixture, AHostnameHeldByAnotherProjectIsREFUSEDAtWriteTime) {
+    HostGatingGuard guard{port_, adminKey_, project_};
+    const std::string other = "svapitest_hostclash";
+    db_->dropProject(other);
+    ASSERT_EQ(admin().Post("/api/v1/projects", nlohmann::json{{"name", other}}.dump(),
+                           "application/json")->status, 201);
+
+    ASSERT_EQ(admin().Put(("/api/v1/projects/" + project_ + "/settings/hostnames").c_str(),
+        nlohmann::json{{"hostnames", {"taken.example.com"}}}.dump(), "application/json")->status, 200);
+
+    // Refused at write time rather than resolved at read time: the read-time
+    // resolution is "serve neither", which would turn this typo into an outage
+    // for the project that had the name first.
+    auto clash = admin().Put(("/api/v1/projects/" + other + "/settings/hostnames").c_str(),
+        nlohmann::json{{"hostnames", {"taken.example.com"}}}.dump(), "application/json");
+    ASSERT_TRUE(clash);
+    EXPECT_EQ(clash->status, 422) << clash->body;
+    EXPECT_EQ(nlohmann::json::parse(clash->body).at("error").at("code"), "hostname_taken");
+
+    // PAIRING: a free name on the same project in the same breath succeeds, so
+    // the refusal is about the collision and not about the project or the route.
+    auto free_ = admin().Put(("/api/v1/projects/" + other + "/settings/hostnames").c_str(),
+        nlohmann::json{{"hostnames", {"free.example.com"}}}.dump(), "application/json");
+    ASSERT_TRUE(free_);
+    EXPECT_EQ(free_->status, 200) << free_->body;
+
+    // And re-claiming one's OWN name is idempotent, so the web UI's
+    // read-edit-PUT-the-whole-list cycle does not fail on its second save.
+    auto again = admin().Put(("/api/v1/projects/" + project_ + "/settings/hostnames").c_str(),
+        nlohmann::json{{"hostnames", {"taken.example.com"}}}.dump(), "application/json");
+    ASSERT_TRUE(again);
+    EXPECT_EQ(again->status, 200) << again->body;
+
+    (void)admin().Put(("/api/v1/projects/" + other + "/settings/hostnames").c_str(),
+        nlohmann::json{{"hostnames", nlohmann::json::array()}}.dump(), "application/json");
+    db_->dropProject(other);
+}
+
+TEST_F(ApiFixture, AWildcardAndTheDeploymentsOwnNameAreRefusedWithTHEIROWNSlugs) {
+    HostGatingGuard guard{port_, adminKey_, project_};
+    const std::string base = "/api/v1/projects/" + project_ + "/settings/hostnames";
+
+    // Three slugs rather than one, because the remedies differ: change the
+    // value, negotiate for the name, or you cannot have it at all.
+    auto wild = admin().Put(base.c_str(),
+        nlohmann::json{{"hostnames", {"*.example.com"}}}.dump(), "application/json");
+    ASSERT_TRUE(wild); EXPECT_EQ(wild->status, 422);
+    EXPECT_EQ(nlohmann::json::parse(wild->body).at("error").at("code"), "invalid_hostname")
+        << "a wildcard must be refused in the REGISTRY - it belongs in a certificate, where a "
+           "wrong match fails a handshake instead of serving data";
+
+    ASSERT_EQ(admin().Put("/api/v1/settings",
+        nlohmann::json{{"admin_hostname", "admin.example.com"}}.dump(), "application/json")->status, 200);
+    auto reserved = request("PUT", base, nlohmann::json{{"hostnames", {"admin.example.com"}}}.dump(),
+                            "application/json", adminKey_, {{"Host", "admin.example.com"}});
+    ASSERT_TRUE(reserved); EXPECT_EQ(reserved->status, 422) << reserved->body;
+    EXPECT_EQ(nlohmann::json::parse(reserved->body).at("error").at("code"), "hostname_reserved")
+        << "a project claiming the admin hostname would be handed the web UI and the docs catalogue";
+}
+
+TEST_F(ApiFixture, TheGlobalStatsRouteSurvivesTheProjectRouteWideningBesideIt) {
+    // A REGRESSION TEST FOR A COLLISION CLASS, not for one route.
+    //
+    // `/api/v1/projects/(p)/stats` must NOT be widened to the optional-project
+    // form, because its short shape is `/api/v1/stats` - the GLOBAL admin stats
+    // route registered 11 lines below it in the same file. Widened, the project
+    // handler swallows every request to the global one and it becomes
+    // unreachable. The same trap applies to the bare `/api/v1/projects/(p)`,
+    // whose short shape is the literal `/api/v1`.
+    //
+    // This asserts the BEHAVIOUR rather than the pattern text, so it still
+    // fires if someone widens the route in a different spelling.
+    auto r = admin().Get("/api/v1/stats");
+    ASSERT_TRUE(r); ASSERT_EQ(r->status, 200) << r->body;
+    auto j = nlohmann::json::parse(r->body);
+    EXPECT_TRUE(j.contains("total_documents"))
+        << "/api/v1/stats answered with something other than the global stats shape - the "
+           "per-project stats route has probably been widened and is now swallowing it: " << r->body;
+    EXPECT_FALSE(j.contains("project"))
+        << "/api/v1/stats was answered by the PER-PROJECT handler with an empty project: " << r->body;
+
+    // PAIRING: the per-project route still works in its full form, so this
+    // cannot pass because project stats broke.
+    auto p = admin().Get(("/api/v1/projects/" + project_ + "/stats").c_str());
+    ASSERT_TRUE(p); ASSERT_EQ(p->status, 200) << p->body;
+    EXPECT_EQ(nlohmann::json::parse(p->body).at("project"), project_);
+}

+ 235 - 0
tests/test_hostnames.cpp

@@ -278,3 +278,238 @@ TEST(ProjectSettingsHostnames, AMalformedEntryIsSkippedWithoutLosingTheRest) {
     ASSERT_EQ(p.hostnames.size(), 1u);
     EXPECT_EQ(p.hostnames[0].host, "ok.example.com");
 }
+
+// --- the four rules: WHICH PROJECT a request is about -----------------------
+//
+// Mostly refusals, because an over-permissive rule here is a cross-tenant hole
+// and an over-strict one is a 404 somebody reports in an hour.
+
+using svapi::ProjectResolution;
+using svapi::resolveProject;
+
+namespace {
+HostBinding projectHost(const char* p, PathStyle s = PathStyle::Short) {
+    return HostBinding{HostKind::Project, p, s};
+}
+const HostBinding kAdmin{HostKind::Admin, {}, PathStyle::Full};
+const HostBinding kGlobal{HostKind::Global, {}, PathStyle::Full};
+const HostBinding kUnknown{};
+} // namespace
+
+TEST(ResolveProject, Rule1_APathOnItsOwnProjectHostIsAccepted) {
+    const ProjectResolution r = resolveProject("novitax", projectHost("novitax"), true);
+    EXPECT_TRUE(r.ok);
+    EXPECT_EQ(r.project, "novitax");
+}
+
+TEST(ResolveProject, Rule1_APathNamingANOTHERProjectOnAProjectHostIsREFUSED) {
+    // THE cross-tenant test. novitax's hostname must not serve justice-pa,
+    // however the caller spells the path.
+    for (const char* other : {"justice-pa", "toloajto", "", " novitax", "novitax "}) {
+        const ProjectResolution r = resolveProject(other, projectHost("novitax"), true);
+        if (std::string(other).empty()) continue;  // covered by rule 3 below
+        EXPECT_FALSE(r.ok) << "a project host served '" << other << "'";
+        EXPECT_TRUE(r.project.empty());
+    }
+}
+
+TEST(ResolveProject, Rule2_TheAdminAndGlobalHostsUseThePathUnchanged) {
+    // Today's behaviour, which must not move.
+    for (const HostBinding& h : {kAdmin, kGlobal}) {
+        const ProjectResolution r = resolveProject("justice-pa", h, true);
+        EXPECT_TRUE(r.ok);
+        EXPECT_EQ(r.project, "justice-pa");
+    }
+}
+
+TEST(ResolveProject, Rule3_TheShortFormOnAShortStyleProjectHostUsesTheHost) {
+    const ProjectResolution r = resolveProject("", projectHost("novitax", PathStyle::Short), true);
+    EXPECT_TRUE(r.ok);
+    EXPECT_EQ(r.project, "novitax");
+}
+
+TEST(ResolveProject, Rule4_AShortPathOnTheADMINorGLOBALHostIsREFUSED) {
+    // The load-bearing refusal. A short path there names NO project, and
+    // falling back to a default - the first project, the only project, any
+    // project - would be a cross-tenant hole wearing routing's clothes.
+    for (const HostBinding& h : {kAdmin, kGlobal}) {
+        const ProjectResolution r = resolveProject("", h, true);
+        EXPECT_FALSE(r.ok) << "a short path resolved to '" << r.project << "'";
+        EXPECT_TRUE(r.project.empty());
+    }
+}
+
+TEST(ResolveProject, Rule4_AShortPathOnAFULLStyleProjectHostIsREFUSED) {
+    // path_style is a SETTING, not a hint. A hostname that answered to both
+    // shapes would silently make the choice meaningless, and an operator who
+    // picked `full` did so to keep the project visible in their own logs.
+    const ProjectResolution r = resolveProject("", projectHost("novitax", PathStyle::Full), true);
+    EXPECT_FALSE(r.ok);
+}
+
+TEST(ResolveProject, AnUNKNOWNHostResolvesToNothingEvenWithAPath) {
+    // Defence in depth: the pre-routing gate answers this one more cheaply,
+    // and this is the arm a route added later cannot forget about.
+    EXPECT_FALSE(resolveProject("novitax", kUnknown, true).ok);
+    EXPECT_FALSE(resolveProject("", kUnknown, true).ok);
+}
+
+// --- gating OFF: every existing deployment, and the reason it is a parameter -
+
+TEST(ResolveProject, WithGatingOffThePathIsTheOnlySourceExactlyAsBefore) {
+    // No hostnames configured: the Host header decides nothing. This is what
+    // every deployment does today and what the test fixture and devstack do.
+    const ProjectResolution r = resolveProject("novitax", kUnknown, false);
+    EXPECT_TRUE(r.ok);
+    EXPECT_EQ(r.project, "novitax");
+}
+
+TEST(ResolveProject, WithGatingOffAShortPathIsStillREFUSED) {
+    // There is no hostname to complete it, so it names no project. Refusing is
+    // the only answer that cannot be a guess.
+    EXPECT_FALSE(resolveProject("", kUnknown, false).ok);
+}
+
+TEST(ResolveProject, UNKNOWNMeansTwoOppositeThingsAndOnlyTheFlagTellsThemApart) {
+    // The reason gatingOn is a PARAMETER rather than inferred from the binding.
+    // Identical host value, opposite correct answers - so a reader inferring
+    // from `host` alone would have to be wrong in one of these two cases, and
+    // the dangerous direction is serving the request.
+    EXPECT_TRUE(resolveProject("novitax", kUnknown, false).ok) << "gating off: serve it";
+    EXPECT_FALSE(resolveProject("novitax", kUnknown, true).ok) << "gating on: an unregistered host";
+}
+
+// --- write-time collision refusal -------------------------------------------
+
+using svapi::HostClaimRefusal;
+using svapi::mayClaimHostname;
+
+namespace {
+const std::unordered_map<std::string, std::vector<HostEntry>> kHeld = {
+    {"novitax", {{"nt.kb.smartbotics.ai", PathStyle::Short}}},
+    {"justice-pa", {{"pa.smartbotics.ai", PathStyle::Full}}},
+};
+HostClaimRefusal claim(const char* host, const char* project) {
+    return mayClaimHostname(host, project, "admin.smartbotics.ai",
+                            {"global-api-01.smartbotics.ai"}, kHeld);
+}
+} // namespace
+
+TEST(MayClaimHostname, AFreeNameIsAccepted) {
+    EXPECT_EQ(claim("new.smartbotics.ai", "toloajto"), HostClaimRefusal::None);
+}
+
+TEST(MayClaimHostname, ANameHELDByANOTHERProjectIsTAKEN) {
+    EXPECT_EQ(claim("nt.kb.smartbotics.ai", "toloajto"), HostClaimRefusal::Taken);
+    // And case or a trailing dot must not get round it - otherwise the refusal
+    // is a formality a caller can spell their way past.
+    EXPECT_EQ(claim("NT.KB.Smartbotics.AI", "toloajto"), HostClaimRefusal::Taken);
+    EXPECT_EQ(claim("nt.kb.smartbotics.ai.", "toloajto"), HostClaimRefusal::Taken);
+}
+
+TEST(MayClaimHostname, ReClaimingAHostnameYouAlreadyHoldIsIdempotent) {
+    // The web UI reads the list, edits one entry and PUTs the whole thing, so a
+    // self-collision would make the second save fail.
+    EXPECT_EQ(claim("nt.kb.smartbotics.ai", "novitax"), HostClaimRefusal::None);
+}
+
+TEST(MayClaimHostname, TheDeploymentsOwnNamesAreRESERVED) {
+    EXPECT_EQ(claim("admin.smartbotics.ai", "novitax"), HostClaimRefusal::Reserved);
+    EXPECT_EQ(claim("global-api-01.smartbotics.ai", "novitax"), HostClaimRefusal::Reserved);
+}
+
+TEST(MayClaimHostname, AnUnservableNameIsINVALIDRatherThanAccepted) {
+    // Distinct from Taken and Reserved because the remedy differs: a caller
+    // meeting Invalid must change the VALUE, not negotiate for the name.
+    EXPECT_EQ(claim("*.smartbotics.ai", "novitax"), HostClaimRefusal::Invalid);
+    EXPECT_EQ(claim("localhost", "novitax"), HostClaimRefusal::Invalid);
+    EXPECT_EQ(claim("has space.example.com", "novitax"), HostClaimRefusal::Invalid);
+    EXPECT_EQ(claim("", "novitax"), HostClaimRefusal::Invalid);
+}
+
+TEST(MayClaimHostname, TheWriteTimeAnswerAGREESWithTheRegistrysOwnPrecedence) {
+    // The two must never disagree: if a write is accepted, the registry must
+    // serve it, and if the registry would drop it, the write must refuse. This
+    // asserts the pairing rather than each side separately - a mismatch is how
+    // a project gets a 200 for a hostname that silently never works.
+    const char* free_ = "fresh.smartbotics.ai";
+    ASSERT_EQ(claim(free_, "toloajto"), HostClaimRefusal::None);
+    auto held = kHeld;
+    held["toloajto"] = {{free_, PathStyle::Short}};
+    const HostRegistry r = HostRegistry::build("admin.smartbotics.ai",
+                                               {"global-api-01.smartbotics.ai"}, held, nullptr);
+    EXPECT_EQ(r.resolve(free_).project, "toloajto") << "accepted at write time but not served";
+
+    // And the converse, for each refusal reason.
+    for (const char* bad : {"nt.kb.smartbotics.ai", "admin.smartbotics.ai", "*.smartbotics.ai"}) {
+        EXPECT_NE(claim(bad, "toloajto"), HostClaimRefusal::None) << bad;
+        auto h2 = kHeld;
+        h2["toloajto"] = {{bad, PathStyle::Short}};
+        const HostRegistry r2 = HostRegistry::build("admin.smartbotics.ai",
+                                                    {"global-api-01.smartbotics.ai"}, h2, nullptr);
+        EXPECT_NE(r2.resolve(bad).project, "toloajto")
+            << bad << " was refused at write time but the registry served it to the claimant";
+    }
+}
+
+// --- gating is the DEPLOYMENT's decision, and the way back in ---------------
+//
+// Both of these come from a defect an integration test found rather than from
+// the design: keying gating on "the registry is non-empty" meant attaching the
+// 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;
+
+TEST(HostGating, APROJECTHostnameAloneDoesNOTTurnGatingOn) {
+    // The defect. An admin adding a customer hostname must not lock themselves
+    // out of the admin UI, and nothing would have connected the two.
+    const HostRegistry r = HostRegistry::build(
+        "", {}, {{"novitax", {{"nt.kb.smartbotics.ai", PathStyle::Short}}}}, nullptr);
+    EXPECT_FALSE(r.gating()) << "a project hostname turned gating on by itself";
+    EXPECT_FALSE(r.empty()) << "it is still STORED - inert, not discarded";
+    EXPECT_EQ(r.resolve("nt.kb.smartbotics.ai").project, "novitax")
+        << "and it still resolves, so switching gating on later needs no re-entry";
+}
+
+TEST(HostGating, THEDEPLOYMENTNamingItselfIsWhatTurnsGatingOn) {
+    EXPECT_TRUE(HostRegistry::build("admin.example.com", {}, {}, nullptr).gating());
+    EXPECT_TRUE(HostRegistry::build("", {"global.example.com"}, {}, nullptr).gating());
+    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, 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, 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.
+    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);
+}