Parcourir la source

feat: serve a project's static files on its own hostname SV-132

Static files out of the database over HTTP with Content-Type, ETag and
caching, aliased by a `path` in the database's per-file metadata, served ONLY
on a project hostname and only when that project explicitly enables it. Design
in docs/superpowers/specs/2026-11-20-static-file-serving-design.md; web UI tab
alongside.

IT IS UNAUTHENTICATED, which is why it needs TWO independent conditions rather
than one: the request arrived on a project hostname AND that project turned it
on. Neither implies the other, and `enabled` defaults to false because turning
it on publishes files that were private a moment earlier.

FIXES A LIVE DEFECT THIS WORK FOUND, and it was mine from this morning. The
SPA history fallback answered ANY extensionless 404 with the admin
`index.html` at status 200 - including on a project hostname, handing back the
exact surface withdrawn from the customer-facing name in 0.15.0. It ran from
`set_error_handler`, which fires for every 404 however produced, so my own host
gate's refusal was being converted into the admin shell. Measured live on the
new VM before the fix: `/api/*` and `/healthz` correctly 404 on an
unregistered host while `/` answered 200 with the shell. Data was never
reachable - every `/api/` path stayed refused - so the exposure was the static
HTML and not access. Now gated on HostKind::Admin, pinned by
`TheAdminSPAShellIsNOTServedOnAProjectHostname` with the pairing that the admin
hostname still gets the shell. Falsified: removing the gate reddens exactly
that test.

SHADOWING IS ENFORCED EXPLICITLY, NOT BY REGISTRATION ORDER. cpp-httplib's
order is pre-routing, then static mounts, then handlers - so a last-resort
handler sits BEHIND `set_mount_point("/", webuiDir)` and a `/` mount would
answer with the admin SPA. Static dispatch therefore runs from the pre-routing
handler and refuses any service-owned path itself. Falsified by commenting out
that refusal: `GET /api/v1/collections` on a project hostname answered
`<html>ROOTFILE</html>` - the tenant's own file served in place of the API.

A DATABASE-LAYER GAP FOUND BY MEASUREMENT, to be routed upstream: `uploadFile`
stores per-file `metadata` and `getFileInfo` returns it, but `listFiles`
returns every record with an EMPTY map. `FileStore::hydrateMetadata()` re-fetches
when the listing left it empty, written so it becomes a no-op the day the
listing carries it. A fast path keeps the normal case at two calls.

The spec's own shadowing test was WRONG and the implementation caught it:
`/api/v1/version` is not served on a project hostname at all, so it cannot
distinguish "shadowed by static" from "refused by the gate". The test uses
`/api/v1/collections` instead and additionally asserts `/api/v1/version`
answers the gate's own message, which is the discriminator.

`index: ""` is a VALUE meaning "no SPA fallback", not an absent key - decided by
contains(), round-tripped, and pinned both pure and in integration.

32 new tests, 1519/1519 serial, zero pending build steps, verified by my own
build and run rather than on report.
fszontagh il y a 6 jours
Parent
commit
c58c4a631d

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.19.0
+0.19.1

+ 1 - 1
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.19.0",
+    "version": "0.19.1",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {

+ 130 - 0
docs/superpowers/specs/2026-11-20-static-file-serving-design.md

@@ -0,0 +1,130 @@
+# Serving a project's static files on its own hostname
+
+Owner's request, 2026-11-20: serve small images, chunked JS and HTML out of the
+database over HTTP, with correct `Content-Type`, caching and `ETag`; aliased
+paths (`/img/something.png`) taken from the database's file metadata;
+configurable in the web UI; **allowed only when the project has at least one
+hostname**; and a configurable mount so `https://nt.kb.smartbotics.ai/` or
+`https://nt.kb.smartbotics.ai/something` both work.
+
+## What makes this different from every other route here
+
+**It is UNAUTHENTICATED and it is a browser surface.** Everything else under
+`/api/` requires a key. A browser fetching `/img/logo.png` carries no
+credential and cannot be given one, so this is the first deliberately public
+read path in the service besides `/fn/` and `/healthz`.
+
+That is the whole reason for the gate below. Two independent conditions must
+both hold before a single byte is served:
+
+1. the request arrived on a **project hostname** (`HostKind::Project`), and
+2. that project has **explicitly enabled** static serving.
+
+Neither implies the other. A project may hold a hostname and serve no files; a
+project may have files and no hostname, in which case they stay private.
+Serving on the admin or global hostname is refused outright - those names carry
+the operator surface, and a tenant's HTML rendered there would be same-origin
+with the admin UI.
+
+## Configuration
+
+In the per-project settings document, beside `hostnames`:
+
+```json
+"static": {
+  "enabled": false,
+  "mount": "/",
+  "index": "index.html",
+  "cache_control": "public, max-age=300"
+}
+```
+
+- `enabled` - **false by default**, and the default must stay false. Turning
+  this on publishes files that were private a moment earlier, so it is an act,
+  not an inherited state.
+- `mount` - where the tree appears. `/` or `/something`. Normalised to a
+  leading slash and no trailing slash.
+- `index` - the SPA fallback served for a path that matches no file. `""`
+  disables it, and then an unmatched path is a plain 404. It is NOT a wildcard
+  rewrite: the file must exist.
+- `cache_control` - sent verbatim. The default is deliberately short, because a
+  long max-age on a path with no content hash in it is how a tenant ships a
+  change nobody can see for a day.
+
+Admin-only to write, like `hostnames` and the function policy, and for the same
+reason: it decides what the world can reach.
+
+## Path aliasing
+
+The database's file records carry `std::map<std::string, std::string> metadata`
+(`FileUploadMeta::metadata`, `FileRecord::metadata`), which our `StoredFile`
+currently drops. The served path lives there under the key **`path`**:
+
+```
+metadata["path"] = "/img/something.png"
+```
+
+This is necessary rather than stylistic: our file NAMES are a single path
+segment (`[^/]+`, charset-restricted), so `assets/index-a1b2.js` cannot be a
+name. The alias is the only way to express a tree.
+
+A file with no `path` metadata is **not reachable over the static mount at
+all**. It stays a private file addressable only through the authenticated
+`/api/.../files/{name}` route. Absence means private; it never falls back to
+serving by name.
+
+## The three hazards, and what is done about them
+
+**Shadowing.** With `mount: "/"`, a naive handler would swallow `/api/v1/...`
+and `/fn/...`. The static handler must therefore refuse to serve any path whose
+first segment is `api`, `fn`, or that equals `/healthz`, regardless of mount -
+and a mount that would itself sit under those prefixes is refused at write time
+with 422. State it as the rule: **the service's own surfaces always win**.
+
+**Traversal.** `..` in any segment is refused, before normalisation and after.
+The lookup is an exact match on the stored `path` metadata, never a filesystem
+join, so there is no path to escape - but the check stays, because the next
+person to touch this may introduce one.
+
+**Enumeration.** There is no directory listing, ever, and a path that matches no
+file answers the same 404 whether the project has one file or a thousand.
+
+## ETag and caching
+
+The stored checksum is already computed and returned as `X-File-Checksum` on
+the authenticated route. Use it as a **strong ETag**: `ETag: "<checksum>"`.
+
+`If-None-Match` must be honoured with a **304** carrying the ETag and
+`Cache-Control` and no body. This is the single highest-value part of the
+feature for an SPA, because the alternative is re-sending every chunk on every
+load.
+
+`Content-Type` comes from the stored `contentType` and is never sniffed from
+the extension. A file stored with the wrong type is a tenant's mistake to fix,
+and guessing would make the stored value a lie that sometimes works.
+
+## Ceilings, stated so nobody rediscovers them
+
+`max_file_bytes` (global setting, default 2 MiB) bounds what can be stored, so
+that is the per-file ceiling for anything served here. There is no separate
+static ceiling and there should not be a second number meaning nearly the same
+thing. The per-run 1 MiB `ctx.files` limit does NOT apply - that bounds what one
+function may load into a JS heap, and this path never enters the runtime.
+
+## Testing
+
+- Pure: mount normalisation, the shadowing rule, traversal refusal, and
+  `path` → file resolution, all without a socket.
+- Integration, as PAIRINGS throughout:
+  - a file with `path` metadata is served on the project hostname with the
+    right `Content-Type` and ETag, **and** the same file is 404 on the admin
+    hostname;
+  - `If-None-Match` with the right ETag gives 304, **and** with a wrong one
+    gives 200 - the pairing, because a 304-always handler would pass the first
+    half alone;
+  - with `enabled: false` the same request is 404, **and** flipping it to true
+    makes it 200, so the switch is proven to be the thing that decides;
+  - `/api/v1/version` still answers on a project hostname with `mount: "/"`,
+    which is the shadowing regression.
+- Falsification: make the static handler run before the API routes and confirm
+  the shadowing test goes red.

+ 2 - 0
src/CMakeLists.txt

@@ -8,6 +8,7 @@ add_library(vectorapi_core STATIC
     filters.cpp
     client_ip.cpp
     hostnames.cpp
+    static_serve.cpp
     cert_store.cpp
     tls_certs.cpp
     access_log.cpp
@@ -52,6 +53,7 @@ add_library(vectorapi_core STATIC
     handlers/project_settings.cpp
     handlers/project_secrets.cpp
     handlers/files.cpp
+    handlers/static_files.cpp
     handlers/export.cpp
     handlers/relations.cpp
     handlers/functions.cpp

+ 121 - 2
src/file_store.cpp

@@ -1,5 +1,7 @@
 #include "file_store.hpp"
 
+#include "static_serve.hpp"
+
 #include <algorithm>
 
 namespace svapi {
@@ -14,6 +16,16 @@ constexpr size_t kMaxNameLen = 128;
 /// paginating to chase it would hide the problem rather than fix it.
 constexpr uint32_t kNameLookupLimit = 100;
 
+/// One page of the path scan, and the ceiling on how far it will go.
+///
+/// The path lookup has no server-side filter to lean on (see infoByPath), so
+/// it walks the project's files. The cap exists so an unauthenticated request
+/// cannot turn into an unbounded walk; a project holding more files than this
+/// cannot serve the ones past the cap, which is a real limit and is documented
+/// rather than papered over.
+constexpr uint32_t kPathScanPage = 200;
+constexpr uint32_t kPathScanMaxRecords = 5000;
+
 bool allowedNameChar(unsigned char c) {
     return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
            c == '.' || c == '-' || c == '_';
@@ -22,11 +34,18 @@ bool allowedNameChar(unsigned char c) {
 } // namespace
 
 nlohmann::json StoredFile::toJson() const {
+    // `metadata` is emitted UNCONDITIONALLY, empty object included, so its
+    // absence means exactly one thing - a server older than this release -
+    // rather than also meaning "this file has none". A field present only when
+    // non-empty is this codebase's most repeated trap.
+    nlohmann::json meta = nlohmann::json::object();
+    for (const auto& [k, v] : metadata) meta[k] = v;
     return {{"name", name},
             {"content_type", contentType},
             {"size", size},
             {"checksum", checksum},
-            {"created_at", createdAt}};
+            {"created_at", createdAt},
+            {"metadata", std::move(meta)}};
 }
 
 std::string fileNameRejection(const std::string& name) {
@@ -66,11 +85,34 @@ std::optional<smartbotic::database::Client::FileRecord> FileStore::newestRecord(
         if (f.related_id != project || f.name != name) continue;
         if (!best || f.created_at > best->created_at) best = f;
     }
+    if (best) hydrateMetadata(*best);
     return best;
 }
 
+void FileStore::hydrateMetadata(smartbotic::database::Client::FileRecord& rec) {
+    // MEASURED 2026-11-20 AGAINST THE DEPLOYED CLIENT AND SERVER: `uploadFile`
+    // STORES the per-file metadata map and `getFileInfo` RETURNS it, while
+    // `listFiles` returns every record with an EMPTY map. A probe uploading a
+    // file with `metadata["path"]` read it back from getFileInfo and got
+    // nothing at all from a list of the same record.
+    //
+    // So anything that needs metadata has to pay a second call per record.
+    // That is the database's gap rather than ours and has been reported there;
+    // what this does is make our side correct in the meantime.
+    //
+    // It is written as "fetch when the list left it empty" rather than "always
+    // fetch", so the day the list carries metadata this becomes a no-op with
+    // no code change. The cost of that shape is that a file with genuinely NO
+    // metadata pays the extra call every time - which is the right way round,
+    // since the alternative is silently reporting an empty map for a file that
+    // has one.
+    if (!rec.metadata.empty() || rec.id.empty()) return;
+    if (auto full = db_.client().getFileInfo(rec.id)) rec.metadata = full->metadata;
+}
+
 StoredFile FileStore::put(const std::string& project, const std::string& name,
-                          const std::vector<uint8_t>& bytes, const std::string& contentType) {
+                          const std::vector<uint8_t>& bytes, const std::string& contentType,
+                          const std::map<std::string, std::string>& metadata) {
     // Collected BEFORE the upload, so the new record is not in the list and
     // cannot delete itself.
     std::vector<std::string> superseded;
@@ -85,6 +127,7 @@ StoredFile FileStore::put(const std::string& project, const std::string& name,
     meta.file_type = kFileTypeMarker;
     meta.related_id = project;
     meta.is_public = false;
+    meta.metadata = metadata;
     const auto up = db_.client().uploadFile(bytes, meta);
 
     // Only now, with the new bytes safely stored. A delete that fails leaves a
@@ -98,6 +141,7 @@ StoredFile FileStore::put(const std::string& project, const std::string& name,
     out.contentType = contentType;
     out.size = up.size;
     out.checksum = up.checksum;
+    out.metadata = metadata;
     if (auto rec = db_.client().getFileInfo(up.id)) out.createdAt = rec->created_at;
     return out;
 }
@@ -111,6 +155,7 @@ std::optional<StoredFile> FileStore::info(const std::string& project, const std:
     out.size = rec->size;
     out.checksum = rec->checksum;
     out.createdAt = rec->created_at;
+    out.metadata = rec->metadata;
     return out;
 }
 
@@ -124,9 +169,76 @@ std::optional<std::pair<StoredFile, std::vector<uint8_t>>> FileStore::get(
     meta.size = rec->size;
     meta.checksum = rec->checksum;
     meta.createdAt = rec->created_at;
+    meta.metadata = rec->metadata;
     return std::make_pair(meta, db_.client().downloadFile(rec->id));
 }
 
+std::optional<StoredFile> FileStore::infoByPath(const std::string& project,
+                                                const std::string& path) {
+    if (path.empty() || path == "/") return std::nullopt;
+
+    auto toStored = [](const smartbotic::database::Client::FileRecord& r) {
+        StoredFile out;
+        out.name = r.name;
+        out.contentType = r.mime_type;
+        out.size = r.size;
+        out.checksum = r.checksum;
+        out.createdAt = r.created_at;
+        out.metadata = r.metadata;
+        return out;
+    };
+    auto pathOf = [](const smartbotic::database::Client::FileRecord& r) -> std::string {
+        const auto it = r.metadata.find(kStaticPathMetadataKey);
+        return it == r.metadata.end() ? std::string() : it->second;
+    };
+
+    // THE FAST PATH, and it is an OPTIMISATION ONLY - the answer it gives is
+    // verified against the same metadata equality the scan uses, so it cannot
+    // serve a file whose stored path differs.
+    //
+    // It exists because the scan below is O(files in the project) in ROUND
+    // TRIPS, on an unauthenticated path. A caller who uploads `app.js` and
+    // serves it at `/assets/app.js` - the natural thing to do - is answered in
+    // two calls instead of N, because `listFiles` filters by name server-side.
+    // A caller whose name and last segment differ falls through and is correct
+    // but slow.
+    const std::string lastSegment = path.substr(path.rfind('/') + 1);
+    if (!lastSegment.empty() && fileNameRejection(lastSegment).empty()) {
+        if (auto rec = newestRecord(project, lastSegment); rec && pathOf(*rec) == path)
+            return toStored(*rec);
+    }
+
+    std::optional<smartbotic::database::Client::FileRecord> best;
+    uint32_t scanned = 0;
+    for (uint32_t offset = 0; scanned < kPathScanMaxRecords; offset += kPathScanPage) {
+        const auto page =
+            db_.client().listFiles(kFileTypeMarker, project, kPathScanPage, offset, "", "");
+        if (page.files.empty()) break;
+        for (const auto& f : page.files) {
+            ++scanned;
+            // BOTH the project re-check and the metadata match, in that order.
+            // Project isolation for files is OURS rather than the database's,
+            // and this is the one lookup reached by an UNAUTHENTICATED caller -
+            // so a change in what `related_id` filters would be a cross-tenant
+            // leak on a public path rather than a mis-sorted list.
+            if (f.related_id != project) continue;
+            // Skipped without a round trip: a file whose name IS the last
+            // segment was already tried and rejected by the fast path above.
+            if (f.name == lastSegment) continue;
+            auto rec = f;
+            hydrateMetadata(rec);
+            if (pathOf(rec) != path) continue;
+            // Newest wins, for the same reason newestRecord() takes the newest:
+            // an interrupted put can leave two records, and serving the older
+            // bytes some of the time is worse than always serving the newer.
+            if (!best || rec.created_at > best->created_at) best = std::move(rec);
+        }
+        if (!page.has_more) break;
+    }
+    if (!best) return std::nullopt;
+    return toStored(*best);
+}
+
 FileListing FileStore::listPage(const std::string& project, uint32_t limit, uint32_t offset) {
     // `project` is the client's `related_id` argument, so the database filters
     // by project server-side and `limit` is spent on this project's files
@@ -140,12 +252,19 @@ FileListing FileStore::listPage(const std::string& project, uint32_t limit, uint
     out.total = found.total_count;
     for (const auto& f : found.files) {
         if (f.related_id != project) continue;
+        // See hydrateMetadata: the list does not carry it, so a listing that
+        // did not hydrate would report every file as having no served path -
+        // an empty map that LOOKS like an answer. The cost is one extra call
+        // per row in the page, which is stated rather than hidden.
+        auto rec = f;
+        hydrateMetadata(rec);
         StoredFile s;
         s.name = f.name;
         s.contentType = f.mime_type;
         s.size = f.size;
         s.checksum = f.checksum;
         s.createdAt = f.created_at;
+        s.metadata = std::move(rec.metadata);
         out.files.push_back(std::move(s));
     }
     // Newest first WITHIN THE PAGE. Stated precisely because the sort happens

+ 43 - 1
src/file_store.hpp

@@ -1,6 +1,7 @@
 #pragma once
 #include "db_gateway.hpp"
 #include <cstdint>
+#include <map>
 #include <optional>
 #include <string>
 #include <vector>
@@ -52,6 +53,16 @@ struct StoredFile {
     std::string checksum;
     uint64_t createdAt = 0;
 
+    /// The database's own per-file metadata map, carried through rather than
+    /// dropped.
+    ///
+    /// IT USED TO BE DROPPED, and the cost was that the only way to express a
+    /// served PATH for a file - our names are a single charset-restricted
+    /// segment, so `assets/index-a1b2.js` cannot be one - had nowhere to live.
+    /// The static mount reads `metadata["path"]`; everything else here ignores
+    /// it, so carrying it is additive for every existing caller.
+    std::map<std::string, std::string> metadata;
+
     nlohmann::json toJson() const;
 };
 
@@ -87,8 +98,15 @@ public:
     /// It uploads FIRST and deletes afterwards: a failure then leaves the old
     /// file intact rather than destroying it on the way to a write that never
     /// landed.
+    ///
+    /// `metadata` REPLACES whatever the previous record carried rather than
+    /// merging with it, because this is a PUT: a caller re-uploading without a
+    /// path is saying the file has no path, and a merge would make removing one
+    /// impossible - the same reasoning the hostname list's whole-list replace
+    /// carries.
     StoredFile put(const std::string& project, const std::string& name,
-                   const std::vector<uint8_t>& bytes, const std::string& contentType);
+                   const std::vector<uint8_t>& bytes, const std::string& contentType,
+                   const std::map<std::string, std::string>& metadata = {});
 
     /// Metadata only, without moving the bytes.
     std::optional<StoredFile> info(const std::string& project, const std::string& name);
@@ -97,6 +115,21 @@ public:
     std::optional<std::pair<StoredFile, std::vector<uint8_t>>> get(const std::string& project,
                                                                    const std::string& name);
 
+    /// The newest file whose `path` metadata equals `path`, or nullopt.
+    ///
+    /// THE LOOKUP FOR THE STATIC MOUNT, and it is a SCAN: the client's
+    /// `listFiles` filters by type, project, checksum and name, and has no
+    /// metadata filter, so there is nothing to ask the database for. It pages
+    /// through this project's files and stops at `kPathScanMaxRecords`, which
+    /// bounds the worst case at the cost of making a project with more files
+    /// than that unable to serve the ones past the cap. Stated rather than
+    /// hidden, because the remedy if it ever bites is a server-side filter and
+    /// not a bigger number.
+    ///
+    /// A file with NO `path` metadata can never match, which is what makes
+    /// absence mean private.
+    std::optional<StoredFile> infoByPath(const std::string& project, const std::string& path);
+
     /// Newest first. `limit` is clamped by the caller, not here.
     std::vector<StoredFile> list(const std::string& project, uint32_t limit, uint32_t offset);
 
@@ -127,6 +160,15 @@ private:
     std::optional<smartbotic::database::Client::FileRecord> newestRecord(
         const std::string& project, const std::string& name);
 
+    /// Fill in a record's `metadata` when the listing left it empty.
+    ///
+    /// MEASURED: `listFiles` returns every record with an EMPTY metadata map
+    /// while `getFileInfo` returns the stored one, so anything that needs
+    /// metadata pays a second call per record. Reported to the database layer;
+    /// written as "fetch when empty" so it becomes a no-op the day the listing
+    /// carries it.
+    void hydrateMetadata(smartbotic::database::Client::FileRecord& rec);
+
     DbGateway& db_;
 };
 

+ 23 - 1
src/handlers/files.cpp

@@ -3,8 +3,10 @@
 #include "json_http.hpp"
 #include "query_params.hpp"
 #include "server.hpp"
+#include "static_serve.hpp"
 
 #include <algorithm>
+#include <map>
 
 namespace svapi {
 namespace {
@@ -161,10 +163,30 @@ void registerFileRoutes(ApiServer& s) {
                                                         !it->second.empty())
             type = it->second;
 
+        // THE SERVED PATH, as per-file metadata. It is a HEADER rather than a
+        // body field because the body IS the file - there is nowhere else to
+        // put it - and `X-File-Path` sits beside the `X-File-Checksum` the
+        // download already answers with.
+        //
+        // ABSENT MEANS NO PATH, and because a PUT replaces the record rather
+        // than merging into it, re-uploading without the header REMOVES the
+        // path and makes the file private again. That is the same whole-value
+        // replacement the hostname list and the key scope use, and it is the
+        // only shape in which a path can be removed at all.
+        std::map<std::string, std::string> metadata;
+        if (auto it = req.headers.find("X-File-Path"); it != req.headers.end() &&
+                                                       !it->second.empty()) {
+            const std::string why = staticPathError(it->second);
+            if (!why.empty())
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "X-File-Path: " + why);
+            metadata[kStaticPathMetadataKey] = it->second;
+        }
+
         const std::vector<uint8_t> bytes(req.body.begin(), req.body.end());
         FileStore store(d->db);
         const bool existed = store.info(project, name).has_value();
-        const StoredFile stored = store.put(project, name, bytes, type);
+        const StoredFile stored = store.put(project, name, bytes, type, metadata);
         // 201 for a new name, 200 for a replacement - the same distinction a
         // document PUT makes, so a caller can tell which happened.
         sendJson(res, existed ? 200 : 201, stored.toJson());

+ 103 - 0
src/handlers/project_settings.cpp

@@ -133,6 +133,37 @@ std::optional<int64_t> capFromJson(const nlohmann::json& v, const char* what) {
     return v.get<int64_t>();
 }
 
+/// What the static-serving route returns, from both the GET and the PUT so the
+/// two cannot drift.
+///
+/// `served` is the field that stops this looking identical in force and not in
+/// force, exactly as it does on the hostnames route - and here it answers a
+/// harder question, because serving needs THREE things to line up: the
+/// deployment must have named itself (so host gating is on), the project must
+/// hold at least one hostname, and `enabled` must be true. An admin who turns
+/// `enabled` on and sees nothing served is otherwise left guessing which of the
+/// three is missing.
+nlohmann::json staticViewJson(ServerDeps& d, const std::string& project,
+                              const ProjectSettings* p) {
+    const StaticConfig cfg = (p && p->staticServing) ? *p->staticServing : StaticConfig{};
+    const auto reg = d.settings.hostRegistry();
+    const bool gating = reg && reg->gating();
+    const bool hasHost = p != nullptr && !p->hostnames.empty();
+    // FLAT, with the four configured fields at the top level, so the body a
+    // caller PUTs and the body it GETs are the same shape. A nested `static`
+    // object would make the round trip asymmetric for no gain.
+    nlohmann::json out = cfg.toJson();
+    out["project"] = project;
+    // `configured` tells a UI whether the values above are STORED or are the
+    // built-in defaults being shown. Without it, a project that has never been
+    // configured is indistinguishable from one an admin deliberately set to
+    // the defaults.
+    out["configured"] = p != nullptr && p->staticServing.has_value();
+    out["has_hostname"] = hasHost;
+    out["served"] = cfg.enabled && gating && hasHost;
+    return out;
+}
+
 }  // namespace
 
 void registerProjectSettingsRoutes(ApiServer& s) {
@@ -369,6 +400,78 @@ void registerProjectSettingsRoutes(ApiServer& s) {
                             {"served", (bool)(reg && reg->gating())}});
     });
 
+    // ---- static file serving ---------------------------------------------
+    //
+    // ADMIN ONLY, like hostnames and the function policy, and for the strongest
+    // version of the same reason: this route decides what the WORLD can read
+    // without a credential. A project-manage key must not be able to publish
+    // its own project's files.
+    svr.Get(R"(/api/v1(?:/projects/([^/]+))?/settings/static)",
+            [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);
+        sendJson(res, 200, staticViewJson(*d, project, proj.get()));
+    });
+
+    svr.Put(R"(/api/v1(?:/projects/([^/]+))?/settings/static)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = projectFor(*d, req, 1);
+        requireAdmin(requireKey(*d, req));
+        auto body = bodyJson(req);
+
+        auto current = d->settings.projectSnapshot(project);
+        ProjectSettings updated = current ? *current : ProjectSettings{};
+        updated.project = project;
+        // Start from what is stored, or from the defaults when nothing is -
+        // so a PUT carrying only `{"enabled": true}` publishes at the
+        // documented default mount rather than at an empty one.
+        StaticConfig cfg = updated.staticServing ? *updated.staticServing : StaticConfig{};
+
+        if (body.contains("enabled")) {
+            if (!body.at("enabled").is_boolean())
+                throw ApiError(ErrCode::Unprocessable, "validation", "enabled must be a boolean");
+            cfg.enabled = body.at("enabled").get<bool>();
+        }
+        if (body.contains("mount")) {
+            if (!body.at("mount").is_string())
+                throw ApiError(ErrCode::Unprocessable, "validation", "mount must be a string");
+            cfg.mount = normaliseMount(body.at("mount").get<std::string>());
+        }
+        if (body.contains("index")) {
+            // An EMPTY index is meaningful - it disables the SPA fallback - so
+            // unlike the embedding overrides it is not refused, and unlike them
+            // null is not an "inherit" signal because there is nothing to
+            // inherit from.
+            if (!body.at("index").is_string())
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "index must be a string (\"\" disables the SPA fallback)");
+            cfg.index = body.at("index").get<std::string>();
+        }
+        if (body.contains("cache_control")) {
+            if (!body.at("cache_control").is_string())
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "cache_control must be a string");
+            cfg.cacheControl = body.at("cache_control").get<std::string>();
+        }
+
+        // Validated AFTER normalisation and on every PUT, not only when the
+        // mount changed: a stored document can be hand-edited, and a PUT is the
+        // one moment we can refuse what is there.
+        if (const std::string why = mountError(cfg.mount); !why.empty())
+            throw ApiError(ErrCode::Unprocessable, "invalid_mount", why);
+
+        updated.staticServing = cfg;
+        // hasAnyOverrides() counts staticServing, so this cannot delete the
+        // document it just wrote - the trap hostnames hit once already.
+        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);
+        sendJson(res, 200, staticViewJson(*d, project, proj.get()));
+    });
+
     svr.Delete(R"(/api/v1(?:/projects/([^/]+))?/settings/embeddings)",
                [d](const httplib::Request& req, httplib::Response& res) {
         std::string project = projectFor(*d, req, 1);

+ 125 - 0
src/handlers/static_files.cpp

@@ -0,0 +1,125 @@
+#include "errors.hpp"
+#include "file_store.hpp"
+#include "json_http.hpp"
+#include "project_settings.hpp"
+#include "server.hpp"
+#include "static_serve.hpp"
+
+namespace svapi {
+namespace {
+
+/// Does `If-None-Match` name this representation?
+///
+/// A comma-separated list and `*` are both legal, so a naive equality test
+/// would re-send every chunk to a client that happened to hold two cached
+/// entries. Exact match per element: our ETags are strong (the stored
+/// checksum), so there is no weak-comparison arm to get wrong.
+bool etagMatches(const std::string& header, const std::string& etag) {
+    size_t i = 0;
+    while (i <= header.size()) {
+        const size_t comma = header.find(',', i);
+        const size_t end = comma == std::string::npos ? header.size() : comma;
+        size_t b = i, e = end;
+        while (b < e && (header[b] == ' ' || header[b] == '\t')) ++b;
+        while (e > b && (header[e - 1] == ' ' || header[e - 1] == '\t')) --e;
+        const std::string_view one(header.data() + b, e - b);
+        if (one == "*" || one == etag) return true;
+        if (comma == std::string::npos) break;
+        i = comma + 1;
+    }
+    return false;
+}
+
+} // namespace
+
+bool serveProjectStatic(ServerDeps& d, const std::string& project, const httplib::Request& req,
+                        httplib::Response& res) {
+    // GET only. A HEAD would have to be answered without a body, and
+    // cpp-httplib's own handling of that for a pre-routing response is not
+    // something this path should be guessing about - so it is left to fall
+    // through to a plain 404 rather than served half-right.
+    if (req.method != "GET") return false;
+
+    const auto ps = d.settings.projectSnapshot(project);
+    // BOTH conditions, and neither implies the other: the caller has already
+    // established that this is a project hostname, and this establishes that
+    // the project has explicitly turned serving on. A project may hold a
+    // hostname and serve no files.
+    if (!ps || !ps->staticServing || !ps->staticServing->enabled) return false;
+    const StaticConfig& cfg = *ps->staticServing;
+
+    // THE SHADOWING RULE. `resolveStaticPath` refuses a service-owned path and
+    // a `..` segment before it looks at the mount at all, so `mount: "/"`
+    // cannot swallow `/api/v1/...`, `/fn/...` or `/healthz`. Returning false
+    // here hands the request back to the router, which is what makes those
+    // surfaces still work on a project hostname.
+    const auto alias = resolveStaticPath(cfg.mount, req.path);
+    if (!alias) return false;
+
+    FileStore store(d.db);
+    auto file = store.infoByPath(project, *alias);
+    if (!file) {
+        // The SPA fallback. NOT a wildcard rewrite: the index file must exist,
+        // and when it does not this is a plain 404.
+        const std::string idx = indexAlias(cfg.index);
+        if (!idx.empty()) file = store.infoByPath(project, idx);
+    }
+    if (!file) {
+        // THE SAME 404 whether the project holds one file or a thousand, and
+        // never a directory listing. Answered here rather than handed back to
+        // the router, because the path is inside a mount this project claimed -
+        // falling through would let the admin web UI's own mount answer for it.
+        res.status = 404;
+        sendJson(res, 404, errorBody("not_found", "not found"));
+        return true;
+    }
+
+    // A STRONG ETag from the stored checksum, which is already computed and is
+    // already handed out as `X-File-Checksum` on the authenticated route.
+    const std::string etag = "\"" + file->checksum + "\"";
+    res.set_header("ETag", etag);
+    res.set_header("Cache-Control", cfg.cacheControl);
+
+    if (auto it = req.headers.find("If-None-Match");
+        it != req.headers.end() && !file->checksum.empty() && etagMatches(it->second, etag)) {
+        // 304 carries the ETag and Cache-Control and NO body - the single
+        // highest-value part of this feature for an SPA, because the
+        // alternative is re-sending every chunk on every load.
+        res.status = 304;
+        return true;
+    }
+
+    auto got = store.get(project, file->name);
+    if (!got) {
+        // Between the metadata read and the download the file went away. A 404
+        // rather than a 500: the caller's request is now simply about something
+        // that is not there.
+        res.status = 404;
+        sendJson(res, 404, errorBody("not_found", "not found"));
+        return true;
+    }
+
+    // THE STORED CONTENT TYPE, NEVER SNIFFED from the extension. A file stored
+    // with the wrong type is a tenant's mistake to fix, and guessing would make
+    // the stored value a lie that sometimes works.
+    const std::string type =
+        got->first.contentType.empty() ? "application/octet-stream" : got->first.contentType;
+    res.set_content(reinterpret_cast<const char*>(got->second.data()), got->second.size(), type);
+    res.status = 200;
+    return true;
+}
+
+/// Is `path` inside the mount this project would serve on?
+///
+/// The host gate needs this BEFORE it decides to 404, because its whitelist of
+/// project-scoped surfaces knows nothing about a mount an admin configured -
+/// and without this the gate would refuse the request before the static
+/// handler ever ran.
+bool projectStaticClaimsPath(ServerDeps& d, const std::string& project,
+                             const std::string& path) {
+    const auto ps = d.settings.projectSnapshot(project);
+    if (!ps || !ps->staticServing || !ps->staticServing->enabled) return false;
+    return resolveStaticPath(ps->staticServing->mount, path).has_value();
+}
+
+} // namespace svapi

+ 9 - 0
src/project_settings.cpp

@@ -54,6 +54,11 @@ ProjectSettings ProjectSettings::fromJson(const nlohmann::json& j) {
             if (!e.host.empty()) p.hostnames.push_back(std::move(e));
         }
     }
+    // Static serving. Present-but-default and ABSENT are kept apart, the same
+    // way the function policy is: an absent key follows whatever the built-in
+    // defaults become, a stored object does not.
+    if (j.contains("static") && j.at("static").is_object())
+        p.staticServing = StaticConfig::fromJson(j.at("static"));
     if (j.contains("embedding_connect_timeout_sec") &&
         j.at("embedding_connect_timeout_sec").is_number_integer())
         p.embeddingConnectTimeoutSec = j.at("embedding_connect_timeout_sec").get<uint32_t>();
@@ -95,6 +100,10 @@ nlohmann::json ProjectSettings::toJson() const {
         hosts.push_back({{"host", e.host},
                          {"path_style", e.pathStyle == PathStyle::Full ? "full" : "short"}});
     j["hostnames"] = std::move(hosts);
+    // Written only when configured, so round-tripping a project that never
+    // touched this does not pin today's defaults - including `enabled: false`,
+    // which would then look like a deliberate choice somebody made.
+    if (staticServing) j["static"] = staticServing->toJson();
 
     if (embeddingConnectTimeoutSec) j["embedding_connect_timeout_sec"] = *embeddingConnectTimeoutSec;
     if (embeddingReadTimeoutSec) j["embedding_read_timeout_sec"] = *embeddingReadTimeoutSec;

+ 20 - 1
src/project_settings.hpp

@@ -2,6 +2,7 @@
 #include "functions/wall_budget.hpp"
 #include "apikey.hpp"
 #include "hostnames.hpp"
+#include "static_serve.hpp"
 #include <nlohmann/json.hpp>
 #include <cstdint>
 #include <optional>
@@ -54,6 +55,19 @@ struct ProjectSettings {
     /// mechanism an embedding override does.
     std::vector<HostEntry> hostnames;
 
+    /// Serving this project's stored files over its own hostname.
+    ///
+    /// Absent means NEVER CONFIGURED, which is not the same as configured to
+    /// the defaults - the same distinction `defaultFunctionPolicy` keeps, and
+    /// for the same reason: a stored value survives a change to the built-in
+    /// defaults while an absent key follows them.
+    ///
+    /// It lives here rather than in a collection of its own so it rides the
+    /// subscribe stream this document already has, exactly like `hostnames` -
+    /// and because the two are read together on every request to a project
+    /// hostname, so splitting them would cost a second lookup in the hot path.
+    std::optional<StaticConfig> staticServing;
+
     std::optional<uint32_t> embeddingConnectTimeoutSec;
     std::optional<uint32_t> embeddingReadTimeoutSec;
 
@@ -110,7 +124,8 @@ struct ProjectSettings {
     bool hasAnyOverrides() const {
         return hasEmbeddingOverrides() || defaultFunctionPolicy.has_value() ||
                maxFunctionWallTimeHttpMs.has_value() || maxFunctionWallTimeJobMs.has_value() ||
-               functionNetworkEgress.has_value() || !hostnames.empty();
+               functionNetworkEgress.has_value() || !hostnames.empty() ||
+               staticServing.has_value();
     }
     // `hostnames` MUST be counted here. The settings PUTs call
     // removeProject() when nothing is overridden, so without this a project
@@ -118,6 +133,10 @@ struct ProjectSettings {
     // 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.
+    //
+    // `staticServing` MUST be counted for the identical reason, and it is the
+    // second instance of the same trap: a project whose only override is the
+    // static block would have its document deleted by the PUT that wrote it.
 
     /// 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

+ 49 - 1
src/server.cpp

@@ -333,6 +333,22 @@ void ApiServer::registerRoutes() {
     // Serve index.html so React Router can handle it. Excludes API/meta routes and asset
     // requests (paths with a file extension), which should keep their real 404.
     svr_->set_error_handler([this](const httplib::Request& req, httplib::Response& res) {
+        // NOT ON A PROJECT HOSTNAME. The fallback below serves the ADMIN SPA,
+        // and this handler runs for every 404 however it was produced - so
+        // without this clause any extensionless 404 on a tenant's hostname
+        // (`/foo`, and every miss inside a static mount) was answered with the
+        // operator's web UI at status 200. That is the surface deliberately
+        // withdrawn from the customer-facing name in 0.15.0, handed back by an
+        // error handler nobody thought of as a route.
+        //
+        // Found by the static-serving tests, where it turned an empty `index`
+        // - which must mean "a plain 404" - into the admin shell.
+        if (const auto reg = d_.settings.hostRegistry(); reg && reg->gating()) {
+            HostBinding host = reg->resolve(req.get_header_value("Host"));
+            if (host.kind == HostKind::Unknown && isLoopbackAddress(req.local_addr))
+                host = HostBinding{HostKind::Admin, {}, PathStyle::Full};
+            if (host.kind != HostKind::Admin) return httplib::Server::HandlerResponse::Unhandled;
+        }
         if (res.status == 404 && req.method == "GET" && !d_.webuiDir.empty()
             && req.path.rfind("/api/", 0) != 0
             && req.path.rfind("/ui/", 0) != 0
@@ -420,11 +436,38 @@ void ApiServer::registerRoutes() {
                     for (const char* r : kProjectResources)
                         if (first == r) { allowed = true; break; }
                 }
+                // THE CONFIGURED STATIC MOUNT, when the project enabled one.
+                // The whitelist above names RESOURCES this service invented; a
+                // mount is a path an admin chose, so it cannot be a literal
+                // here. Without this clause the gate 404s the request before
+                // serveProjectStatic() is ever reached, and the feature looks
+                // like it simply does not work.
+                if (!allowed && (req.method == "GET" || req.method == "HEAD") &&
+                    projectStaticClaimsPath(d_, host.project, req.path))
+                    allowed = true;
                 if (!allowed) {
                     sendJson(res, 404, errorBody("not_found", "not served on this host"));
                     return httplib::Server::HandlerResponse::Handled;
                 }
             }
+
+            // STATIC SERVING, deliberately here and not as a registered route.
+            //
+            // cpp-httplib's order is pre-routing, then the static MOUNTS, then
+            // the handlers - and this service mounts the admin web UI at `/`.
+            // A catch-all handler would therefore sit BEHIND that mount, so a
+            // project hostname with `mount: "/"` would be answered `/` with the
+            // admin SPA. Running here puts it ahead of the mounts, and the
+            // service's own surfaces are protected by isServiceOwnedPath()
+            // inside resolveStaticPath() rather than by registration order.
+            //
+            // UNAUTHENTICATED BY DESIGN, so it must precede the /api/ auth
+            // check below - which costs nothing, because that check only ever
+            // looks at /api/ paths and those are exactly what the static path
+            // refuses to claim.
+            if (host.kind == HostKind::Project && req.method != "OPTIONS" &&
+                serveProjectStatic(d_, host.project, req, res))
+                return httplib::Server::HandlerResponse::Handled;
         }
 
         if (req.method != "OPTIONS" && req.path.rfind("/api/", 0) == 0) {
@@ -473,7 +516,12 @@ void ApiServer::registerRoutes() {
             res.set_header("Access-Control-Allow-Origin", responseOrigin);
             if (responseOrigin != "*") res.set_header("Vary", "Origin");
         }
-        res.set_header("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Captcha-Token, Cache-Control");
+        // X-File-Path carries a file's served path on upload. It has to be
+        // listed here or a cross-origin upload fails its PREFLIGHT, which
+        // surfaces as the whole request never happening rather than as a
+        // refusal naming the header.
+        res.set_header("Access-Control-Allow-Headers",
+                       "Authorization, Content-Type, X-Captcha-Token, Cache-Control, X-File-Path");
         res.set_header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
     });
     svr_->Options(R"(.*)", [](const httplib::Request&, httplib::Response& res) { res.status = 204; });

+ 26 - 0
src/server.hpp

@@ -181,4 +181,30 @@ void registerFunctionRoutes(ApiServer&);
 // a built-in /api/* route.
 void registerFunctionDispatchRoutes(ApiServer&);
 
+/// Serve one of `project`'s stored files for this request, if it owns it.
+///
+/// NOT A ROUTE, and that is a decision rather than an accident. cpp-httplib's
+/// order is pre-routing, then the static MOUNTS (`set_mount_point`, which this
+/// service uses for the admin web UI at `/`), then the registered handlers. A
+/// catch-all handler registered last would be shadowed by the web UI mount, so
+/// a project hostname with `mount: "/"` would answer `/` with the ADMIN SPA -
+/// the one surface a project hostname must never show. `set_file_request_handler`
+/// is no use either: it fires only after a mount has already matched a file on
+/// disk.
+///
+/// Calling it from the pre-routing handler puts it ahead of the mounts, and the
+/// service's own surfaces are then protected EXPLICITLY by
+/// `isServiceOwnedPath` rather than by registration order - which is the half
+/// that can be unit-tested and the half a falsification test can break.
+///
+/// Returns true when it answered (200, 304 or 404 inside a claimed mount), and
+/// false when the request is not this project's static tree to serve.
+bool serveProjectStatic(ServerDeps& d, const std::string& project, const httplib::Request& req,
+                        httplib::Response& res);
+
+/// Would `project`'s static mount claim `path`? Used by the host gate, which
+/// must widen its whitelist for a configured mount or it 404s the request
+/// before the handler above is ever reached.
+bool projectStaticClaimsPath(ServerDeps& d, const std::string& project, const std::string& path);
+
 } // namespace svapi

+ 172 - 0
src/static_serve.cpp

@@ -0,0 +1,172 @@
+#include "static_serve.hpp"
+
+#include <cctype>
+#include <vector>
+
+namespace svapi {
+namespace {
+
+/// A mount or an alias is short by nature. Bounded so a hand-edited document
+/// cannot put an unbounded string into every log line and every comparison.
+constexpr size_t kMaxPathLen = 1024;
+
+/// Split on '/', dropping empty segments. Repeated and trailing slashes
+/// therefore vanish here rather than in three separate places.
+std::vector<std::string_view> segments(std::string_view p) {
+    std::vector<std::string_view> out;
+    size_t i = 0;
+    while (i < p.size()) {
+        while (i < p.size() && p[i] == '/') ++i;
+        const size_t start = i;
+        while (i < p.size() && p[i] != '/') ++i;
+        if (i > start) out.push_back(p.substr(start, i - start));
+    }
+    return out;
+}
+
+/// The first non-empty segment, or empty for the root.
+std::string_view firstSegment(std::string_view p) {
+    const auto segs = segments(p);
+    return segs.empty() ? std::string_view{} : segs.front();
+}
+
+std::string joined(const std::vector<std::string_view>& segs) {
+    if (segs.empty()) return "/";
+    std::string out;
+    for (const std::string_view s : segs) {
+        out += '/';
+        out.append(s);
+    }
+    return out;
+}
+
+} // namespace
+
+StaticConfig StaticConfig::fromJson(const nlohmann::json& j) {
+    StaticConfig s;
+    if (!j.is_object()) return s;
+    if (j.contains("enabled") && j.at("enabled").is_boolean())
+        s.enabled = j.at("enabled").get<bool>();
+    // Stored values are normalised on the way IN as well as on the way out, so
+    // a hand-edited document carrying `mount: "/x/"` behaves identically to one
+    // written through the route. An unknown key is ignored, like everywhere
+    // else here: a document written by a newer server must still load.
+    if (j.contains("mount") && j.at("mount").is_string())
+        s.mount = normaliseMount(j.at("mount").get<std::string>());
+    // An empty index is MEANINGFUL - it disables the SPA fallback - so it is
+    // read back as empty rather than falling through to the default. That is
+    // why this reads the key's presence instead of using `value()`.
+    if (j.contains("index") && j.at("index").is_string())
+        s.index = j.at("index").get<std::string>();
+    if (j.contains("cache_control") && j.at("cache_control").is_string())
+        s.cacheControl = j.at("cache_control").get<std::string>();
+    return s;
+}
+
+nlohmann::json StaticConfig::toJson() const {
+    return {{"enabled", enabled},
+            {"mount", mount},
+            {"index", index},
+            {"cache_control", cacheControl}};
+}
+
+std::string normaliseMount(std::string_view raw) {
+    // Surrounding whitespace is a paste artefact, not an intention.
+    while (!raw.empty() && std::isspace(static_cast<unsigned char>(raw.front()))) raw.remove_prefix(1);
+    while (!raw.empty() && std::isspace(static_cast<unsigned char>(raw.back()))) raw.remove_suffix(1);
+    return joined(segments(raw));
+}
+
+std::string mountError(const std::string& mount) {
+    if (mount.empty() || mount.front() != '/')
+        return "a mount must start with '/'";
+    if (mount.size() > kMaxPathLen)
+        return "a mount may be at most " + std::to_string(kMaxPathLen) + " characters";
+    for (const unsigned char c : mount) {
+        if (c < 0x20 || c == 0x7f) return "a mount may not contain control characters";
+        if (c == ' ') return "a mount may not contain spaces";
+        if (c == '?' || c == '#') return "a mount may not contain '?' or '#'";
+    }
+    if (hasDotDotSegment(mount)) return "a mount may not contain a '..' segment";
+    // THE SHADOWING RULE, stated at write time. A mount under these prefixes
+    // would put a tenant's tree in front of the service's own surfaces - and
+    // while isServiceOwnedPath refuses them again on every request, an admin
+    // deserves to be told now rather than to discover it as a silent 404 on
+    // their own API.
+    const std::string_view first = firstSegment(mount);
+    if (first == "api" || first == "fn")
+        return "a mount may not sit under '/" + std::string(first) +
+               "' - that prefix belongs to the service's own surface";
+    if (mount == "/healthz")
+        return "a mount may not be '/healthz' - that path belongs to the service";
+    return {};
+}
+
+bool isServiceOwnedPath(std::string_view path) {
+    if (path == "/healthz") return true;
+    const std::string_view first = firstSegment(path);
+    return first == "api" || first == "fn";
+}
+
+bool hasDotDotSegment(std::string_view path) {
+    for (const std::string_view s : segments(path))
+        if (s == "..") return true;
+    return false;
+}
+
+std::optional<std::string> resolveStaticPath(const std::string& mount,
+                                             std::string_view requestPath) {
+    if (requestPath.empty() || requestPath.front() != '/') return std::nullopt;
+    if (requestPath.size() > kMaxPathLen) return std::nullopt;
+    // Checked on the RAW path, before any normalisation, and again implicitly
+    // after it: normalising first would be the one ordering where a `..` could
+    // be spelled away.
+    if (hasDotDotSegment(requestPath)) return std::nullopt;
+    // THE SERVICE'S OWN SURFACES ALWAYS WIN, whatever is mounted. This is the
+    // clause that makes `mount: "/"` safe.
+    if (isServiceOwnedPath(requestPath)) return std::nullopt;
+
+    const auto mountSegs = segments(mount);
+    const auto pathSegs = segments(requestPath);
+    if (pathSegs.size() < mountSegs.size()) return std::nullopt;
+    for (size_t i = 0; i < mountSegs.size(); ++i)
+        if (pathSegs[i] != mountSegs[i]) return std::nullopt;
+
+    const std::vector<std::string_view> rest(pathSegs.begin() +
+                                                 static_cast<long>(mountSegs.size()),
+                                             pathSegs.end());
+    return joined(rest);
+}
+
+std::string indexAlias(const std::string& index) {
+    if (index.empty()) return {};
+    const std::string alias = normaliseMount(index);
+    // `normaliseMount("")` and `normaliseMount("/")` are both "/", which names
+    // no file. An index that normalises to the root is therefore treated as
+    // disabled rather than as a lookup that can never match.
+    return alias == "/" ? std::string() : alias;
+}
+
+std::string staticPathError(const std::string& path) {
+    if (path.empty()) return "a file path cannot be empty";
+    if (path.size() > kMaxPathLen)
+        return "a file path may be at most " + std::to_string(kMaxPathLen) + " characters";
+    if (path.front() != '/') return "a file path must start with '/'";
+    for (const unsigned char c : path) {
+        if (c < 0x20 || c == 0x7f) return "a file path may not contain control characters";
+        if (c == '?' || c == '#') return "a file path may not contain '?' or '#'";
+    }
+    if (hasDotDotSegment(path)) return "a file path may not contain a '..' segment";
+    // A path the read side can never resolve is refused here rather than
+    // stored: `isServiceOwnedPath` would discard it on every request, so
+    // accepting it would be a 201 for something that can never be served.
+    if (isServiceOwnedPath(path))
+        return "a file path may not sit under '/api', '/fn' or at '/healthz' - those belong "
+               "to the service's own surface";
+    if (normaliseMount(path) != path)
+        return "a file path must be canonical: a leading slash, no trailing slash and no "
+               "repeated slashes (try '" + normaliseMount(path) + "')";
+    return {};
+}
+
+} // namespace svapi

+ 123 - 0
src/static_serve.hpp

@@ -0,0 +1,123 @@
+#pragma once
+
+#include <nlohmann/json.hpp>
+#include <optional>
+#include <string>
+#include <string_view>
+
+/// THE DECISIONS BEHIND THE ONLY DELIBERATELY PUBLIC READ PATH IN THIS SERVICE,
+/// pure, so every one of them is testable without a socket, a database or a
+/// hostname.
+///
+/// Serving a project's files over its own hostname is unauthenticated by
+/// design - a browser fetching `/img/logo.png` carries no credential and cannot
+/// be given one. Everything that decides WHETHER a byte is served therefore
+/// lives here rather than inside a handler, for the reason this codebase keeps
+/// relearning: a check that lives in a function the route does not call is the
+/// most expensive shape a security decision can take.
+///
+/// Two conditions must BOTH hold before this path is reached at all, and
+/// neither implies the other: the request arrived on a `HostKind::Project`
+/// hostname, and that project has explicitly enabled static serving. The
+/// functions here answer only the third question - given that both hold, which
+/// stored file (if any) does this request path name.
+namespace svapi {
+
+/// A project's static-serving configuration, as stored beside `hostnames`.
+///
+/// The defaults are the ones that ship, and `enabled` STAYS false: turning this
+/// on publishes files that were private a moment earlier, so it is an act
+/// rather than an inherited state. `ProjectSettings` holds it as an
+/// `optional<StaticConfig>` so that "never configured" and "configured to the
+/// defaults" remain distinguishable - the same reason `default_function_policy`
+/// is optional there.
+struct StaticConfig {
+    bool enabled = false;
+    /// Where the tree appears. Canonical form: a leading slash, no trailing
+    /// slash, `/` for the root.
+    std::string mount = "/";
+    /// The SPA fallback for a path matching no file. Empty disables it, and
+    /// then an unmatched path is a plain 404. It is NOT a wildcard rewrite -
+    /// the file must exist.
+    std::string index = "index.html";
+    /// Sent verbatim. Short on purpose: a long max-age on a path carrying no
+    /// content hash is how a tenant ships a change nobody can see for a day.
+    std::string cacheControl = "public, max-age=300";
+
+    static StaticConfig fromJson(const nlohmann::json& j);
+    nlohmann::json toJson() const;
+};
+
+/// The metadata key on a stored file holding the path it is served at.
+///
+/// Our file NAMES are a single path segment (`[^/]+`, charset-restricted), so
+/// `assets/index-a1b2.js` cannot be a name. The alias is the only way to
+/// express a tree, and a file with NO such metadata is not reachable over the
+/// static mount at all - absence means private, and it never falls back to
+/// serving by name.
+inline constexpr const char* kStaticPathMetadataKey = "path";
+
+/// Canonicalise a mount as written by a human.
+///
+/// Adds the leading slash, drops trailing slashes, collapses repeated slashes,
+/// and answers `/` for anything that normalises away to nothing. Pure and
+/// total: it never refuses, because refusing is `mountError`'s job and a
+/// caller that conflated the two would end up validating a string it had not
+/// yet canonicalised.
+std::string normaliseMount(std::string_view raw);
+
+/// Why this mount may not be used, or empty when it is acceptable.
+///
+/// Takes an ALREADY NORMALISED mount. The refusals are the shadowing rule
+/// stated at write time: a mount sitting under `api/`, under `fn/`, or at
+/// `/healthz` would put a tenant's tree in front of the service's own
+/// surfaces. `isServiceOwnedPath` refuses the same shapes again at READ time,
+/// and the duplication is deliberate - this one gives an admin a 422 they can
+/// act on, that one is what actually holds if a stored document is ever
+/// hand-edited.
+std::string mountError(const std::string& mount);
+
+/// Does this request path belong to the service rather than to any tenant?
+///
+/// THE SERVICE'S OWN SURFACES ALWAYS WIN. True for `/api/**`, `/fn/**` and
+/// exactly `/healthz`, regardless of what any project mounted - which is what
+/// makes `mount: "/"` safe rather than a way to swallow the API.
+bool isServiceOwnedPath(std::string_view path);
+
+/// Is there a `..` SEGMENT anywhere in this path?
+///
+/// The lookup is an exact match on stored metadata and never a filesystem
+/// join, so there is nothing to escape today. The check stays because the next
+/// person to touch this may introduce one, and because a path containing `..`
+/// is never something a caller meant.
+///
+/// Segment-wise rather than a substring search: a file legitimately named
+/// `v1..2.js` is not traversal, and refusing it would be a defect of its own.
+bool hasDotDotSegment(std::string_view path);
+
+/// The stored `path` metadata value this request names, or nullopt when the
+/// request is not this mount's to answer.
+///
+/// Returns nullopt for a path outside the mount, a path owned by the service,
+/// and any path carrying a `..` segment. Otherwise the alias is canonical: a
+/// leading slash, no trailing slash, `/` for the mount root itself.
+std::optional<std::string> resolveStaticPath(const std::string& mount,
+                                             std::string_view requestPath);
+
+/// The alias the `index` fallback is looked up under, or empty when the
+/// fallback is disabled.
+///
+/// Shares `normaliseMount`'s canonicalisation so that `index.html`,
+/// `/index.html` and `/index.html/` all name one stored file - a tenant typing
+/// the second spelling into a form must not get a silent 404.
+std::string indexAlias(const std::string& index);
+
+/// Why a file's `path` metadata may not be stored, or empty when acceptable.
+///
+/// The value arrives from an authenticated upload, so this is not a security
+/// boundary the way the read-side checks are - but a path that can never be
+/// served is worth refusing at write time rather than storing and 404ing on
+/// forever.
+std::string staticPathError(const std::string& path);
+
+} // namespace svapi

+ 7 - 0
tests/CMakeLists.txt

@@ -43,6 +43,13 @@ add_executable(test_hostnames test_hostnames.cpp)
 target_link_libraries(test_hostnames PRIVATE vectorapi_core GTest::gtest_main)
 gtest_discover_tests(test_hostnames)
 
+# Static serving: the mount rules, the shadowing rule, traversal and path
+# resolution are PURE and link only the core - the only unauthenticated read
+# path in this service must be testable at its edges without a socket.
+add_executable(test_static_serve test_static_serve.cpp)
+target_link_libraries(test_static_serve PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_static_serve)
+
 # Certificate selection is pure too: the wildcard rules and the exact-beats-
 # wildcard precedence need no socket and no OpenSSL to test.
 add_executable(test_tls_certs test_tls_certs.cpp)

+ 511 - 0
tests/test_api_integration.cpp

@@ -5449,3 +5449,514 @@ TEST_F(ApiFixture, TheGlobalStatsRouteSurvivesTheProjectRouteWideningBesideIt) {
     ASSERT_TRUE(p); ASSERT_EQ(p->status, 200) << p->body;
     EXPECT_EQ(nlohmann::json::parse(p->body).at("project"), project_);
 }
+
+// ===========================================================================
+// STATIC FILE SERVING ON A PROJECT HOSTNAME.
+//
+// THE ONLY DELIBERATELY PUBLIC READ PATH in this service besides /fn/ and
+// /healthz, so every test here is a PAIRING: an arm that proves the refusal
+// and an arm that proves the refusal is SELECTIVE. A suite that only asserted
+// the 404s would pass just as well against a build that served nothing at all,
+// which is a strictly worse defect than the one being prevented.
+//
+// Two conditions must BOTH hold before a byte is served - a project hostname,
+// and that project having enabled serving - and neither implies the other, so
+// each is pinned by flipping it alone with everything else held constant.
+// ===========================================================================
+
+namespace {
+
+/// RAII: put the project's static block back to DISABLED however the test
+/// leaves. Host gating has its own guard for the same reason; this one is
+/// separate because the two settings are written by different routes and a
+/// test may use either alone.
+struct StaticServingGuard {
+    int port;
+    std::string key;
+    std::string project;
+    ~StaticServingGuard() {
+        httplib::Client c("127.0.0.1", port);
+        c.set_default_headers({{"Authorization", "Bearer " + key}});
+        (void)c.Put(("/api/v1/projects/" + project + "/settings/static").c_str(),
+                    nlohmann::json{{"enabled", false}, {"mount", "/"}}.dump(),
+                    "application/json");
+    }
+};
+
+} // namespace
+
+TEST_F(ApiFixture, TheStaticBlockSURVIVESThePutThatWroteIt) {
+    StaticServingGuard sguard{port_, adminKey_, project_};
+    const std::string base = "/api/v1/projects/" + project_ + "/settings/static";
+
+    auto put = admin().Put(base.c_str(),
+        nlohmann::json{{"enabled", true}, {"mount", "site/"}}.dump(), "application/json");
+    ASSERT_TRUE(put); ASSERT_EQ(put->status, 200) << put->body;
+    auto j = nlohmann::json::parse(put->body);
+    EXPECT_TRUE(j.at("enabled").get<bool>());
+    EXPECT_EQ(j.at("mount"), "/site") << "the mount was not normalised on write";
+    EXPECT_TRUE(j.at("configured").get<bool>());
+    EXPECT_FALSE(j.at("served").get<bool>())
+        << "no hostname and no gating, so nothing can actually be reached yet";
+
+    // THE REGRESSION: hasAnyOverrides() has to count the static block, or the
+    // PUT's own removeProject() deletes the document it just wrote. It is the
+    // second instance of this trap - hostnames hit it first.
+    auto get = admin().Get(base.c_str());
+    ASSERT_TRUE(get); ASSERT_EQ(get->status, 200);
+    auto g = nlohmann::json::parse(get->body);
+    EXPECT_TRUE(g.at("configured").get<bool>())
+        << "the static block did not survive the write - hasAnyOverrides() is probably "
+           "ignoring it: " << get->body;
+    EXPECT_EQ(g.at("mount"), "/site");
+}
+
+TEST_F(ApiFixture, AMountUnderTheServicesOwnPrefixIsREFUSEDWithItsOwnSlug) {
+    StaticServingGuard sguard{port_, adminKey_, project_};
+    const std::string base = "/api/v1/projects/" + project_ + "/settings/static";
+
+    for (const char* bad : {"/api", "/api/v1", "/fn", "/healthz"}) {
+        auto r = admin().Put(base.c_str(),
+            nlohmann::json{{"enabled", true}, {"mount", bad}}.dump(), "application/json");
+        ASSERT_TRUE(r); EXPECT_EQ(r->status, 422) << bad << ": " << r->body;
+        EXPECT_EQ(nlohmann::json::parse(r->body).at("error").at("code"), "invalid_mount")
+            << bad << " was refused with the wrong slug: " << r->body;
+    }
+
+    // PAIRING: an ordinary mount in the same breath is accepted, so the refusal
+    // is about the prefix and not about the route being broken.
+    auto ok = admin().Put(base.c_str(),
+        nlohmann::json{{"enabled", true}, {"mount", "/apidocs"}}.dump(), "application/json");
+    ASSERT_TRUE(ok); EXPECT_EQ(ok->status, 200) << ok->body;
+}
+
+TEST_F(ApiFixture, AStaticPUTIsADMINOnly) {
+    StaticServingGuard sguard{port_, adminKey_, project_};
+    auto mk = admin().Post("/api/v1/keys",
+        nlohmann::json{{"label","mgr"},{"projects",{project_}},{"admin",false}}.dump(),
+        "application/json");
+    ASSERT_EQ(mk->status, 201);
+    auto mkJson = nlohmann::json::parse(mk->body);
+    const std::string manageKey = mkJson["key"], manageId = mkJson["id"];
+
+    const std::string base = "/api/v1/projects/" + project_ + "/settings/static";
+    // A project-manage key must not be able to publish its own project's files
+    // to the world - this route decides what the world can read with no
+    // credential at all.
+    auto denied = http(manageKey).Put(base.c_str(),
+        nlohmann::json{{"enabled", true}}.dump(), "application/json");
+    ASSERT_TRUE(denied); EXPECT_EQ(denied->status, 403) << denied->body;
+    auto deniedGet = http(manageKey).Get(base.c_str());
+    ASSERT_TRUE(deniedGet); EXPECT_EQ(deniedGet->status, 403) << deniedGet->body;
+
+    // PAIRING: the admin key reaches the same route, so the 403 is about the
+    // key rather than about the route refusing everyone.
+    EXPECT_EQ(admin().Get(base.c_str())->status, 200);
+    admin().Delete(("/api/v1/keys/" + manageId).c_str());
+}
+
+TEST_F(ApiFixture, AFileCarriesItsServedPathAsMETADATAAndWithoutOneItIsPrivate) {
+    const std::string files = "/api/v1/projects/" + project_ + "/files/";
+
+    // WITH a path.
+    auto withPath = request("PUT", files + "withpath.png", "PNGBYTES", "image/png", adminKey_,
+                            {{"X-File-Path", "/img/logo.png"}});
+    ASSERT_TRUE(withPath); ASSERT_EQ(withPath->status, 201) << withPath->body;
+    auto wp = nlohmann::json::parse(withPath->body);
+    ASSERT_TRUE(wp.contains("metadata")) << "the metadata map is not carried through";
+    EXPECT_EQ(wp.at("metadata").at("path"), "/img/logo.png");
+
+    // It SURVIVES a read back, which is the half that proves the database
+    // stores and returns it rather than our own response echoing the request.
+    auto info = admin().Get((files + "withpath.png/info").c_str());
+    ASSERT_TRUE(info); ASSERT_EQ(info->status, 200) << info->body;
+    EXPECT_EQ(nlohmann::json::parse(info->body).at("metadata").at("path"), "/img/logo.png")
+        << "the path metadata did not round-trip through the database: " << info->body;
+
+    // WITHOUT a path. The PAIRING: the upload still works and the file is still
+    // readable by name, so "no path" means private rather than broken.
+    auto noPath = request("PUT", files + "nopath.png", "PNGBYTES2", "image/png", adminKey_, {});
+    ASSERT_TRUE(noPath); ASSERT_EQ(noPath->status, 201) << noPath->body;
+    auto np = nlohmann::json::parse(noPath->body);
+    ASSERT_TRUE(np.contains("metadata"))
+        << "the key must be present even when empty, or its absence would mean two things";
+    EXPECT_TRUE(np.at("metadata").empty());
+    EXPECT_EQ(admin().Get((files + "nopath.png").c_str())->status, 200);
+
+    // A path that could never be served is refused at write time rather than
+    // stored and 404ed on forever.
+    auto badPath = request("PUT", files + "bad.png", "X", "image/png", adminKey_,
+                           {{"X-File-Path", "/api/v1/version"}});
+    ASSERT_TRUE(badPath); EXPECT_EQ(badPath->status, 422) << badPath->body;
+    auto traversal = request("PUT", files + "bad2.png", "X", "image/png", adminKey_,
+                             {{"X-File-Path", "/a/../b.png"}});
+    ASSERT_TRUE(traversal); EXPECT_EQ(traversal->status, 422) << traversal->body;
+
+    admin().Delete((files + "withpath.png").c_str());
+    admin().Delete((files + "nopath.png").c_str());
+}
+
+TEST_F(ApiFixture, AStaticFileIsServedOnTheProjectHostnameAndIsNOTOnTheAdminOne) {
+    HostGatingGuard guard{port_, adminKey_, project_};
+    StaticServingGuard sguard{port_, adminKey_, project_};
+    const std::string files = "/api/v1/projects/" + project_ + "/files/";
+
+    ASSERT_EQ(request("PUT", files + "logo.png", "PNGBYTES", "image/png", adminKey_,
+                      {{"X-File-Path", "/img/logo.png"}})->status, 201);
+    ASSERT_EQ(admin().Put(("/api/v1/projects/" + project_ + "/settings/static").c_str(),
+        nlohmann::json{{"enabled", true}, {"mount", "/"}}.dump(), "application/json")->status, 200);
+    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);
+    ASSERT_EQ(admin().Put("/api/v1/settings",
+        nlohmann::json{{"admin_hostname", "admin.example.com"}}.dump(),
+        "application/json")->status, 200);
+
+    // UNAUTHENTICATED, which is the whole point: a browser fetching an image
+    // carries no credential and cannot be given one.
+    httplib::Client tenant("127.0.0.1", port_);
+    tenant.set_default_headers({{"Host", "tenant.example.com"}});
+    auto served = tenant.Get("/img/logo.png");
+    ASSERT_TRUE(served);
+    ASSERT_EQ(served->status, 200) << served->body;
+    EXPECT_EQ(served->body, "PNGBYTES");
+    EXPECT_EQ(served->get_header_value("Content-Type"), "image/png")
+        << "the content type must be the STORED one, never sniffed from the extension";
+    EXPECT_FALSE(served->get_header_value("ETag").empty());
+    EXPECT_EQ(served->get_header_value("Cache-Control"), "public, max-age=300");
+
+    // PAIRING: the SAME file on the ADMIN hostname is 404. A tenant's HTML
+    // rendered there would be same-origin with the admin UI.
+    httplib::Client adminHost("127.0.0.1", port_);
+    adminHost.set_default_headers({{"Host", "admin.example.com"}});
+    auto onAdmin = adminHost.Get("/img/logo.png");
+    ASSERT_TRUE(onAdmin);
+    EXPECT_NE(onAdmin->status, 200)
+        << "a project's static tree was served on the admin hostname: " << onAdmin->body;
+
+    // A path that matches no file is the SAME 404 whatever the project holds -
+    // there is no directory listing and no enumeration, ever. (index is
+    // disabled first, so this is the plain-404 arm rather than the fallback.)
+    ASSERT_EQ(admin().Put(("/api/v1/projects/" + project_ + "/settings/static").c_str(),
+        nlohmann::json{{"index", ""}}.dump(), "application/json")->status, 200);
+    auto missing = tenant.Get("/img/nothing-here.png");
+    ASSERT_TRUE(missing); EXPECT_EQ(missing->status, 404);
+
+    admin().Delete((files + "logo.png").c_str());
+}
+
+TEST_F(ApiFixture, IfNoneMatchWithTheRightEtagIs304AndWithAWrongOneIs200) {
+    HostGatingGuard guard{port_, adminKey_, project_};
+    StaticServingGuard sguard{port_, adminKey_, project_};
+    const std::string files = "/api/v1/projects/" + project_ + "/files/";
+
+    ASSERT_EQ(request("PUT", files + "app.js", "console.log(1)", "application/javascript",
+                      adminKey_, {{"X-File-Path", "/assets/app.js"}})->status, 201);
+    ASSERT_EQ(admin().Put(("/api/v1/projects/" + project_ + "/settings/static").c_str(),
+        nlohmann::json{{"enabled", true}, {"mount", "/"}}.dump(), "application/json")->status, 200);
+    ASSERT_EQ(admin().Put(("/api/v1/projects/" + project_ + "/settings/hostnames").c_str(),
+        nlohmann::json{{"hostnames", {"tenant.example.com"}}}.dump(), "application/json")->status, 200);
+    ASSERT_EQ(admin().Put("/api/v1/settings",
+        nlohmann::json{{"admin_hostname", "admin.example.com"}}.dump(),
+        "application/json")->status, 200);
+
+    httplib::Client tenant("127.0.0.1", port_);
+    tenant.set_default_headers({{"Host", "tenant.example.com"}});
+    auto first = tenant.Get("/assets/app.js");
+    ASSERT_TRUE(first); ASSERT_EQ(first->status, 200) << first->body;
+    const std::string etag = first->get_header_value("ETag");
+    ASSERT_FALSE(etag.empty());
+
+    // THE RIGHT ETag: 304, carrying the ETag and Cache-Control and NO body.
+    httplib::Client c304("127.0.0.1", port_);
+    c304.set_default_headers({{"Host", "tenant.example.com"}, {"If-None-Match", etag}});
+    auto notModified = c304.Get("/assets/app.js");
+    ASSERT_TRUE(notModified);
+    EXPECT_EQ(notModified->status, 304) << notModified->body;
+    EXPECT_EQ(notModified->get_header_value("ETag"), etag);
+    EXPECT_EQ(notModified->get_header_value("Cache-Control"), "public, max-age=300");
+    EXPECT_TRUE(notModified->body.empty());
+
+    // THE PAIRING, and it is the half that matters: a WRONG ETag must be 200
+    // with the content. A handler that answered 304 unconditionally would pass
+    // the arm above on its own.
+    httplib::Client cWrong("127.0.0.1", port_);
+    cWrong.set_default_headers({{"Host", "tenant.example.com"},
+                                {"If-None-Match", "\"definitely-not-the-checksum\""}});
+    auto stale = cWrong.Get("/assets/app.js");
+    ASSERT_TRUE(stale);
+    EXPECT_EQ(stale->status, 200) << "a wrong If-None-Match was answered 304";
+    EXPECT_EQ(stale->body, "console.log(1)");
+
+    admin().Delete((files + "app.js").c_str());
+}
+
+TEST_F(ApiFixture, TheEnabledSwitchIsWhatDecidesWhetherAFileIsPublic) {
+    HostGatingGuard guard{port_, adminKey_, project_};
+    StaticServingGuard sguard{port_, adminKey_, project_};
+    const std::string files = "/api/v1/projects/" + project_ + "/files/";
+    const std::string staticBase = "/api/v1/projects/" + project_ + "/settings/static";
+
+    ASSERT_EQ(request("PUT", files + "s.css", "body{}", "text/css", adminKey_,
+                      {{"X-File-Path", "/s.css"}})->status, 201);
+    ASSERT_EQ(admin().Put(("/api/v1/projects/" + project_ + "/settings/hostnames").c_str(),
+        nlohmann::json{{"hostnames", {"tenant.example.com"}}}.dump(), "application/json")->status, 200);
+    ASSERT_EQ(admin().Put("/api/v1/settings",
+        nlohmann::json{{"admin_hostname", "admin.example.com"}}.dump(),
+        "application/json")->status, 200);
+
+    httplib::Client tenant("127.0.0.1", port_);
+    tenant.set_default_headers({{"Host", "tenant.example.com"}});
+
+    // OFF: everything else is already in place - the hostname, the file, the
+    // path metadata - so this isolates the switch.
+    ASSERT_EQ(admin().Put(staticBase.c_str(),
+        nlohmann::json{{"enabled", false}, {"mount", "/"}}.dump(), "application/json")->status, 200);
+    auto off = tenant.Get("/s.css");
+    ASSERT_TRUE(off); EXPECT_EQ(off->status, 404) << off->body;
+
+    // ON: the same request, nothing else changed.
+    ASSERT_EQ(admin().Put(staticBase.c_str(),
+        nlohmann::json{{"enabled", true}}.dump(), "application/json")->status, 200);
+    auto on = tenant.Get("/s.css");
+    ASSERT_TRUE(on);
+    EXPECT_EQ(on->status, 200) << "flipping enabled did not publish the file: " << on->body;
+    EXPECT_EQ(on->body, "body{}");
+
+    // And the file is still readable by its authenticated route either way, so
+    // the switch governs the PUBLIC path only.
+    EXPECT_EQ(admin().Get((files + "s.css").c_str())->status, 200);
+    admin().Delete((files + "s.css").c_str());
+}
+
+TEST_F(ApiFixture, TheServicesOwnSurfacesSurviveAStaticMountAtTheROOT) {
+    // THE SHADOWING REGRESSION. With mount "/", a naive handler swallows the
+    // API. Note which paths are checked and why: /api/v1/version is NOT served
+    // on a project hostname at all (the host gate's whitelist is about project
+    // resources), so it cannot distinguish "shadowed by static" from "refused
+    // by the gate". The project-scoped API routes CAN.
+    HostGatingGuard guard{port_, adminKey_, project_};
+    StaticServingGuard sguard{port_, adminKey_, project_};
+    const std::string files = "/api/v1/projects/" + project_ + "/files/";
+
+    ASSERT_EQ(request("PUT", files + "idx.html", "<html>ROOTFILE</html>", "text/html", adminKey_,
+                      {{"X-File-Path", "/index.html"}})->status, 201);
+    ASSERT_EQ(admin().Put(("/api/v1/projects/" + project_ + "/settings/static").c_str(),
+        nlohmann::json{{"enabled", true}, {"mount", "/"}, {"index", "index.html"}}.dump(),
+        "application/json")->status, 200);
+    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);
+    ASSERT_EQ(admin().Put("/api/v1/settings",
+        nlohmann::json{{"admin_hostname", "admin.example.com"}}.dump(),
+        "application/json")->status, 200);
+
+    // (1) A PROJECT API ROUTE still answers on the project hostname, with the
+    // API's own JSON rather than the tenant's index.html.
+    auto api = request("GET", "/api/v1/collections", "", "", adminKey_,
+                       {{"Host", "tenant.example.com"}});
+    ASSERT_TRUE(api);
+    ASSERT_EQ(api->status, 200)
+        << "a static mount at '/' swallowed the API on a project hostname: " << api->body;
+    EXPECT_TRUE(nlohmann::json::parse(api->body).contains("collections"))
+        << "the API route answered with something other than the API: " << api->body;
+    EXPECT_EQ(api->body.find("ROOTFILE"), std::string::npos)
+        << "the tenant's index.html was served in place of the API response";
+
+    // (2) The FULL form too, which is the other spelling that must survive.
+    auto apiFull = request("GET", "/api/v1/projects/" + project_ + "/collections", "", "",
+                           adminKey_, {{"Host", "tenant.example.com"}});
+    ASSERT_TRUE(apiFull); EXPECT_EQ(apiFull->status, 200) << apiFull->body;
+
+    // (3) UNAUTHENTICATED /api/ still answers 401, not the index file. The
+    // static handler runs BEFORE the auth check, so this is the arm that
+    // proves it declined to claim the path rather than claimed it and missed.
+    httplib::Client anon("127.0.0.1", port_);
+    anon.set_default_headers({{"Host", "tenant.example.com"}});
+    auto unauth = anon.Get("/api/v1/collections");
+    ASSERT_TRUE(unauth);
+    EXPECT_EQ(unauth->status, 401)
+        << "an unauthenticated /api/ request was answered by the static tree: " << unauth->body;
+
+    // (4) /healthz is still the health route, not a static 404 and not the
+    // index file - a monitor must need no credential anywhere.
+    auto health = anon.Get("/healthz");
+    ASSERT_TRUE(health); EXPECT_EQ(health->status, 200) << health->body;
+    EXPECT_EQ(health->body.find("ROOTFILE"), std::string::npos);
+
+    // (5) /api/v1/version on a project hostname is refused BY THE HOST GATE,
+    // and its message says so - which is how this distinguishes "the gate
+    // refused it" from "static claimed it and found nothing".
+    auto version = request("GET", "/api/v1/version", "", "", adminKey_,
+                           {{"Host", "tenant.example.com"}});
+    ASSERT_TRUE(version); ASSERT_EQ(version->status, 404) << version->body;
+    EXPECT_EQ(nlohmann::json::parse(version->body).at("error").at("message"),
+              "not served on this host")
+        << "the static tree claimed a service-owned path: " << version->body;
+
+    // (6) THE PAIRING for all of the above: the mount really is at '/' and
+    // really is serving, so none of these passed because static was inert.
+    auto root = anon.Get("/");
+    ASSERT_TRUE(root);
+    EXPECT_EQ(root->status, 200) << "the root mount is not serving at all: " << root->body;
+    EXPECT_EQ(root->body, "<html>ROOTFILE</html>");
+
+    admin().Delete((files + "idx.html").c_str());
+}
+
+TEST_F(ApiFixture, TheIndexFallbackServesAnUnmatchedPathAndAnEmptyIndexDisablesIt) {
+    HostGatingGuard guard{port_, adminKey_, project_};
+    StaticServingGuard sguard{port_, adminKey_, project_};
+    const std::string files = "/api/v1/projects/" + project_ + "/files/";
+    const std::string staticBase = "/api/v1/projects/" + project_ + "/settings/static";
+
+    ASSERT_EQ(request("PUT", files + "spa.html", "<html>SPA</html>", "text/html", adminKey_,
+                      {{"X-File-Path", "/index.html"}})->status, 201);
+    ASSERT_EQ(admin().Put(staticBase.c_str(),
+        nlohmann::json{{"enabled", true}, {"mount", "/"}, {"index", "index.html"}}.dump(),
+        "application/json")->status, 200);
+    ASSERT_EQ(admin().Put(("/api/v1/projects/" + project_ + "/settings/hostnames").c_str(),
+        nlohmann::json{{"hostnames", {"tenant.example.com"}}}.dump(), "application/json")->status, 200);
+    ASSERT_EQ(admin().Put("/api/v1/settings",
+        nlohmann::json{{"admin_hostname", "admin.example.com"}}.dump(),
+        "application/json")->status, 200);
+
+    httplib::Client tenant("127.0.0.1", port_);
+    tenant.set_default_headers({{"Host", "tenant.example.com"}});
+
+    // A client-side route matches no stored file and gets the SPA shell.
+    auto deep = tenant.Get("/settings/profile");
+    ASSERT_TRUE(deep); ASSERT_EQ(deep->status, 200) << deep->body;
+    EXPECT_EQ(deep->body, "<html>SPA</html>");
+    EXPECT_EQ(deep->get_header_value("Content-Type"), "text/html");
+
+    // THE PAIRING: an EMPTY index disables it, and the same request is then a
+    // plain 404. Without this arm the test could not tell the fallback from a
+    // handler that serves index.html for everything unconditionally.
+    ASSERT_EQ(admin().Put(staticBase.c_str(),
+        nlohmann::json{{"index", ""}}.dump(), "application/json")->status, 200);
+    auto noFallback = tenant.Get("/settings/profile");
+    ASSERT_TRUE(noFallback);
+    EXPECT_EQ(noFallback->status, 404)
+        << "an empty index did not disable the SPA fallback: " << noFallback->body;
+
+    // And the real file is still served either way, so disabling the fallback
+    // did not disable serving.
+    auto real = tenant.Get("/index.html");
+    ASSERT_TRUE(real); EXPECT_EQ(real->status, 200) << real->body;
+
+    admin().Delete((files + "spa.html").c_str());
+}
+
+TEST_F(ApiFixture, AFileWithNoPathMetadataIsNOTReachableOverTheMount) {
+    // ABSENCE MEANS PRIVATE. It never falls back to serving by name, which is
+    // the rule that keeps every file uploaded before this feature existed
+    // exactly as private as it was.
+    HostGatingGuard guard{port_, adminKey_, project_};
+    StaticServingGuard sguard{port_, adminKey_, project_};
+    const std::string files = "/api/v1/projects/" + project_ + "/files/";
+
+    ASSERT_EQ(request("PUT", files + "secret.txt", "PRIVATE", "text/plain", adminKey_, {})->status,
+              201);
+    ASSERT_EQ(request("PUT", files + "public.txt", "PUBLIC", "text/plain", adminKey_,
+                      {{"X-File-Path", "/public.txt"}})->status, 201);
+    ASSERT_EQ(admin().Put(("/api/v1/projects/" + project_ + "/settings/static").c_str(),
+        nlohmann::json{{"enabled", true}, {"mount", "/"}, {"index", ""}}.dump(),
+        "application/json")->status, 200);
+    ASSERT_EQ(admin().Put(("/api/v1/projects/" + project_ + "/settings/hostnames").c_str(),
+        nlohmann::json{{"hostnames", {"tenant.example.com"}}}.dump(), "application/json")->status, 200);
+    ASSERT_EQ(admin().Put("/api/v1/settings",
+        nlohmann::json{{"admin_hostname", "admin.example.com"}}.dump(),
+        "application/json")->status, 200);
+
+    httplib::Client tenant("127.0.0.1", port_);
+    tenant.set_default_headers({{"Host", "tenant.example.com"}});
+
+    // By NAME: not reachable, because the lookup is on the `path` metadata and
+    // nothing else.
+    auto byName = tenant.Get("/secret.txt");
+    ASSERT_TRUE(byName);
+    EXPECT_EQ(byName->status, 404) << "a file with no path metadata was served by NAME: "
+                                   << byName->body;
+
+    // PAIRING: the file that DOES carry a path is served from the same mount in
+    // the same breath, so the 404 above is about the metadata and not about the
+    // mount being broken.
+    auto withPath = tenant.Get("/public.txt");
+    ASSERT_TRUE(withPath); EXPECT_EQ(withPath->status, 200) << withPath->body;
+    EXPECT_EQ(withPath->body, "PUBLIC");
+
+    admin().Delete((files + "secret.txt").c_str());
+    admin().Delete((files + "public.txt").c_str());
+}
+
+TEST_F(ApiFixture, ANonRootMountStripsItselfAndClaimsNothingOutsideItself) {
+    HostGatingGuard guard{port_, adminKey_, project_};
+    StaticServingGuard sguard{port_, adminKey_, project_};
+    const std::string files = "/api/v1/projects/" + project_ + "/files/";
+
+    ASSERT_EQ(request("PUT", files + "m.txt", "MOUNTED", "text/plain", adminKey_,
+                      {{"X-File-Path", "/deep/m.txt"}})->status, 201);
+    ASSERT_EQ(admin().Put(("/api/v1/projects/" + project_ + "/settings/static").c_str(),
+        nlohmann::json{{"enabled", true}, {"mount", "/site"}, {"index", ""}}.dump(),
+        "application/json")->status, 200);
+    ASSERT_EQ(admin().Put(("/api/v1/projects/" + project_ + "/settings/hostnames").c_str(),
+        nlohmann::json{{"hostnames", {"tenant.example.com"}}}.dump(), "application/json")->status, 200);
+    ASSERT_EQ(admin().Put("/api/v1/settings",
+        nlohmann::json{{"admin_hostname", "admin.example.com"}}.dump(),
+        "application/json")->status, 200);
+
+    httplib::Client tenant("127.0.0.1", port_);
+    tenant.set_default_headers({{"Host", "tenant.example.com"}});
+
+    auto mounted = tenant.Get("/site/deep/m.txt");
+    ASSERT_TRUE(mounted); EXPECT_EQ(mounted->status, 200) << mounted->body;
+    EXPECT_EQ(mounted->body, "MOUNTED");
+
+    // PAIRING: outside the mount the gate refuses rather than the static tree
+    // answering - a prefix match would have handed /sitemap.xml to this mount
+    // and stripped four characters out of the middle of the name.
+    auto outside = tenant.Get("/deep/m.txt");
+    ASSERT_TRUE(outside); EXPECT_EQ(outside->status, 404) << outside->body;
+    auto prefixTrap = tenant.Get("/sitemap.xml");
+    ASSERT_TRUE(prefixTrap); EXPECT_EQ(prefixTrap->status, 404) << prefixTrap->body;
+
+    admin().Delete((files + "m.txt").c_str());
+}
+
+TEST_F(ApiFixture, TheAdminSPAShellIsNOTServedOnAProjectHostname) {
+    // A DEFECT THE STATIC TESTS FOUND, and it predates static serving: the SPA
+    // history fallback lives in set_error_handler, which runs for EVERY 404
+    // however it was produced - so any extensionless 404 on a tenant's
+    // hostname was answered with the OPERATOR's web UI at status 200. That is
+    // the surface withdrawn from the customer-facing name in 0.15.0, handed
+    // back by a handler nobody thinks of as a route.
+    //
+    // Static serving is deliberately left OFF here, so this isolates the error
+    // handler rather than testing the static 404 path.
+    HostGatingGuard guard{port_, adminKey_, project_};
+    ASSERT_EQ(admin().Put(("/api/v1/projects/" + project_ + "/settings/hostnames").c_str(),
+        nlohmann::json{{"hostnames", {"tenant.example.com"}}}.dump(), "application/json")->status, 200);
+    ASSERT_EQ(admin().Put("/api/v1/settings",
+        nlohmann::json{{"admin_hostname", "admin.example.com"}}.dump(),
+        "application/json")->status, 200);
+
+    httplib::Client tenant("127.0.0.1", port_);
+    tenant.set_default_headers({{"Host", "tenant.example.com"}});
+    auto onProject = tenant.Get("/some/client/route");
+    ASSERT_TRUE(onProject);
+    EXPECT_NE(onProject->status, 200) << onProject->body;
+    EXPECT_EQ(onProject->body.find("SVAPI_SPA_OK"), std::string::npos)
+        << "the admin web UI shell was served on a project hostname: " << onProject->body;
+
+    // THE PAIRING: the admin hostname still gets the shell, so the fix narrowed
+    // the fallback rather than removing it. Without this arm the assertion
+    // above would pass against a build where the SPA fallback was simply gone.
+    httplib::Client adminHost("127.0.0.1", port_);
+    adminHost.set_default_headers({{"Host", "admin.example.com"}});
+    auto onAdmin = adminHost.Get("/some/client/route");
+    ASSERT_TRUE(onAdmin);
+    EXPECT_EQ(onAdmin->status, 200) << onAdmin->body;
+    EXPECT_NE(onAdmin->body.find("SVAPI_SPA_OK"), std::string::npos)
+        << "the SPA history fallback stopped working on the admin hostname: " << onAdmin->body;
+}

+ 239 - 0
tests/test_static_serve.cpp

@@ -0,0 +1,239 @@
+#include "static_serve.hpp"
+#include <gtest/gtest.h>
+
+using namespace svapi;
+
+// ===========================================================================
+// THE PURE HALF OF THE ONLY UNAUTHENTICATED READ PATH IN THIS SERVICE.
+//
+// Everything that decides whether a byte is served lives in static_serve.hpp
+// precisely so it can be tested here, with no socket, no database and no
+// hostname - the same reasoning that put the tenancy decision in
+// hostnames.hpp. A check reachable only through an integration test is a check
+// nobody exercises at the edges, and the edges are where a traversal or a
+// shadowed `/api/` lives.
+// ===========================================================================
+
+// --- normaliseMount --------------------------------------------------------
+
+TEST(StaticMount, ASpellingOfTheRootIsAlwaysTheSameCanonicalRoot) {
+    // Four spellings a human will type, one stored value. Without this a mount
+    // saved as "/" and one saved as "" would be different strings that have to
+    // be compared identically everywhere downstream.
+    EXPECT_EQ(normaliseMount("/"), "/");
+    EXPECT_EQ(normaliseMount(""), "/");
+    EXPECT_EQ(normaliseMount("   "), "/");
+    EXPECT_EQ(normaliseMount("///"), "/");
+}
+
+TEST(StaticMount, ALeadingSlashIsAddedAndATrailingOneIsDropped) {
+    EXPECT_EQ(normaliseMount("site"), "/site");
+    EXPECT_EQ(normaliseMount("/site"), "/site");
+    EXPECT_EQ(normaliseMount("/site/"), "/site");
+    EXPECT_EQ(normaliseMount("site///"), "/site");
+    EXPECT_EQ(normaliseMount("/a//b/"), "/a/b");
+    EXPECT_EQ(normaliseMount("  /site/  "), "/site");
+}
+
+TEST(StaticMount, NormalisingIsIdempotent) {
+    // The property, not three more examples: a value read back out of storage
+    // and normalised again must not move, or a stored mount and the mount the
+    // route just wrote would compare unequal.
+    for (const char* raw : {"", "/", "site", "/a//b/", "   /x/y//  "}) {
+        const std::string once = normaliseMount(raw);
+        EXPECT_EQ(normaliseMount(once), once) << raw;
+    }
+}
+
+// --- mountError: the shadowing rule at WRITE time --------------------------
+
+TEST(StaticMount, AMountUnderTheServicesOwnPrefixesIsREFUSED) {
+    EXPECT_FALSE(mountError("/api").empty());
+    EXPECT_FALSE(mountError("/api/v1").empty());
+    EXPECT_FALSE(mountError("/fn").empty());
+    EXPECT_FALSE(mountError("/fn/anything").empty());
+    EXPECT_FALSE(mountError("/healthz").empty());
+}
+
+TEST(StaticMount, AnORDINARYMountIsACCEPTED) {
+    // THE PAIRING for the test above. Without it, that one would pass just as
+    // well against a mountError() that refused everything - which is a strictly
+    // worse defect than the one it is written to prevent.
+    EXPECT_EQ(mountError("/"), "");
+    EXPECT_EQ(mountError("/site"), "");
+    EXPECT_EQ(mountError("/a/b"), "");
+    // A segment that merely CONTAINS a reserved word is fine: only the first
+    // segment decides, so a tenant may mount at /apidocs.
+    EXPECT_EQ(mountError("/apidocs"), "");
+    EXPECT_EQ(mountError("/fnord"), "");
+    EXPECT_EQ(mountError("/healthzz"), "");
+    // And a reserved word NOT in the first position is fine too.
+    EXPECT_EQ(mountError("/site/api"), "");
+}
+
+TEST(StaticMount, AnUnnormalisedOrHostileMountIsRefused) {
+    EXPECT_FALSE(mountError("site").empty()) << "no leading slash";
+    EXPECT_FALSE(mountError("/a/../b").empty());
+    EXPECT_FALSE(mountError("/a b").empty());
+    EXPECT_FALSE(mountError(std::string("/a\x01") + "b").empty());
+    EXPECT_FALSE(mountError("/a?b").empty());
+    EXPECT_FALSE(mountError("/a#b").empty());
+}
+
+// --- isServiceOwnedPath ----------------------------------------------------
+
+TEST(StaticShadowing, TheServicesOwnSurfacesAreOwnedWhateverIsMounted) {
+    EXPECT_TRUE(isServiceOwnedPath("/api"));
+    EXPECT_TRUE(isServiceOwnedPath("/api/v1/version"));
+    EXPECT_TRUE(isServiceOwnedPath("/api/v1/projects/p/collections"));
+    EXPECT_TRUE(isServiceOwnedPath("/fn"));
+    EXPECT_TRUE(isServiceOwnedPath("/fn/proj/thing"));
+    EXPECT_TRUE(isServiceOwnedPath("/healthz"));
+}
+
+TEST(StaticShadowing, ATenantPathThatMerelyLooksLikeOneIsNOTOwned) {
+    // PAIRING again. A blanket "everything is service-owned" would pass the
+    // test above and silently serve nothing at all.
+    EXPECT_FALSE(isServiceOwnedPath("/"));
+    EXPECT_FALSE(isServiceOwnedPath("/index.html"));
+    EXPECT_FALSE(isServiceOwnedPath("/apidocs/x"));
+    EXPECT_FALSE(isServiceOwnedPath("/fnord.js"));
+    EXPECT_FALSE(isServiceOwnedPath("/healthzz"));
+    EXPECT_FALSE(isServiceOwnedPath("/assets/api/x.js"))
+        << "'api' deeper in the path is an ordinary segment, not our surface";
+    // /readyz is NOT in the owned set - it is covered by the host gate rather
+    // than here, and asserting it is owned would be inventing a rule.
+    EXPECT_FALSE(isServiceOwnedPath("/readyz"));
+}
+
+// --- traversal -------------------------------------------------------------
+
+TEST(StaticTraversal, ADotDotSEGMENTIsRefusedAndADotDotINSIDEANameIsNot) {
+    EXPECT_TRUE(hasDotDotSegment("/.."));
+    EXPECT_TRUE(hasDotDotSegment("/a/../b"));
+    EXPECT_TRUE(hasDotDotSegment("/a/.."));
+    EXPECT_TRUE(hasDotDotSegment("/../a"));
+    // Segment-wise, deliberately: a file legitimately named `v1..2.js` is not
+    // traversal, and refusing it would be a defect of its own.
+    EXPECT_FALSE(hasDotDotSegment("/v1..2.js"));
+    EXPECT_FALSE(hasDotDotSegment("/a/..b/c"));
+    EXPECT_FALSE(hasDotDotSegment("/a/b../c"));
+    EXPECT_FALSE(hasDotDotSegment("/a/b/c"));
+}
+
+// --- resolveStaticPath -----------------------------------------------------
+
+TEST(StaticResolve, AtTheRootMountThePathIsTheAlias) {
+    EXPECT_EQ(resolveStaticPath("/", "/img/a.png").value(), "/img/a.png");
+    EXPECT_EQ(resolveStaticPath("/", "/").value(), "/");
+    EXPECT_EQ(resolveStaticPath("/", "/index.html").value(), "/index.html");
+    // A trailing slash on the request names the same thing as without one.
+    EXPECT_EQ(resolveStaticPath("/", "/img/").value(), "/img");
+}
+
+TEST(StaticResolve, AMountIsSTRIPPEDAndOnlySegmentWise) {
+    EXPECT_EQ(resolveStaticPath("/site", "/site/img/a.png").value(), "/img/a.png");
+    EXPECT_EQ(resolveStaticPath("/site", "/site").value(), "/");
+    EXPECT_EQ(resolveStaticPath("/site", "/site/").value(), "/");
+    // SEGMENT-wise, not prefix-wise. A string prefix match would hand
+    // /sitemap.xml to the /site mount and strip four characters off the middle
+    // of a filename.
+    EXPECT_FALSE(resolveStaticPath("/site", "/sitemap.xml").has_value());
+    EXPECT_FALSE(resolveStaticPath("/site", "/other/x").has_value());
+    EXPECT_FALSE(resolveStaticPath("/site", "/").has_value());
+}
+
+TEST(StaticResolve, THESERVICESOWNSURFACESAreRefusedEvenAtTheRootMount) {
+    // The regression this whole mechanism exists for: with mount "/", a naive
+    // resolver would hand /api/v1/version to the tenant's file tree.
+    EXPECT_FALSE(resolveStaticPath("/", "/api/v1/version").has_value());
+    EXPECT_FALSE(resolveStaticPath("/", "/fn/p/f").has_value());
+    EXPECT_FALSE(resolveStaticPath("/", "/healthz").has_value());
+    // PAIRING: the same mount DOES resolve an ordinary path, so the refusal
+    // above is selective rather than blanket.
+    EXPECT_TRUE(resolveStaticPath("/", "/anything/else").has_value());
+}
+
+TEST(StaticResolve, TraversalAndAMalformedPathAreRefused) {
+    EXPECT_FALSE(resolveStaticPath("/", "/../etc/passwd").has_value());
+    EXPECT_FALSE(resolveStaticPath("/site", "/site/../../x").has_value());
+    EXPECT_FALSE(resolveStaticPath("/", "no-leading-slash").has_value());
+    EXPECT_FALSE(resolveStaticPath("/", "").has_value());
+    EXPECT_FALSE(resolveStaticPath("/", std::string("/") + std::string(2000, 'a')).has_value());
+}
+
+// --- indexAlias ------------------------------------------------------------
+
+TEST(StaticIndex, EverySpellingOfTheIndexNamesOneStoredFile) {
+    EXPECT_EQ(indexAlias("index.html"), "/index.html");
+    EXPECT_EQ(indexAlias("/index.html"), "/index.html");
+    EXPECT_EQ(indexAlias("/index.html/"), "/index.html");
+}
+
+TEST(StaticIndex, AnEmptyIndexDISABLESTheFallback) {
+    EXPECT_EQ(indexAlias(""), "");
+    // "/" normalises to the root, which names no file - treated as disabled
+    // rather than as a lookup that can never match.
+    EXPECT_EQ(indexAlias("/"), "");
+}
+
+// --- staticPathError -------------------------------------------------------
+
+TEST(StaticPathMetadata, ACanonicalServedPathIsAccepted) {
+    EXPECT_EQ(staticPathError("/index.html"), "");
+    EXPECT_EQ(staticPathError("/assets/index-a1b2.js"), "");
+    EXPECT_EQ(staticPathError("/img/logo.png"), "");
+}
+
+TEST(StaticPathMetadata, APathThatCouldNEVERBeServedIsRefusedAtWriteTime) {
+    // Refused here rather than stored, because the read side discards these on
+    // every request - so accepting one would be a 201 for something that can
+    // never be served.
+    EXPECT_FALSE(staticPathError("/api/v1/version").empty());
+    EXPECT_FALSE(staticPathError("/fn/p/f").empty());
+    EXPECT_FALSE(staticPathError("/healthz").empty());
+    EXPECT_FALSE(staticPathError("/a/../b").empty());
+    EXPECT_FALSE(staticPathError("no-leading-slash").empty());
+    EXPECT_FALSE(staticPathError("").empty());
+    EXPECT_FALSE(staticPathError("/trailing/").empty()) << "not canonical";
+    EXPECT_FALSE(staticPathError("/double//slash").empty()) << "not canonical";
+}
+
+// --- StaticConfig round trip ----------------------------------------------
+
+TEST(StaticConfigJson, TheDefaultsAreTheDocumentedOnesAndEnabledIsFALSE) {
+    const StaticConfig c;
+    EXPECT_FALSE(c.enabled) << "turning this on publishes files that were private a moment "
+                               "earlier; it must be an act, never an inherited state";
+    EXPECT_EQ(c.mount, "/");
+    EXPECT_EQ(c.index, "index.html");
+    EXPECT_EQ(c.cacheControl, "public, max-age=300");
+}
+
+TEST(StaticConfigJson, RoundTripsAndNormalisesTheMountOnTheWayIN) {
+    StaticConfig c;
+    c.enabled = true;
+    c.mount = "/site";
+    c.index = "";
+    c.cacheControl = "no-store";
+    const StaticConfig back = StaticConfig::fromJson(c.toJson());
+    EXPECT_TRUE(back.enabled);
+    EXPECT_EQ(back.mount, "/site");
+    EXPECT_EQ(back.index, "") << "an empty index disables the fallback and must survive a "
+                                 "round trip rather than falling back to the default";
+    EXPECT_EQ(back.cacheControl, "no-store");
+
+    // A hand-edited document carrying an unnormalised mount behaves exactly
+    // like one written through the route.
+    const StaticConfig edited =
+        StaticConfig::fromJson(nlohmann::json{{"enabled", true}, {"mount", "site/"}});
+    EXPECT_EQ(edited.mount, "/site");
+}
+
+TEST(StaticConfigJson, AnUnknownKeyIsIgnoredAndAnAbsentOneKeepsItsDefault) {
+    const StaticConfig c =
+        StaticConfig::fromJson(nlohmann::json{{"enabled", true}, {"written_by_a_newer_server", 7}});
+    EXPECT_TRUE(c.enabled);
+    EXPECT_EQ(c.mount, "/") << "an absent key must follow the default, not become empty";
+    EXPECT_EQ(c.index, "index.html");
+}

+ 16 - 0
webui/src/api/client.ts

@@ -7,6 +7,7 @@ import type {
   FunctionSummary,
   FunctionsListResponse, FunctionDetail, FunctionRun, InvokeEnvelope, InvokeRequest,
   ProjectFunctionSettings, ProjectFunctionSettingsPatch,
+  ProjectHostnamesView, ProjectStaticSettings,
   CollectionSchema, SchemaChangeResult, SchemaSuggestion, SchemaMode,
 } from '@/types'
 import { ApiError } from '@/types'
@@ -144,6 +145,21 @@ export const api = {
       body: JSON.stringify(patch),
     }),
 
+  // Read-only here. Hostnames are attached elsewhere; the static tab reads
+  // this route because static serving is refused outright for a project with
+  // no hostname, and a UI that let the user enable it anyway would be handing
+  // them a server error instead of an explanation.
+  getProjectHostnames: (project: string) =>
+    request<ProjectHostnamesView>(`${P(project)}/settings/hostnames`),
+
+  getProjectStatic: (project: string) =>
+    request<ProjectStaticSettings>(`${P(project)}/settings/static`),
+  updateProjectStatic: (project: string, body: ProjectStaticSettings) =>
+    request<ProjectStaticSettings>(`${P(project)}/settings/static`, {
+      method: 'PUT',
+      body: JSON.stringify(body),
+    }),
+
   getProjectEmbeddings: (project: string) =>
     request<ProjectEmbeddingsView>(`${P(project)}/settings/embeddings`),
   updateProjectEmbeddings: (project: string, patch: ProjectEmbeddingsPatch) =>

+ 9 - 0
webui/src/pages/Settings.tsx

@@ -8,6 +8,7 @@ import AccessTab from '@/pages/settings/AccessTab'
 import WebuiTab from '@/pages/settings/WebuiTab'
 import ProjectEmbeddingsTab from '@/pages/settings/ProjectEmbeddingsTab'
 import ProjectFunctionsTab from '@/pages/settings/ProjectFunctionsTab'
+import ProjectStaticTab from '@/pages/settings/ProjectStaticTab'
 
 interface TabDef {
   id: string
@@ -41,6 +42,14 @@ export default function Settings() {
       adminOnly: true,
       render: () => <ProjectFunctionsTab />,
     },
+    {
+      id: 'static',
+      label: 'Static files',
+      // Admin-only, matching the route: it decides what this project publishes
+      // to the open internet with no credential.
+      adminOnly: true,
+      render: () => <ProjectStaticTab />,
+    },
   ].filter((t) => admin || !t.adminOnly)
 
   const [active, setActive] = useState(tabs[0]?.id ?? 'project')

+ 298 - 0
webui/src/pages/settings/ProjectStaticTab.tsx

@@ -0,0 +1,298 @@
+import { useEffect, useState } from 'react'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { api } from '@/api/client'
+import { Badge, FormRow, inputCls, SaveButton, Toggle } from '@/components/form'
+import { useAuthStore } from '@/stores/authStore'
+import { useToastStore } from '@/stores/toastStore'
+import { ApiError } from '@/types'
+import type { ProjectStaticSettings } from '@/types'
+
+/// Serving a project's stored files to the open internet.
+///
+/// ADMIN ONLY, matching the route, like hostnames and the function policy: this
+/// is the first deliberately public read path in the service besides /fn and
+/// /healthz, so the party it exposes must not be the party who turns it on.
+///
+/// TWO independent conditions must both hold before a byte is served: the
+/// request arrived on a PROJECT hostname, and the project enabled this. Neither
+/// implies the other, which is why this tab reads the hostnames route before it
+/// will let anyone touch the switch.
+
+const DEFAULT_MOUNT = '/'
+const DEFAULT_INDEX = 'index.html'
+const DEFAULT_CACHE_CONTROL = 'public, max-age=300'
+
+/// The client-side half of the mount rule. The SERVER is the authority and
+/// answers 422 'invalid_mount'; this exists for the person typing, so a wrong
+/// mount is visible before a save rather than after one. The two are not
+/// redundant - this one can be wrong or stale, and the server's cannot.
+///
+/// The rule the refusals come from: the service's own surfaces always win, so a
+/// mount may never sit under /api, /fn or /healthz whatever else it says.
+export function mountError(raw: string): string | null {
+  const mount = raw.trim()
+  if (mount === '') return 'Mount is required. Use / to serve at the root of the hostname.'
+  if (!mount.startsWith('/')) return 'Mount must begin with a slash, for example /assets.'
+  if (mount !== '/' && mount.endsWith('/')) return 'Mount must not end with a slash. Use /assets, not /assets/.'
+  if (mount.includes('//')) return 'Mount must not contain an empty path segment.'
+  if (/\s/.test(mount)) return 'Mount must not contain whitespace.'
+  const segments = mount.split('/').filter((s) => s !== '')
+  if (segments.some((s) => s === '..' || s === '.')) return 'Mount must not contain a . or .. segment.'
+  const first = segments[0] ?? ''
+  if (first === 'api' || first === 'fn') {
+    return `Mount may not sit under /${first}: the service's own surfaces always win, so nothing there would ever be reached.`
+  }
+  if (first === 'healthz') {
+    return 'Mount may not sit under /healthz: the service\'s own surfaces always win, so nothing there would ever be reached.'
+  }
+  return null
+}
+
+/// The exact origin the files land on, built from the project's FIRST hostname
+/// and the mount. This sentence is the safety message of the whole feature: it
+/// is what makes a wrong mount visible to a reviewer, and what makes "enabled"
+/// read as the publishing act it is rather than as a checkbox.
+export function servedOrigin(host: string, mount: string): string {
+  const m = mount.trim()
+  const path = m === '/' || m === '' ? '' : m
+  return `https://${host}${path}`
+}
+
+export default function ProjectStaticTab() {
+  const admin = useAuthStore((s) => s.admin)
+  const project = useAuthStore((s) => s.currentProject)
+  const toast = useToastStore((s) => s.push)
+  const qc = useQueryClient()
+
+  const hostsQuery = useQuery({
+    queryKey: ['project-hostnames', project],
+    queryFn: () => api.getProjectHostnames(project!),
+    enabled: admin && !!project,
+  })
+
+  const staticQuery = useQuery({
+    queryKey: ['project-static', project],
+    queryFn: () => api.getProjectStatic(project!),
+    enabled: admin && !!project,
+  })
+
+  const [enabled, setEnabled] = useState(false)
+  const [mount, setMount] = useState(DEFAULT_MOUNT)
+  const [index, setIndex] = useState(DEFAULT_INDEX)
+  const [cacheControl, setCacheControl] = useState(DEFAULT_CACHE_CONTROL)
+  const [saving, setSaving] = useState(false)
+  /// The server's own refusal, kept beside the client check rather than in
+  /// place of it: it is the authority, and it can refuse something this file
+  /// has not learned about yet.
+  const [serverMountError, setServerMountError] = useState<string | null>(null)
+
+  useEffect(() => {
+    const d = staticQuery.data
+    if (!d) return
+    setEnabled(d.enabled)
+    setMount(d.mount)
+    setIndex(d.index)
+    setCacheControl(d.cache_control)
+  }, [staticQuery.data])
+
+  if (!admin) {
+    return (
+      <p className="text-sm text-slate-400">
+        These settings are admin-only: they decide what this project publishes to
+        anyone on the internet, with no credential required.
+      </p>
+    )
+  }
+  if (!project) return <p className="text-sm text-slate-400">Select a project first.</p>
+  if (hostsQuery.isLoading || staticQuery.isLoading) return <p className="text-sm text-slate-400">Loading...</p>
+  if (hostsQuery.error) return <p className="text-sm text-rose-400">{String(hostsQuery.error)}</p>
+  if (staticQuery.error) return <p className="text-sm text-rose-400">{String(staticQuery.error)}</p>
+
+  const hostnames = hostsQuery.data?.hostnames ?? []
+  const firstHost = hostnames[0]?.host ?? ''
+  /// The gate, shown rather than merely enforced. A project with no hostname
+  /// cannot serve files at all, because there is no name for a browser to ask
+  /// on - so the switch is disabled and says why, instead of letting the user
+  /// turn it on and meet a server error they then have to interpret.
+  const noHostname = hostnames.length === 0
+  /// Stored and not in force. The list alone cannot distinguish this, which is
+  /// why the route carries the flag at all.
+  const notServed = !noHostname && hostsQuery.data?.served === false
+
+  const clientMountError = mountError(mount)
+  const canSave = !saving && clientMountError === null
+
+  async function onSubmit(e: React.FormEvent) {
+    e.preventDefault()
+    if (!project) return
+    // Belt and braces: the submit button is already disabled on a bad mount,
+    // but a form can be submitted by Enter in a text field.
+    if (mountError(mount) !== null) return
+    const body: ProjectStaticSettings = {
+      enabled,
+      mount: mount.trim(),
+      index: index.trim(),
+      cache_control: cacheControl,
+    }
+    setSaving(true)
+    setServerMountError(null)
+    try {
+      await api.updateProjectStatic(project, body)
+      await qc.invalidateQueries({ queryKey: ['project-static', project] })
+      toast(
+        body.enabled
+          ? `Static serving is ON. Files with a path are now public at ${servedOrigin(firstHost, body.mount)}`
+          : 'Static serving is OFF. Stored files are private again.',
+        'success',
+      )
+    } catch (err) {
+      if (err instanceof ApiError && err.code === 'invalid_mount') {
+        setServerMountError(err.message)
+      }
+      toast(err instanceof ApiError ? err.message : String(err), 'error')
+    } finally {
+      setSaving(false)
+    }
+  }
+
+  return (
+    <form onSubmit={onSubmit} className="flex flex-col gap-5 max-w-2xl">
+      <p className="text-xs text-slate-400">
+        Serves this project's stored files over HTTP with no key, on this
+        project's own hostname only. A file is reachable only if its metadata
+        carries a <code className="mx-0.5">path</code>; a file without one stays
+        private and is addressable only through the authenticated files route.
+      </p>
+
+      {noHostname && (
+        <div
+          className="rounded-md border border-amber-500/30 bg-amber-500/10 px-4 py-3"
+          data-testid="static-no-hostname"
+        >
+          <p className="text-sm text-amber-300">
+            This project has no hostname, so it cannot serve files. Files are
+            served on a project hostname and nowhere else, so attach one to{' '}
+            <strong>{project}</strong> first, under the project's hostnames
+            settings, and this switch becomes available.
+          </p>
+        </div>
+      )}
+
+      {notServed && (
+        <p className="text-xs text-amber-400/90" data-testid="static-not-gating">
+          This project has a hostname but the server is not gating on hostnames
+          yet, so nothing is served on it today. Static serving can still be
+          configured here and takes effect once hostname gating is in force.
+        </p>
+      )}
+
+      <FormRow
+        label="Serve files publicly"
+        hint="Off by default, and off is the safe state. Turning this on publishes every file carrying a path to anyone who knows the address - no key, no session, no referer check."
+        badge={enabled ? <Badge tone="amber">public</Badge> : <Badge>private</Badge>}
+      >
+        <div className="flex flex-col gap-2">
+          {/* The switch shows the STORED value even when it is disabled, so
+              the control never disagrees with what a save would write. */}
+          <div className={noHostname ? 'opacity-50 pointer-events-none' : ''} aria-disabled={noHostname}>
+            <Toggle
+              checked={enabled}
+              onChange={(next) => setEnabled(next)}
+              onLabel="Serving publicly"
+              offLabel="Not served"
+            />
+          </div>
+          {noHostname && enabled && (
+            <p className="text-xs text-amber-300" data-testid="static-enabled-but-unreachable">
+              Stored as on, and nothing is served: there is no hostname for a
+              browser to ask on. It takes effect the moment one is attached.
+            </p>
+          )}
+          {!noHostname && (
+            <p
+              className={enabled ? 'text-xs text-amber-300' : 'text-xs text-slate-500'}
+              data-testid="static-origin"
+            >
+              {enabled ? 'Will serve at ' : 'Would serve at '}
+              <code className="text-slate-100">{servedOrigin(firstHost, mount)}</code>
+              {hostnames.length > 1 && (
+                <span className="text-slate-500"> (and {hostnames.length - 1} more hostname{hostnames.length > 2 ? 's' : ''})</span>
+              )}
+            </p>
+          )}
+        </div>
+      </FormRow>
+
+      <FormRow
+        label="Mount"
+        hint="Where the tree appears on the hostname. / serves at the root. Leading slash, no trailing slash. A mount under /api, /fn or /healthz is refused: the service's own surfaces always win."
+      >
+        <input
+          type="text"
+          value={mount}
+          placeholder={DEFAULT_MOUNT}
+          onChange={(e) => {
+            setMount(e.target.value)
+            setServerMountError(null)
+          }}
+          className={`${inputCls} w-72`}
+          data-testid="static-mount"
+        />
+      </FormRow>
+
+      {clientMountError && (
+        <p className="text-xs text-rose-400" data-testid="static-mount-error">
+          {clientMountError}
+        </p>
+      )}
+      {!clientMountError && serverMountError && (
+        <p className="text-xs text-rose-400" data-testid="static-mount-server-error">
+          Refused by the server: {serverMountError}
+        </p>
+      )}
+
+      <FormRow
+        label="Index file"
+        hint="The SPA fallback served for a path that matches no file. It is not a wildcard rewrite - the named file must itself exist and carry a path."
+      >
+        <input
+          type="text"
+          value={index}
+          placeholder={DEFAULT_INDEX}
+          onChange={(e) => setIndex(e.target.value)}
+          className={`${inputCls} w-72`}
+          data-testid="static-index"
+        />
+      </FormRow>
+
+      {index.trim() === '' && (
+        <p className="text-xs text-slate-400" data-testid="static-index-empty">
+          Empty is a decision, not an unset field: with no index there is no SPA
+          fallback, and an unmatched path answers a plain 404. Set{' '}
+          <code>{DEFAULT_INDEX}</code> if this project serves a single-page app
+          that routes in the browser.
+        </p>
+      )}
+
+      <FormRow
+        label="Cache-Control"
+        hint="Sent verbatim on every served file. The default is deliberately short: a long max-age on a path with no content hash in it is how a tenant ships a change nobody can see for a day."
+      >
+        <input
+          type="text"
+          value={cacheControl}
+          placeholder={DEFAULT_CACHE_CONTROL}
+          onChange={(e) => setCacheControl(e.target.value)}
+          className={`${inputCls} w-96`}
+          data-testid="static-cache-control"
+        />
+      </FormRow>
+
+      {/* SaveButton IS the button, with type="submit" - wrapping it in another
+          button nests one inside the other and only works by accident. */}
+      <div className="flex items-center gap-3">
+        <SaveButton saving={saving} disabled={!canSave} />
+      </div>
+    </form>
+  )
+}

+ 36 - 0
webui/src/types/index.ts

@@ -308,3 +308,39 @@ export interface InvokeRequest {
   headers?: Record<string, unknown>
   body?: unknown
 }
+
+/// One hostname attached to a project. `path_style` decides whether a caller
+/// on that host addresses a collection by the full `/api/v1/projects/{p}/...`
+/// path or by the short form with the project implied by the host.
+export interface ProjectHostname {
+  host: string
+  path_style: 'short' | 'full'
+}
+
+/// GET /settings/hostnames. `served` is NOT derivable from the list: with no
+/// deployment hostnames configured a project hostname is stored and not in
+/// force, and the two cases produce an identical `hostnames` array.
+export interface ProjectHostnamesView {
+  project: string
+  hostnames: ProjectHostname[]
+  served: boolean
+}
+
+/// GET/PUT /settings/static. Admin-only on both verbs, like hostnames and the
+/// function policy, and for the same reason: it decides what the world can
+/// reach without presenting a credential.
+export interface ProjectStaticSettings {
+  /// False by default and the default stays false. Turning it on publishes
+  /// files that were private a moment earlier, so it is an act rather than an
+  /// inherited state.
+  enabled: boolean
+  /// Where the tree appears: '/' or '/something'. Leading slash, no trailing
+  /// slash. A mount under /api, /fn or /healthz is refused 422 'invalid_mount'.
+  mount: string
+  /// The SPA fallback served for a path matching no file. '' disables it, and
+  /// then an unmatched path is a plain 404. It is not a wildcard rewrite - the
+  /// named file must exist.
+  index: string
+  /// Sent verbatim on every served file.
+  cache_control: string
+}