Procházet zdrojové kódy

feat(files): per-project named binary assets, over HTTP and in functions

So everything customer-specific - a logo, an e-mail signature image - can be
tenant DATA instead of being bundled into a function's source, and a project
can be cloned for another customer by changing data only.

  PUT    /api/v1/projects/{p}/files/{name}   raw body, Content-Type kept
  GET    /api/v1/projects/{p}/files/{name}   the bytes, with their type
  GET    /api/v1/projects/{p}/files/{name}/info
  GET    /api/v1/projects/{p}/files          newest first
  DELETE /api/v1/projects/{p}/files/{name}
  ctx.files.get(name) / .info(name) / .list()   read only

Name-addressed, because the database hands back a UUID per upload and exposing
that would put an opaque id in every caller's config. Reads follow the scope
rules under the reserved `_files` pseudo-collection, so requireCapabilityCore
stays the one implementation and file access cannot drift from collection
access; the leading underscore makes it unshadowable, since collection-create
rejects `_`-prefixed names. Writes need project-manage: replacing a tenant's
asset is a management act, which is also why ctx.files is read only.

PROJECT ISOLATION HERE IS OURS, NOT THE DATABASE'S, and that is the thing to
know before changing this code. The database namespaces files by the client's
project; this service runs one client for `default` because collections are
qualified per call instead, and the file API takes no project argument. So
every project's files share one database namespace and are separated only by
the related_id we stamp and filter on. Every lookup filters on BOTH project and
name, nothing outside file_store.cpp addresses a file by its database id, and
an integration test asserts a file in one project is invisible to another by
name and by listing.

Measured against the database rather than assumed:
- an upload does NOT replace by name - two uploads of one name leave two
  records - so put() deletes the previous ones itself, uploading FIRST so a
  failure leaves the old file intact, and reads take the newest record.
- identical bytes under two names share one reference-counted blob, so
  deleting one name keeps the other readable. There is a test for it, because
  getting it wrong loses a file nobody deleted.
- the database imposed no cap at 5 MiB, so ours is the only one that matters.

Two caps, answering two questions: max_file_bytes (global, default 2 MiB)
bounds what can be stored, and a separate 1 MiB ceiling bounds what one run may
load - a file stored when the limit was generous must not pull megabytes into a
64 MiB JS heap on every run afterwards.

A file name is an identifier, not a label: letters, digits, '.', '-', '_', no
leading '.', no '..', no path separator, no ':'. Validated by a pure function
with its own tests, because the name arrives in a URL path that httplib
percent-decodes before a handler sees it, and it is echoed in a
Content-Disposition header. A bad name is 422 with the reason, never 404 - the
name is unusable rather than missing.

Deleting a project deletes its files, so a recycled project name does not
inherit the previous tenant's assets. The test fails without it.

Asking the database team about refcounts, caps, memory and dropProject turned
up three defects on their side, fixed in 2.12.3: an oversized upload was
buffered whole and refused as Internal, downloads read whole files into memory,
and dropProject left a project's files behind. Our own dropAll covers the last
one regardless of database version.

NOT included: files in a project export. There is no project export in this
repo at all, so that is its own feature rather than an addition to this one.

837/837 natively and 837/837 in the Debian container.
fszontagh před 1 měsícem
rodič
revize
7ca9d4e3b6

+ 4 - 0
CLAUDE.md

@@ -71,6 +71,10 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **The database-event loop guard reads the event's actor** (client 2.12.0). Every write a function makes is stamped `fn:<project>/<id>:<depth>` via the `actor` parameter, and `Event::actor` carries it back - so provenance costs nothing and lives in the audit trail, NOT in a field inside user documents (which would travel into every export forever). A chain is refused past `events.max_depth` generations and logged at error.
 - **Delivery is at-least-once.** A claim that goes stale is reclaimed and the job runs again, so cron and db functions must be idempotent. `singleFlight` (default true for cron) skips a tick while the previous run is still going, which bounds stacking but is not exactly-once.
 - **`jobs.enabled` is OFF by default in the runner**, so a runner upgrade never starts draining a queue in a deployment whose server has no scheduler. On a host that wants cron it MUST be turned on, or the scheduler enqueues work nothing ever runs - the most confusing possible way for cron to look broken.
+- **Project files** are small named binary assets per project (`file_store.hpp`), so everything customer-specific - a logo, a signature image - is tenant DATA rather than something bundled into a function's source. **PROJECT ISOLATION IS OURS, NOT THE DATABASE'S:** the database namespaces files by `Client::Config::project`, this service runs ONE client configured for `default` (collections are qualified per call instead), and the file API has no per-call project argument - so every project's files share one database namespace and are separated only by the `related_id` we stamp and filter on. Every lookup must therefore filter on BOTH project and name, and nothing outside `file_store.cpp` may address a file by its database id. A bug there is a cross-tenant leak, not a mis-sorted list.
+- **Files answer to the scope rules under the reserved `_files` pseudo-collection**, so `requireCapabilityCore` is the one implementation and file access cannot drift from collection access. The leading underscore makes it unshadowable - collection-create rejects `_`-prefixed names. `ctx.files` is **read only**: writing a tenant's asset is a management act and the HTTP route requires project-manage for it.
+- **Two different file size caps, answering two different questions.** `max_file_bytes` (global settings, default 2 MiB) bounds what can be STORED; `kCtxFileMaxBytes` (1 MiB) bounds what one function run may LOAD. A file stored when the limit was generous must not be able to pull megabytes into a 64 MiB JS heap on every run afterwards. The database imposes a cap of its own (`storage.files.max_file_size_mb`, default 500), which is far above either.
+- **A file upload does NOT replace by name at the database layer** - two uploads of one name leave two records - so `FileStore::put` deletes the previous ones itself, uploading FIRST so a failure leaves the old file intact. Reads take the NEWEST record, because an interrupted put can leave two and a read that picked arbitrarily would serve stale bytes some of the time.
 - **Project secrets** live in `<project>:vectorapi_secrets`, encrypted and deliberately NOT in the collection registry - so the documents API and `ctx.collections` both 404 it, and even a policy granting every collection cannot read it. Writes are admin-only; no GET ever returns a value. A `SVAPI_FN_<project>__<NAME>` host variable WINS over a stored secret of the same name, which is the break-glass a stolen API credential cannot shadow.
 - **The runner SUBSCRIBES to project settings; it does not poll.** `ProjectWallMax` wraps a `SettingsStore` with `reloadAll()` plus `startWatch()`, so a changed cap reaches the next run immediately. It used to be a hand-rolled cache on a `project_budget_ttl_sec` TTL, which made clearing a cap look broken for up to 15 s and produced a false bug report. **`reloadAll()`, never `bootstrap()`** - bootstrap WRITES, seeding the settings document, and a runner must never author configuration it only reads.
 - **The runner's `runtime` ceilings are boot-time only**, unlike every hot-reloading setting in the server: QuickJS fixes a runtime's memory limit at creation, so changing one live would mean draining and recreating the whole pool. Editing them means restarting the runner - cheap, because vectorapi answers 503 for that moment and stores nothing unvalidated. By contrast `function_egress_blocked_cidrs` / `function_egress_allow_private` DO hot-reload, because they are read per run.

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.6.0
+0.7.0

+ 13 - 0
api/llms.txt

@@ -176,6 +176,19 @@ Deleting a project deletes its secrets, so a recycled project name inherits noth
 
 **A job run and an HTTP run have different ceilings.** An HTTP route answers a caller holding a socket open (seconds); a queue-claimed run has nobody waiting (minutes, 120 s by default) and draws from its own pool lane, so a slow scheduled job cannot take the runtime an interactive route needs.
 
+## Project files
+
+Small named binary assets per project, so everything customer-specific (a logo, an e-mail signature image) is tenant **data** rather than something bundled into a function's source - a project can then be cloned for another customer by changing data only. Reads follow the scope rules under the reserved pseudo-collection **`_files`**; writes and deletes need a full (non-scoped) key with project access, because replacing a tenant's asset is a management act.
+
+- `PUT    /api/v1/projects/{project}/files/{name}` - Store the **raw request body** under `name`, taking the content type from the `Content-Type` header (default `application/octet-stream`). Not base64 and not a JSON wrapper: a file is bytes. **201** for a new name, **200** for a replacement, and a replacement makes the old bytes unreadable. Answers `{name, content_type, size, checksum, created_at}`. An empty body is **422**; over the size cap is **422** `file_too_large` (default **2 MiB**, `max_file_bytes` in the global settings).
+- `GET    /api/v1/projects/{project}/files/{name}` - The bytes, with the stored content type, plus `X-File-Checksum` and a `Content-Disposition` naming the file. **404** when there is no such file.
+- `GET    /api/v1/projects/{project}/files/{name}/info` - Metadata only, without moving the bytes.
+- `GET    /api/v1/projects/{project}/files` - `{files:[{name, content_type, size, checksum, created_at}]}`, newest first. `limit` (1-1000, default 100, clamped rather than refused) and `offset`.
+- `DELETE /api/v1/projects/{project}/files/{name}` - **404** when absent. Safe against content dedup: identical bytes stored under two names share storage and are reference-counted, so deleting one name leaves the other readable.
+- **A file name is an identifier, not a label.** Letters, digits, `.`, `-` and `_`, at most 128 characters, no leading `.`, no `..`, no path separator and no `:`. A bad name is **422** with the reason, never 404 - the name is unusable rather than missing, and a caller told "not found" would retry a name that can never work.
+- **Deleting a project deletes its files**, so a recycled project name does not inherit the previous tenant's assets.
+- In functions: `ctx.files.get(name)` -> `{name, content_type, size, checksum, created_at, base64}` or **null** when absent, `ctx.files.info(name)`, `ctx.files.list()`. Governed by the function policy under `_files`, exactly like a collection. **Read only** - a function cannot write or delete a file. A single `ctx.files.get()` is capped at **1 MiB** independently of the storage cap, because base64 inflates by a third and a run holds a pooled runtime with its own memory limit.
+
 ## Functions
 
 Server-side JavaScript that serves HTTP routes. These routes require a key granted the project (admin keys reach every project); capability-scoped publishable keys are refused. **Changing a function's policy is admin-only** - developers push code, admins grant what it may touch, exactly as keys already work.

+ 276 - 1
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.6.0",
+    "version": "0.7.0",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {
@@ -4364,6 +4364,281 @@
           }
         }
       }
+    },
+    "/api/v1/projects/{project}/files": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": {
+            "type": "string"
+          }
+        }
+      ],
+      "get": {
+        "summary": "List the project's files, newest first",
+        "description": "Reads follow the scope rules under the reserved '_files' pseudo-collection. limit is clamped to 1-1000 rather than refused.",
+        "parameters": [
+          {
+            "name": "limit",
+            "in": "query",
+            "schema": {
+              "type": "integer",
+              "minimum": 1,
+              "maximum": 1000,
+              "default": 100
+            }
+          },
+          {
+            "name": "offset",
+            "in": "query",
+            "schema": {
+              "type": "integer",
+              "minimum": 0
+            }
+          }
+        ],
+        "responses": {
+          "200": {
+            "description": "The files",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "files": {
+                      "type": "array",
+                      "items": {
+                        "type": "object",
+                        "properties": {
+                          "name": {
+                            "type": "string"
+                          },
+                          "content_type": {
+                            "type": "string"
+                          },
+                          "size": {
+                            "type": "integer"
+                          },
+                          "checksum": {
+                            "type": "string"
+                          },
+                          "created_at": {
+                            "type": "integer"
+                          }
+                        }
+                      }
+                    }
+                  }
+                }
+              }
+            }
+          },
+          "401": {
+            "description": "Unauthorized"
+          },
+          "403": {
+            "description": "Scope does not grant '_files'"
+          }
+        }
+      }
+    },
+    "/api/v1/projects/{project}/files/{name}": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": {
+            "type": "string"
+          }
+        },
+        {
+          "name": "name",
+          "in": "path",
+          "required": true,
+          "schema": {
+            "type": "string",
+            "maxLength": 128,
+            "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*$"
+          },
+          "description": "Letters, digits, '.', '-' and '_'. No leading '.', no '..', no path separator, no ':'."
+        }
+      ],
+      "get": {
+        "summary": "Download the file's bytes",
+        "description": "Answers with the stored bytes and the stored content type, plus X-File-Checksum and a Content-Disposition naming the file.",
+        "responses": {
+          "200": {
+            "description": "The file content",
+            "content": {
+              "*/*": {
+                "schema": {
+                  "type": "string",
+                  "format": "binary"
+                }
+              }
+            }
+          },
+          "404": {
+            "description": "No such file"
+          },
+          "422": {
+            "description": "Unusable file name (with the reason) - never 404, because the name is unusable rather than missing"
+          }
+        }
+      },
+      "put": {
+        "summary": "Store the raw request body under this name, replacing whatever was there",
+        "description": "Requires a full (non-scoped) key with project access: replacing a tenant's asset is a management act. The body is the content - not base64, not a JSON wrapper. Content type comes from the Content-Type header.",
+        "requestBody": {
+          "required": true,
+          "content": {
+            "*/*": {
+              "schema": {
+                "type": "string",
+                "format": "binary"
+              }
+            }
+          }
+        },
+        "responses": {
+          "201": {
+            "description": "Stored under a new name",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "name": {
+                      "type": "string"
+                    },
+                    "content_type": {
+                      "type": "string"
+                    },
+                    "size": {
+                      "type": "integer"
+                    },
+                    "checksum": {
+                      "type": "string"
+                    },
+                    "created_at": {
+                      "type": "integer"
+                    }
+                  }
+                }
+              }
+            }
+          },
+          "200": {
+            "description": "Replaced an existing file",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "name": {
+                      "type": "string"
+                    },
+                    "content_type": {
+                      "type": "string"
+                    },
+                    "size": {
+                      "type": "integer"
+                    },
+                    "checksum": {
+                      "type": "string"
+                    },
+                    "created_at": {
+                      "type": "integer"
+                    }
+                  }
+                }
+              }
+            }
+          },
+          "403": {
+            "description": "Forbidden - scoped keys cannot write files"
+          },
+          "422": {
+            "description": "Empty body, unusable name, or file_too_large"
+          }
+        }
+      },
+      "delete": {
+        "summary": "Delete the file",
+        "description": "Safe against content dedup: identical bytes under two names share storage and are reference-counted, so deleting one name leaves the other readable.",
+        "responses": {
+          "200": {
+            "description": "Deleted"
+          },
+          "404": {
+            "description": "No such file"
+          },
+          "403": {
+            "description": "Forbidden - scoped keys cannot delete files"
+          }
+        }
+      }
+    },
+    "/api/v1/projects/{project}/files/{name}/info": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": {
+            "type": "string"
+          }
+        },
+        {
+          "name": "name",
+          "in": "path",
+          "required": true,
+          "schema": {
+            "type": "string",
+            "maxLength": 128,
+            "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*$"
+          },
+          "description": "Letters, digits, '.', '-' and '_'. No leading '.', no '..', no path separator, no ':'."
+        }
+      ],
+      "get": {
+        "summary": "File metadata without the bytes",
+        "responses": {
+          "200": {
+            "description": "Metadata",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "name": {
+                      "type": "string"
+                    },
+                    "content_type": {
+                      "type": "string"
+                    },
+                    "size": {
+                      "type": "integer"
+                    },
+                    "checksum": {
+                      "type": "string"
+                    },
+                    "created_at": {
+                      "type": "integer"
+                    }
+                  }
+                }
+              }
+            }
+          },
+          "404": {
+            "description": "No such file"
+          }
+        }
+      }
     }
   }
 }

+ 72 - 2
runner/src/host_context.cpp

@@ -6,6 +6,7 @@
 #include "embedding_cache.hpp"
 #include "embeddings.hpp"
 #include "errors.hpp"
+#include "file_store.hpp"
 #include "filters.hpp"
 #include "functions/embed_budget.hpp"
 #include "functions/timezone.hpp"
@@ -142,6 +143,15 @@ JSValue throwApiError(JSContext* ctx, const ApiError& e) {
 /// so each is testable without an engine, a resolver or a database. Not in the
 /// public header - they are an implementation detail of the bindings, not part
 /// of the `ctx` contract.
+/// The most a single ctx.files.get() may pull into the JS heap.
+///
+/// Separate from the HTTP upload cap because they answer different questions:
+/// that one bounds what can be stored, this one bounds what one run can load.
+/// A run holds a pooled runtime with its own memory limit (64 MiB on prod), and
+/// base64 inflates by a third, so a generous value here is a footgun rather
+/// than a feature.
+constexpr size_t kCtxFileMaxBytes = 1024 * 1024;
+
 namespace hostdetail {
 
 /// Where ctx.fetch may connect, and to which address.
@@ -1670,6 +1680,64 @@ struct HostContext::Impl {
 
     // --- time ---------------------------------------------------------------
 
+    /// `__hostFiles(op, payload)` - the project's named binary assets.
+    ///
+    /// Governed by the SAME rule machinery as a collection, under the reserved
+    /// `_files` pseudo-collection, so a function reads a file only when its
+    /// policy says so and file access cannot drift from collection access. A
+    /// real collection can never be called `_files` (collection-create rejects
+    /// a leading underscore), so the name cannot be shadowed.
+    ///
+    /// Read-only on purpose. A function writing a tenant's logo is a management
+    /// act, and the HTTP route already requires project-manage for it; handing
+    /// scripts a write path would quietly widen that.
+    nlohmann::json filesCall(const std::string& op, const nlohmann::json& payload) {
+        if (op != "get" && op != "info" && op != "list")
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "ctx.files does not support '" + op + "'");
+        authorize(kFilesPseudoCollection, op == "list" ? KeyOp::List : KeyOp::Read);
+
+        FileStore store(db);
+        if (op == "list") {
+            nlohmann::json out = nlohmann::json::array();
+            for (const StoredFile& f : store.list(config.project, 100, 0)) out.push_back(f.toJson());
+            return out;
+        }
+
+        const std::string name = payload.is_object() ? payload.value("name", std::string()) : "";
+        const std::string why = fileNameRejection(name);
+        if (!why.empty()) throw ApiError(ErrCode::Unprocessable, "validation", why);
+
+        if (op == "info") {
+            auto meta = store.info(config.project, name);
+            if (!meta) return nlohmann::json(nullptr);
+            return meta->toJson();
+        }
+
+        auto got = store.get(config.project, name);
+        // null rather than a throw for a missing file, matching ctx.collections
+        // .get(): absence is an ordinary answer a script branches on, not an
+        // error it has to catch.
+        if (!got) return nlohmann::json(nullptr);
+
+        // The ctx-side cap. The HTTP route caps what can be STORED, which is
+        // not the same question: a file stored when the limit was generous must
+        // not be able to pull megabytes into a 64 MiB JS heap on every run
+        // afterwards. Refused rather than truncated - half a PNG is worse than
+        // an error.
+        if (got->second.size() > kCtxFileMaxBytes)
+            throw ApiError(ErrCode::Unprocessable, "file_too_large",
+                           "'" + name + "' is " + std::to_string(got->second.size()) +
+                               " bytes, which is more than a function may load (" +
+                               std::to_string(kCtxFileMaxBytes) + ")");
+
+        nlohmann::json out = got->first.toJson();
+        out["base64"] = hostdetail::base64Encode(
+            std::string_view(reinterpret_cast<const char*>(got->second.data()),
+                             got->second.size()));
+        return out;
+    }
+
     /// `__hostTime(op, payload)`. Every answer comes from functions/timezone.hpp
     /// so a function and a cron schedule can never disagree about what 08:00 in
     /// a zone means.
@@ -1870,6 +1938,7 @@ bool HostContext::install(const JsBindingTarget& target, std::string& error) {
     JSValue jobs = JS_NewCFunctionData(ctx, Impl::hostDispatch<&Impl::jobsCall>, 2, 0, 1, data);
     JSValue crypto = JS_NewCFunctionData(ctx, Impl::hostDispatch<&Impl::cryptoCall>, 2, 0, 1, data);
     JSValue time = JS_NewCFunctionData(ctx, Impl::hostDispatch<&Impl::timeCall>, 2, 0, 1, data);
+    JSValue files = JS_NewCFunctionData(ctx, Impl::hostDispatch<&Impl::filesCall>, 2, 0, 1, data);
     JS_FreeValue(ctx, cookie);
 
     const std::string_view prelude = hostPreludeSource();
@@ -1885,8 +1954,8 @@ bool HostContext::install(const JsBindingTarget& target, std::string& error) {
         JS_FreeValue(ctx, exc);
         ok = false;
     } else {
-        JSValueConst args[7] = {*ctxObject, db, fetch, log, jobs, crypto, time};
-        JSValue applied = JS_Call(ctx, factory, JS_UNDEFINED, 7, args);
+        JSValueConst args[8] = {*ctxObject, db, fetch, log, jobs, crypto, time, files};
+        JSValue applied = JS_Call(ctx, factory, JS_UNDEFINED, 8, args);
         if (JS_IsException(applied)) {
             JSValue exc = JS_GetException(ctx);
             error = "the host prelude failed to install: " + toText(ctx, exc);
@@ -1903,6 +1972,7 @@ bool HostContext::install(const JsBindingTarget& target, std::string& error) {
     JS_FreeValue(ctx, jobs);
     JS_FreeValue(ctx, crypto);
     JS_FreeValue(ctx, time);
+    JS_FreeValue(ctx, files);
     return ok;
 }
 

+ 29 - 1
runner/src/host_prelude.js

@@ -19,7 +19,7 @@
 // Every refusal raised here carries a `code`, for the same reason the native
 // side attaches one to an ApiError: a script branches on `e.code`, and matching
 // message text is how a function breaks on a reworded sentence.
-(function (ctx, __hostDb, __hostFetch, __hostLog, __hostJobs, __hostCrypto, __hostTime) {
+(function (ctx, __hostDb, __hostFetch, __hostLog, __hostJobs, __hostCrypto, __hostTime, __hostFiles) {
   'use strict';
 
   function fail(code, message) {
@@ -330,6 +330,34 @@
     return res;
   };
 
+  // --- ctx.files -------------------------------------------------------------
+
+  // The project's named binary assets, so everything customer-specific - a
+  // logo, a signature image - is tenant DATA rather than something baked into
+  // this function's source. READ ONLY: writing a tenant's asset is a
+  // management act and goes through the HTTP route, which requires
+  // project-manage. The project is never an argument, for the same reason it is
+  // not one on ctx.jobs: it is a tenancy boundary, not a parameter.
+  ctx.files = {
+    // Resolves to {name, content_type, size, checksum, created_at, base64},
+    // or null when there is no such file - absence is an ordinary answer to
+    // branch on, matching ctx.collections(...).get().
+    get: function (name) {
+      need(typeof name === 'string' && name.length > 0, 'ctx.files.get() takes a file name');
+      return __hostFiles('get', { name: name });
+    },
+    // Metadata without moving the bytes, for "is it there and how big is it".
+    info: function (name) {
+      need(typeof name === 'string' && name.length > 0, 'ctx.files.info() takes a file name');
+      return __hostFiles('info', { name: name });
+    },
+    // An array, newest first. No arguments: a function that needs paging
+    // through thousands of assets is not the case this exists for.
+    list: function () {
+      return __hostFiles('list', {});
+    },
+  };
+
   // --- ctx.jobs --------------------------------------------------------------
 
   const kMaxDedupeKey = 512;

+ 84 - 0
runner/tests/host_context_test.cpp

@@ -25,6 +25,7 @@
 #include <string>
 #include <vector>
 
+#include "file_store.hpp"
 #include "apikey.hpp"
 #include "db_gateway.hpp"
 #include "errors.hpp"
@@ -1069,6 +1070,89 @@ TEST(HostContext, CryptoIsUsableForAWebhookSignatureCheck) {
     EXPECT_EQ(out.result.value.at("uuid"), 36);
 }
 
+// --- ctx.files -------------------------------------------------------------
+//
+// The gateway in this harness points at loopback port 1 and is never
+// connected, so "the call failed to reach a database" PROVES the policy gate
+// allowed it, and "refused by policy" proves it did not. That is the whole
+// test strategy for the files surface: the bytes are covered by the HTTP
+// integration tests, the GRANT is covered here.
+
+TEST(HostContext, CtxFilesIsRefusedWithoutTheFilesGrant) {
+    // An empty policy grants nothing, which is the floor a first registration
+    // inherits. Reading a file must be refused before anything is fetched.
+    auto out = runScript(httpTrigger({}),
+                         "export default function (ctx) {"
+                         "  try { ctx.files.get('logo.png'); return { reached: true }; }"
+                         "  catch (e) { return { denied: String(e.message || e) }; }"
+                         "}");
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    ASSERT_TRUE(out.result.value.contains("denied"))
+        << "ctx.files.get() was allowed without a grant";
+    const std::string why = out.result.value.at("denied").get<std::string>();
+    EXPECT_NE(why.find("_files"), std::string::npos) << why;
+}
+
+TEST(HostContext, AGrantForAnotherCollectionDoesNotReachFiles) {
+    // The reserved pseudo-collection must not be satisfiable by a rule for a
+    // real collection, nor by a glob that happens to be broad.
+    KeyScope scoped;
+    scoped.rules.push_back(KeyScopeRule{"kb_chunks", {svapi::KeyOp::Read}, false});
+    auto out = runScript(httpTrigger(scoped),
+                         "export default function (ctx) {"
+                         "  try { ctx.files.get('logo.png'); return { reached: true }; }"
+                         "  catch (e) { return { denied: String(e.message || e) }; }"
+                         "}");
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_TRUE(out.result.value.contains("denied"))
+        << "a grant for kb_chunks reached the file store";
+}
+
+// The POSITIVE case deliberately does not live here. This harness's gateway is
+// never connected, and the database client crashes rather than throwing on an
+// RPC made before connect() - true for every surface, not just files (checked:
+// a collection grant behaves identically). So a test that passes the gate
+// cannot also survive, and "allowed" is asserted in the HTTP integration suite
+// instead, where a real database is running:
+// ApiFixture.AScopedKeyNeedsTheFilesGrant proves a `_files` rule is accepted
+// and a rule for another collection is not. Production cannot reach the
+// unconnected state at all - main() exits 1 when healthy() fails.
+
+TEST(HostContext, CtxFilesIsReadOnly) {
+    // No put, no delete. Writing a tenant's asset is a management act and goes
+    // through the HTTP route, which requires project-manage; offering it here
+    // would quietly widen what a function can do.
+    auto out = runScript(httpTrigger({}),
+                         "export default function (ctx) {"
+                         "  return { put: typeof ctx.files.put,"
+                         "           del: typeof ctx.files.delete,"
+                         "           get: typeof ctx.files.get,"
+                         "           info: typeof ctx.files.info,"
+                         "           list: typeof ctx.files.list };"
+                         "}");
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("put"), "undefined");
+    EXPECT_EQ(out.result.value.at("del"), "undefined");
+    EXPECT_EQ(out.result.value.at("get"), "function");
+    EXPECT_EQ(out.result.value.at("info"), "function");
+    EXPECT_EQ(out.result.value.at("list"), "function");
+}
+
+TEST(HostContext, CtxFilesValidatesItsArgumentBeforeAnyGrantCheck) {
+    // A missing name is the script author's typo and should say so, rather
+    // than becoming a lookup for the empty name.
+    auto out = runScript(httpTrigger({}),
+                         "export default function (ctx) {"
+                         "  try { ctx.files.get(); return { reached: true }; }"
+                         "  catch (e) { return { err: String(e.message || e) }; }"
+                         "}");
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    ASSERT_TRUE(out.result.value.contains("err"));
+    EXPECT_NE(out.result.value.at("err").get<std::string>().find("file name"),
+              std::string::npos)
+        << out.result.value.at("err");
+}
+
 TEST(HostContext, TimeAnswersCivilFieldsWithoutIntl) {
     // Guarded on the host actually having a tz database: without tzdata there
     // is nothing to answer with, and a test that fails for that reason would

+ 2 - 0
src/CMakeLists.txt

@@ -22,6 +22,7 @@ add_library(vectorapi_core STATIC
     function_events.cpp
     project_secrets.cpp
     project_secret_store.cpp
+    file_store.cpp
     runner_client.cpp
     embeddings.cpp
     embedding_cache.cpp
@@ -41,6 +42,7 @@ add_library(vectorapi_core STATIC
     handlers/settings.cpp
     handlers/project_settings.cpp
     handlers/project_secrets.cpp
+    handlers/files.cpp
     handlers/relations.cpp
     handlers/functions.cpp
     handlers/function_dispatch.cpp

+ 185 - 0
src/file_store.cpp

@@ -0,0 +1,185 @@
+#include "file_store.hpp"
+
+#include <algorithm>
+
+namespace svapi {
+namespace {
+
+/// Generous enough for a real file name, short enough that it cannot be used to
+/// bloat a listing or a log line.
+constexpr size_t kMaxNameLen = 128;
+
+/// One page of records is plenty to find every copy of one name. A name should
+/// have exactly one; more than a handful means something is badly wrong, and
+/// paginating to chase it would hide the problem rather than fix it.
+constexpr uint32_t kNameLookupLimit = 100;
+
+bool allowedNameChar(unsigned char c) {
+    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
+           c == '.' || c == '-' || c == '_';
+}
+
+} // namespace
+
+nlohmann::json StoredFile::toJson() const {
+    return {{"name", name},
+            {"content_type", contentType},
+            {"size", size},
+            {"checksum", checksum},
+            {"created_at", createdAt}};
+}
+
+std::string fileNameRejection(const std::string& name) {
+    if (name.empty()) return "a file name cannot be empty";
+    if (name.size() > kMaxNameLen)
+        return "a file name may be at most " + std::to_string(kMaxNameLen) + " characters";
+    // Checked before the charset loop so the message names the real problem: a
+    // caller sending "../../etc/passwd" should be told about traversal, not
+    // about the slash.
+    if (name.find("..") != std::string::npos)
+        return "a file name may not contain '..'";
+    if (name.front() == '.')
+        return "a file name may not start with '.'";
+    for (const unsigned char c : name) {
+        if (allowedNameChar(c)) continue;
+        // Named individually where it helps, because "invalid character" sends
+        // the caller hunting.
+        if (c == '/' || c == '\\') return "a file name may not contain a path separator";
+        if (c == ':') return "a file name may not contain ':'";
+        if (c < 0x20 || c == 0x7f) return "a file name may not contain control characters";
+        return "a file name may contain only letters, digits, '.', '-' and '_'";
+    }
+    return {};
+}
+
+std::optional<smartbotic::database::Client::FileRecord> FileStore::newestRecord(
+    const std::string& project, const std::string& name) {
+    // BOTH filters, always: related_id is the only thing separating one
+    // project's files from another's, so a lookup by name alone would reach
+    // across tenants.
+    const auto found =
+        db_.client().listFiles(kFileTypeMarker, project, kNameLookupLimit, 0, "", name);
+    std::optional<smartbotic::database::Client::FileRecord> best;
+    for (const auto& f : found.files) {
+        // Defence in depth. The server filters already; re-checking here means
+        // a change to that filtering cannot silently turn into a leak.
+        if (f.related_id != project || f.name != name) continue;
+        if (!best || f.created_at > best->created_at) best = f;
+    }
+    return best;
+}
+
+StoredFile FileStore::put(const std::string& project, const std::string& name,
+                          const std::vector<uint8_t>& bytes, const std::string& contentType) {
+    // Collected BEFORE the upload, so the new record is not in the list and
+    // cannot delete itself.
+    std::vector<std::string> superseded;
+    const auto existing =
+        db_.client().listFiles(kFileTypeMarker, project, kNameLookupLimit, 0, "", name);
+    for (const auto& f : existing.files)
+        if (f.related_id == project && f.name == name) superseded.push_back(f.id);
+
+    smartbotic::database::Client::FileUploadMeta meta;
+    meta.name = name;
+    meta.mime_type = contentType;
+    meta.file_type = kFileTypeMarker;
+    meta.related_id = project;
+    meta.is_public = false;
+    const auto up = db_.client().uploadFile(bytes, meta);
+
+    // Only now, with the new bytes safely stored. A delete that fails leaves a
+    // superseded record behind, which newestRecord() then ignores - stale
+    // storage, never a wrong answer.
+    for (const std::string& id : superseded)
+        if (id != up.id) db_.client().deleteFile(id);
+
+    StoredFile out;
+    out.name = name;
+    out.contentType = contentType;
+    out.size = up.size;
+    out.checksum = up.checksum;
+    if (auto rec = db_.client().getFileInfo(up.id)) out.createdAt = rec->created_at;
+    return out;
+}
+
+std::optional<StoredFile> FileStore::info(const std::string& project, const std::string& name) {
+    const auto rec = newestRecord(project, name);
+    if (!rec) return std::nullopt;
+    StoredFile out;
+    out.name = rec->name;
+    out.contentType = rec->mime_type;
+    out.size = rec->size;
+    out.checksum = rec->checksum;
+    out.createdAt = rec->created_at;
+    return out;
+}
+
+std::optional<std::pair<StoredFile, std::vector<uint8_t>>> FileStore::get(
+    const std::string& project, const std::string& name) {
+    const auto rec = newestRecord(project, name);
+    if (!rec) return std::nullopt;
+    StoredFile meta;
+    meta.name = rec->name;
+    meta.contentType = rec->mime_type;
+    meta.size = rec->size;
+    meta.checksum = rec->checksum;
+    meta.createdAt = rec->created_at;
+    return std::make_pair(meta, db_.client().downloadFile(rec->id));
+}
+
+std::vector<StoredFile> FileStore::list(const std::string& project, uint32_t limit,
+                                        uint32_t offset) {
+    const auto found = db_.client().listFiles(kFileTypeMarker, project, limit, offset, "", "");
+    std::vector<StoredFile> out;
+    for (const auto& f : found.files) {
+        if (f.related_id != project) continue;
+        StoredFile s;
+        s.name = f.name;
+        s.contentType = f.mime_type;
+        s.size = f.size;
+        s.checksum = f.checksum;
+        s.createdAt = f.created_at;
+        out.push_back(std::move(s));
+    }
+    // Newest first, so a listing is useful without a sort parameter.
+    std::sort(out.begin(), out.end(),
+              [](const StoredFile& a, const StoredFile& b) { return a.createdAt > b.createdAt; });
+    return out;
+}
+
+bool FileStore::remove(const std::string& project, const std::string& name) {
+    const auto found =
+        db_.client().listFiles(kFileTypeMarker, project, kNameLookupLimit, 0, "", name);
+    bool any = false;
+    // Every record of that name, not just the newest: leaving a superseded one
+    // behind would make a deleted name reappear with older content.
+    for (const auto& f : found.files) {
+        if (f.related_id != project || f.name != name) continue;
+        if (db_.client().deleteFile(f.id)) any = true;
+    }
+    return any;
+}
+
+uint32_t FileStore::dropAll(const std::string& project) {
+    uint32_t gone = 0;
+    // Paged, and always from offset 0: each delete shortens the list, so
+    // advancing an offset would step over records.
+    for (;;) {
+        const auto page = db_.client().listFiles(kFileTypeMarker, project, kNameLookupLimit, 0,
+                                                 "", "");
+        bool deletedAny = false;
+        for (const auto& f : page.files) {
+            if (f.related_id != project) continue;
+            if (db_.client().deleteFile(f.id)) {
+                ++gone;
+                deletedAny = true;
+            }
+        }
+        // Stop when a full pass removed nothing, rather than when the page is
+        // empty: a record we cannot delete would otherwise spin here forever.
+        if (!deletedAny) break;
+    }
+    return gone;
+}
+
+} // namespace svapi

+ 118 - 0
src/file_store.hpp

@@ -0,0 +1,118 @@
+#pragma once
+#include "db_gateway.hpp"
+#include <cstdint>
+#include <optional>
+#include <string>
+#include <vector>
+
+/// Small named binary objects, per project.
+///
+/// Exists so everything customer-specific - a logo, an e-mail signature image,
+/// later a document - can live as tenant DATA rather than being bundled into a
+/// function's source. A project can then be cloned for another customer by
+/// changing data only.
+///
+/// NAME-ADDRESSED, deliberately. The database's file store hands back a UUID
+/// per upload; exposing that would put an opaque id into every caller's
+/// configuration and make "the signature image" something you have to look up.
+/// A name per project is what a caller actually wants, so the id stays internal.
+///
+/// ⚠️ PROJECT ISOLATION HERE IS OURS, NOT THE DATABASE'S. The database
+/// namespaces files by `Client::Config::project`, and this service runs ONE
+/// client configured for `default` because collections are qualified per call
+/// instead (see `qualify()`). The file API has no per-call project argument, so
+/// every project's files share one database namespace and are separated only by
+/// the `related_id` we stamp and the `related_id` we filter on. Measured as
+/// working - two projects hold the same name as distinct records, and a listing
+/// filtered by one project returns only its own - but it means a bug in this
+/// file is a cross-tenant data leak rather than a mis-sorted list. Every lookup
+/// must therefore filter on BOTH the project and the name, and nothing outside
+/// this file may address a file by its database id.
+namespace svapi {
+
+/// The reserved pseudo-collection a policy names to grant file access, e.g.
+/// `{"collection": "_files", "ops": ["read"]}`.
+///
+/// Reusing the collection rule machinery rather than inventing a parallel
+/// grant: one implementation of `findRule`, so file access and collection
+/// access cannot drift, and the existing scope editor can already express it.
+/// The leading underscore is what makes it unambiguous - collection-create
+/// rejects `_`-prefixed names, so no real collection can ever shadow it.
+inline constexpr const char* kFilesPseudoCollection = "_files";
+
+/// Stamped into every file we own, so a listing can tell our files from
+/// anything else sharing the database's `default` project.
+inline constexpr const char* kFileTypeMarker = "vectorapi";
+
+/// What a caller is told about a stored file. Never its database id.
+struct StoredFile {
+    std::string name;
+    std::string contentType;
+    uint64_t size = 0;
+    std::string checksum;
+    uint64_t createdAt = 0;
+
+    nlohmann::json toJson() const;
+};
+
+/// Why a name was refused, or empty when it is acceptable.
+///
+/// Pure and separately testable because the name arrives in a URL path and is
+/// therefore hostile input. httplib percent-decodes before a handler sees it,
+/// so a `..` or a `/` can appear inside what looks like a single path segment.
+/// Nothing here depends on that staying true - the charset is restricted to
+/// what a file name legitimately needs.
+std::string fileNameRejection(const std::string& name);
+
+class FileStore {
+public:
+    explicit FileStore(DbGateway& db) : db_(db) {}
+
+    /// Store `bytes` under `name`, replacing whatever was there.
+    ///
+    /// The database's upload does NOT replace by name - two uploads of one name
+    /// leave two records, measured - so this deletes the previous ones itself.
+    /// 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.
+    StoredFile put(const std::string& project, const std::string& name,
+                   const std::vector<uint8_t>& bytes, const std::string& contentType);
+
+    /// Metadata only, without moving the bytes.
+    std::optional<StoredFile> info(const std::string& project, const std::string& name);
+
+    /// Metadata and content.
+    std::optional<std::pair<StoredFile, std::vector<uint8_t>>> get(const std::string& project,
+                                                                   const std::string& name);
+
+    /// Newest first. `limit` is clamped by the caller, not here.
+    std::vector<StoredFile> list(const std::string& project, uint32_t limit, uint32_t offset);
+
+    /// False when there was nothing of that name.
+    ///
+    /// Safe against the database's content dedup: identical bytes under two
+    /// names share one blob and a delete decrements its reference count, so
+    /// removing one name leaves the other readable. Measured, because the
+    /// alternative would be losing a file nobody deleted.
+    bool remove(const std::string& project, const std::string& name);
+
+    /// Every file a project owns, for project delete. Returns how many went.
+    ///
+    /// Without this a deleted project's files would outlive it and a recycled
+    /// project name would inherit the previous tenant's logo - the same class
+    /// of bug as a recycled collection name inheriting its constraints.
+    uint32_t dropAll(const std::string& project);
+
+private:
+    /// The newest record for this project and name, or nullopt.
+    ///
+    /// Newest rather than first: an interrupted `put` can leave two records for
+    /// one name, and a read that picked arbitrarily would return the old bytes
+    /// some of the time, which is far worse than returning the new ones always.
+    std::optional<smartbotic::database::Client::FileRecord> newestRecord(
+        const std::string& project, const std::string& name);
+
+    DbGateway& db_;
+};
+
+} // namespace svapi

+ 163 - 0
src/handlers/files.cpp

@@ -0,0 +1,163 @@
+#include "errors.hpp"
+#include "file_store.hpp"
+#include "json_http.hpp"
+#include "server.hpp"
+
+#include <algorithm>
+
+namespace svapi {
+namespace {
+
+/// The default ceiling on one file, when the setting is unset.
+///
+/// The database imposes none - a 5 MiB upload is accepted without complaint -
+/// so this is the only limit there is. Modest on purpose: these are logos and
+/// signature images, every byte is held in memory during upload and download,
+/// and prod is a 2 GB box. An operator who needs more can raise it; nobody has
+/// to lower it after discovering the hard way that it was unbounded.
+constexpr uint64_t kDefaultMaxFileBytes = 2ull * 1024 * 1024;
+
+uint64_t maxFileBytes(const Settings& s) {
+    return s.maxFileBytes > 0 ? s.maxFileBytes : kDefaultMaxFileBytes;
+}
+
+/// Refuse a bad name with the reason, rather than 404ing on it.
+///
+/// A 404 would be a lie: the name is not missing, it is unusable, and a caller
+/// told "not found" will keep retrying a name that can never work.
+void requireUsableName(const std::string& name) {
+    const std::string why = fileNameRejection(name);
+    if (!why.empty()) throw ApiError(ErrCode::Unprocessable, "validation", why);
+}
+
+/// Files are DATA, so they answer to the scope rule machinery like a collection
+/// does, under the reserved `_files` pseudo-collection. Writes additionally
+/// require project-manage, so a scoped read key cannot replace a tenant's logo.
+void requireFileRead(ServerDeps& d, const ApiKey& k, const httplib::Request& req,
+                     const std::string& project, KeyOp op) {
+    requireCapability(d, k, req, project, kFilesPseudoCollection, op);
+}
+
+} // namespace
+
+void registerFileRoutes(ApiServer& s) {
+    auto& svr = s.raw();
+    ServerDeps* d = &s.deps();
+
+    // List. Newest first; `limit` is clamped rather than refused, because a
+    // caller asking for everything wants as much as we will give, not an error.
+    svr.Get(R"(/api/v1/projects/([^/]+)/files)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        ApiKey k = requireKey(*d, req);
+        const std::string project = req.matches[1];
+        requireFileRead(*d, k, req, project, KeyOp::List);
+
+        auto parseUInt = [](const std::string& v, const char* what) -> uint32_t {
+            try {
+                return static_cast<uint32_t>(std::stoul(v));
+            } catch (...) {
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               std::string(what) + " must be a non-negative integer");
+            }
+        };
+        uint32_t limit = 100, offset = 0;
+        if (req.has_param("limit"))
+            limit = std::clamp<uint32_t>(parseUInt(req.get_param_value("limit"), "limit"), 1, 1000);
+        if (req.has_param("offset")) offset = parseUInt(req.get_param_value("offset"), "offset");
+
+        FileStore store(d->db);
+        nlohmann::json out = nlohmann::json::array();
+        for (const StoredFile& f : store.list(project, limit, offset)) out.push_back(f.toJson());
+        sendJson(res, 200, {{"files", out}});
+    });
+
+    // Download. Answers with the stored bytes and the stored content type, not
+    // JSON: a caller fetching an image wants an image.
+    svr.Get(R"(/api/v1/projects/([^/]+)/files/([^/]+))",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        ApiKey k = requireKey(*d, req);
+        const std::string project = req.matches[1], name = req.matches[2];
+        requireFileRead(*d, k, req, project, KeyOp::Read);
+        requireUsableName(name);
+
+        FileStore store(d->db);
+        auto got = store.get(project, name);
+        if (!got) throw ApiError(ErrCode::NotFound, "not_found", "no such file");
+
+        const std::string type =
+            got->first.contentType.empty() ? "application/octet-stream" : got->first.contentType;
+        res.set_header("X-File-Checksum", got->first.checksum);
+        // The name is echoed so a browser save gets it right, and it is already
+        // charset-restricted, so it cannot inject a header.
+        res.set_header("Content-Disposition", "inline; filename=\"" + got->first.name + "\"");
+        res.set_content(reinterpret_cast<const char*>(got->second.data()), got->second.size(),
+                        type);
+        res.status = 200;
+    });
+
+    // Metadata without the bytes, for a caller that only wants to know whether
+    // a file is there and how big it is.
+    svr.Get(R"(/api/v1/projects/([^/]+)/files/([^/]+)/info)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        ApiKey k = requireKey(*d, req);
+        const std::string project = req.matches[1], name = req.matches[2];
+        requireFileRead(*d, k, req, project, KeyOp::Read);
+        requireUsableName(name);
+
+        FileStore store(d->db);
+        auto meta = store.info(project, name);
+        if (!meta) throw ApiError(ErrCode::NotFound, "not_found", "no such file");
+        sendJson(res, 200, meta->toJson());
+    });
+
+    // Upload, replacing whatever that name held. The raw request body is the
+    // content - not base64, not a JSON wrapper - because a file is bytes and
+    // wrapping them would cost a third of the payload for nothing.
+    svr.Put(R"(/api/v1/projects/([^/]+)/files/([^/]+))",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        ApiKey k = requireKey(*d, req);
+        const std::string project = req.matches[1], name = req.matches[2];
+        // Project-manage, not a scope rule: replacing a tenant's asset is a
+        // management act, and a scoped key exists to be narrower than that.
+        requireProjectManage(k, project);
+        requireUsableName(name);
+
+        auto snap = d->settings.snapshot();
+        const uint64_t cap = maxFileBytes(*snap);
+        if (req.body.size() > cap)
+            throw ApiError(ErrCode::Unprocessable, "file_too_large",
+                           "the file is " + std::to_string(req.body.size()) +
+                               " bytes; the limit is " + std::to_string(cap));
+        if (req.body.empty())
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "the request body is empty; a file needs content");
+
+        std::string type = "application/octet-stream";
+        if (auto it = req.headers.find("Content-Type"); it != req.headers.end() &&
+                                                        !it->second.empty())
+            type = 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);
+        // 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());
+    });
+
+    svr.Delete(R"(/api/v1/projects/([^/]+)/files/([^/]+))",
+               [d](const httplib::Request& req, httplib::Response& res) {
+        ApiKey k = requireKey(*d, req);
+        const std::string project = req.matches[1], name = req.matches[2];
+        requireProjectManage(k, project);
+        requireUsableName(name);
+
+        FileStore store(d->db);
+        if (!store.remove(project, name))
+            throw ApiError(ErrCode::NotFound, "not_found", "no such file");
+        sendJson(res, 200, {{"deleted", name}});
+    });
+}
+
+} // namespace svapi

+ 6 - 0
src/handlers/projects.cpp

@@ -2,6 +2,7 @@
 #include "db_gateway.hpp"
 #include "errors.hpp"
 #include "json_http.hpp"
+#include "file_store.hpp"
 #include "project_secret_store.hpp"
 #include "server.hpp"
 #include <algorithm>
@@ -50,6 +51,11 @@ void registerProjectRoutes(ApiServer& s) {
         // name would inherit the previous tenant's live credentials and hand
         // them to the new tenant's functions as ctx.env.
         ProjectSecretStore(d->db).dropAll(project);
+        // And its files, for the same reason. Without this a deleted project's
+        // logo and signature images outlive it, and a recycled project name
+        // hands the next tenant the previous one's assets - the same class of
+        // bug as a recycled collection name inheriting its constraints.
+        FileStore(d->db).dropAll(project);
         if (!d->db.dropProject(project)) throw ApiError(ErrCode::Unavailable, "db_error", "drop failed");
         sendJson(res, 200, {{"deleted", project}});
     });

+ 1 - 0
src/server.cpp

@@ -169,6 +169,7 @@ void ApiServer::registerRoutes() {
     registerSettingsRoutes(*this);
     registerProjectSettingsRoutes(*this);
     registerProjectSecretRoutes(*this);
+    registerFileRoutes(*this);
     registerRelationRoutes(*this);
     registerFunctionRoutes(*this);
     // LAST. Function dispatch owns /fn/* , and registering it after the

+ 1 - 0
src/server.hpp

@@ -90,6 +90,7 @@ void registerStatsRoutes(ApiServer&);
 void registerSettingsRoutes(ApiServer&);
 void registerProjectSettingsRoutes(ApiServer&);
 void registerProjectSecretRoutes(ApiServer&);
+void registerFileRoutes(ApiServer&);
 void registerRelationRoutes(ApiServer&);
 void registerFunctionRoutes(ApiServer&);
 // Registered LAST: it claims /fn/* , and a function route must never shadow

+ 2 - 0
src/settings.cpp

@@ -19,6 +19,7 @@ Settings Settings::fromJson(const nlohmann::json& j) {
     s.embeddingCacheMaxBytes     = j.value("embedding_cache_max_bytes",   s.embeddingCacheMaxBytes);
     s.embeddingCacheNormalize    = j.value("embedding_cache_normalize",   s.embeddingCacheNormalize);
     s.embeddingClientPoolSize    = j.value("embedding_client_pool_size",  s.embeddingClientPoolSize);
+    s.maxFileBytes               = j.value("max_file_bytes",              s.maxFileBytes);
     if (j.contains("function_egress_blocked_cidrs") && j["function_egress_blocked_cidrs"].is_array()) {
         // Bind before iterating: a range-for over a temporary subobject of a
         // parsed document dangles.
@@ -47,6 +48,7 @@ nlohmann::json Settings::toJson() const {
             {"embedding_cache_max_bytes",   embeddingCacheMaxBytes},
             {"embedding_cache_normalize",   embeddingCacheNormalize},
             {"embedding_client_pool_size",  embeddingClientPoolSize},
+            {"max_file_bytes",              maxFileBytes},
             {"function_egress_blocked_cidrs", functionEgressBlockedCidrs},
             {"function_egress_allow_private", functionEgressAllowPrivate},
             {"captcha_provider",   captchaProvider},

+ 5 - 0
src/settings.hpp

@@ -21,6 +21,11 @@ struct Settings {
     uint64_t    embeddingCacheMaxBytes     = 268435456;  // 256 MB
     bool        embeddingCacheNormalize    = false;      // opt-in trim+lowercase
     uint32_t    embeddingClientPoolSize    = 4;          // keep-alive clients per upstream origin
+    /// Ceiling on ONE stored file, in bytes. 0 means the handler's default.
+    /// The database imposes no limit of its own - a 5 MiB upload is accepted
+    /// without complaint - so this is the only cap there is, and every byte is
+    /// held in memory during an upload or a download.
+    uint64_t    maxFileBytes               = 2ull * 1024 * 1024;
 
     /// Extra CIDRs a function's ctx.fetch may not reach. ADDED to the built-in
     /// defaults, never substituted for them - see SsrfPolicy::fromSettings.

+ 7 - 0
tests/CMakeLists.txt

@@ -218,6 +218,13 @@ target_include_directories(test_embed_budget PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_embed_budget PRIVATE GTest::gtest_main)
 gtest_discover_tests(test_embed_budget)
 
+# fileNameRejection() is pure, but file_store.cpp also holds the store, which
+# links the database client - so this links vectorapi_core like the rest.
+add_executable(test_file_name test_file_name.cpp)
+target_include_directories(test_file_name PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_file_name PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_file_name)
+
 # Document body shaping and the increment deltas: header-only and pure.
 add_executable(test_documents_util test_documents_util.cpp)
 target_include_directories(test_documents_util PRIVATE ${CMAKE_SOURCE_DIR}/src)

+ 12 - 0
tests/api_fixture.hpp

@@ -1,5 +1,6 @@
 #pragma once
 #include "db_test_util.hpp"
+#include "file_store.hpp"
 #include "server.hpp"
 #include <gtest/gtest.h>
 #include <httplib.h>
@@ -75,6 +76,17 @@ protected:
         } catch (const std::exception&) {
             // No previous run to clean up.
         }
+        // Files too. They live in the database's own file store rather than in
+        // a collection, so dropping the project's collections does not touch
+        // them - and against a persistent database the previous run's assets
+        // would survive, which made a PUT of a "new" file answer 200 instead
+        // of 201. Same lesson as the index declarations above: anything that
+        // outlives a project has to be purged here explicitly.
+        try {
+            FileStore(*db_).dropAll(project_);
+        } catch (const std::exception&) {
+            // No previous run, or no file store to clean.
+        }
         db_->dropProject(project_);
         db_->client().dropCollection(qualify(project_, "vectorapi_collections"));
         db_->ensureProject(project_);

+ 202 - 0
tests/test_api_integration.cpp

@@ -2379,6 +2379,208 @@ TEST_F(ApiFixture, ARecycledCollectionNameInheritsNoConstraint) {
                                         "be refused; body: " << declared->body;
 }
 
+// --- Project files ---------------------------------------------------------
+//
+// The store is name-addressed per project, and PROJECT ISOLATION IS OURS: the
+// database namespaces files by the client's project, this service runs one
+// client for `default`, and separation comes only from the related_id we stamp
+// and filter on. So the isolation test below is not a nice-to-have.
+
+TEST_F(ApiFixture, FileRoundTripKeepsBytesAndContentType) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/files/logo.png";
+    // Deliberately includes a NUL and high bytes: a store that went through a
+    // C string, or re-encoded as text, would corrupt exactly this.
+    std::string body("\x89PNG\r\n\x1a\n", 8);
+    body += std::string("\0\xff\xfe binary", 10);
+
+    auto put = c.Put(base.c_str(), body, "image/png");
+    ASSERT_TRUE(put); ASSERT_EQ(put->status, 201) << put->body;
+    auto meta = nlohmann::json::parse(put->body);
+    EXPECT_EQ(meta["name"], "logo.png");
+    EXPECT_EQ(meta["content_type"], "image/png");
+    EXPECT_EQ(meta["size"], body.size());
+    EXPECT_FALSE(meta["checksum"].get<std::string>().empty());
+
+    auto got = c.Get(base.c_str());
+    ASSERT_TRUE(got); ASSERT_EQ(got->status, 200);
+    EXPECT_EQ(got->body, body) << "bytes must round-trip exactly";
+    EXPECT_EQ(got->get_header_value("Content-Type"), "image/png");
+
+    // A replacement is 200, not 201, so a caller can tell which happened.
+    auto again = c.Put(base.c_str(), std::string("replaced"), "text/plain");
+    ASSERT_TRUE(again); EXPECT_EQ(again->status, 200) << again->body;
+    auto after = c.Get(base.c_str());
+    ASSERT_TRUE(after);
+    EXPECT_EQ(after->body, "replaced") << "a replacement must not leave the old bytes readable";
+    EXPECT_EQ(after->get_header_value("Content-Type"), "text/plain");
+}
+
+TEST_F(ApiFixture, FilesAreIsolatedBetweenProjects) {
+    auto c = admin();
+    const std::string other = project_ + "b";
+    ASSERT_EQ(c.Post("/api/v1/projects", nlohmann::json{{"name", other}}.dump(),
+                     "application/json")->status, 201);
+
+    const std::string mine  = "/api/v1/projects/" + project_ + "/files/shared.txt";
+    const std::string yours = "/api/v1/projects/" + other + "/files/shared.txt";
+    ASSERT_EQ(c.Put(mine.c_str(), std::string("MINE"), "text/plain")->status, 201);
+    ASSERT_EQ(c.Put(yours.c_str(), std::string("YOURS"), "text/plain")->status, 201);
+
+    // The same name in two projects is two files, and neither sees the other.
+    auto a = c.Get(mine.c_str());
+    auto b = c.Get(yours.c_str());
+    ASSERT_TRUE(a); ASSERT_TRUE(b);
+    EXPECT_EQ(a->body, "MINE");
+    EXPECT_EQ(b->body, "YOURS");
+
+    // And a listing shows only the project's own. Checked with a name that
+    // exists ONLY in the other project, because a shared name cannot tell the
+    // two apart - which is exactly the mistake worth not making in the test
+    // that guards tenancy.
+    const std::string onlyTheirs = "/api/v1/projects/" + other + "/files/theirs-only.txt";
+    ASSERT_EQ(c.Put(onlyTheirs.c_str(), std::string("theirs"), "text/plain")->status, 201);
+
+    auto list = c.Get(("/api/v1/projects/" + project_ + "/files").c_str());
+    ASSERT_TRUE(list); ASSERT_EQ(list->status, 200);
+    const auto files = nlohmann::json::parse(list->body)["files"];
+    int sawShared = 0;
+    for (const auto& f : files) {
+        EXPECT_NE(f["name"], "theirs-only.txt") << "another project's file appeared in our listing";
+        if (f["name"] == "shared.txt") ++sawShared;
+    }
+    EXPECT_EQ(sawShared, 1) << "our own shared.txt should appear exactly once";
+    // And their file is not reachable by name through our project either.
+    EXPECT_EQ(c.Get(("/api/v1/projects/" + project_ + "/files/theirs-only.txt").c_str())->status,
+              404);
+
+    // Deleting one project's file leaves the other's readable. The database
+    // dedups identical content by checksum and a delete decrements a reference
+    // count, so this is the case where getting it wrong loses someone's data.
+    ASSERT_EQ(c.Delete(mine.c_str())->status, 200);
+    EXPECT_EQ(c.Get(mine.c_str())->status, 404);
+    auto survivor = c.Get(yours.c_str());
+    ASSERT_TRUE(survivor);
+    EXPECT_EQ(survivor->status, 200);
+    EXPECT_EQ(survivor->body, "YOURS");
+
+    c.Delete(("/api/v1/projects/" + other).c_str());
+}
+
+TEST_F(ApiFixture, IdenticalContentUnderTwoNamesSurvivesDeletingOne) {
+    // The dedup case explicitly: same bytes, two names, delete one.
+    auto c = admin();
+    const std::string a = "/api/v1/projects/" + project_ + "/files/dup-a.bin";
+    const std::string b = "/api/v1/projects/" + project_ + "/files/dup-b.bin";
+    const std::string same = "IDENTICAL-CONTENT-FOR-DEDUP";
+    ASSERT_EQ(c.Put(a.c_str(), same, "application/octet-stream")->status, 201);
+    ASSERT_EQ(c.Put(b.c_str(), same, "application/octet-stream")->status, 201);
+    ASSERT_EQ(c.Delete(a.c_str())->status, 200);
+    auto survivor = c.Get(b.c_str());
+    ASSERT_TRUE(survivor);
+    ASSERT_EQ(survivor->status, 200) << "deleting one name destroyed the shared blob";
+    EXPECT_EQ(survivor->body, same);
+}
+
+TEST_F(ApiFixture, FileNamesAreValidatedNotFourOhFoured) {
+    // 422 with a reason, never 404: the name is unusable, not missing, and a
+    // caller told "not found" retries a name that can never work.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/files/";
+    for (const char* bad : {"a:b", ".env", "sp%20ace"}) {
+        auto r = c.Get((base + bad).c_str());
+        ASSERT_TRUE(r) << bad;
+        EXPECT_EQ(r->status, 422) << bad << " -> " << r->body;
+    }
+}
+
+TEST_F(ApiFixture, AnOversizeFileIsRefused) {
+    auto c = admin();
+    // The default cap is 2 MiB, so 3 MiB must be refused rather than stored.
+    const std::string big(3 * 1024 * 1024, 'x');
+    auto r = c.Put(("/api/v1/projects/" + project_ + "/files/big.bin").c_str(), big,
+                   "application/octet-stream");
+    ASSERT_TRUE(r);
+    EXPECT_EQ(r->status, 422) << r->body;
+    EXPECT_NE(r->body.find("file_too_large"), std::string::npos) << r->body;
+    // And nothing was stored under that name.
+    EXPECT_EQ(c.Get(("/api/v1/projects/" + project_ + "/files/big.bin").c_str())->status, 404);
+}
+
+TEST_F(ApiFixture, AnEmptyBodyIsRefused) {
+    auto c = admin();
+    auto r = c.Put(("/api/v1/projects/" + project_ + "/files/empty.bin").c_str(), std::string(),
+                   "application/octet-stream");
+    ASSERT_TRUE(r);
+    EXPECT_EQ(r->status, 422) << r->body;
+}
+
+TEST_F(ApiFixture, AMissingFileIs404AndDeleteOfItToo) {
+    auto c = admin();
+    const std::string p = "/api/v1/projects/" + project_ + "/files/nope.bin";
+    EXPECT_EQ(c.Get(p.c_str())->status, 404);
+    EXPECT_EQ(c.Get((p + "/info").c_str())->status, 404);
+    EXPECT_EQ(c.Delete(p.c_str())->status, 404);
+}
+
+TEST_F(ApiFixture, DeletingAProjectTakesItsFiles) {
+    // Otherwise a recycled project name hands the next tenant the previous
+    // one's logo - the same class of bug as a recycled collection name
+    // inheriting its constraints.
+    auto c = admin();
+    const std::string tmp = project_ + "c";
+    ASSERT_EQ(c.Post("/api/v1/projects", nlohmann::json{{"name", tmp}}.dump(),
+                     "application/json")->status, 201);
+    const std::string f = "/api/v1/projects/" + tmp + "/files/asset.txt";
+    ASSERT_EQ(c.Put(f.c_str(), std::string("tenant data"), "text/plain")->status, 201);
+    ASSERT_EQ(c.Delete(("/api/v1/projects/" + tmp).c_str())->status, 200);
+
+    // Recreate the same project name; the file must be gone.
+    ASSERT_EQ(c.Post("/api/v1/projects", nlohmann::json{{"name", tmp}}.dump(),
+                     "application/json")->status, 201);
+    auto leaked = c.Get(f.c_str());
+    ASSERT_TRUE(leaked);
+    EXPECT_EQ(leaked->status, 404) << "a deleted project's file outlived it: " << leaked->body;
+    c.Delete(("/api/v1/projects/" + tmp).c_str());
+}
+
+TEST_F(ApiFixture, AScopedKeyNeedsTheFilesGrant) {
+    // Files answer to the same rule machinery as collections, under the
+    // reserved `_files` pseudo-collection. A key scoped to a collection must
+    // not reach them.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/files/grant.txt";
+    ASSERT_EQ(c.Put(base.c_str(), std::string("secret-ish"), "text/plain")->status, 201);
+
+    // Scoped to a collection, not to files.
+    auto mk = c.Post("/api/v1/keys",
+        nlohmann::json{{"label","no-files"},{"projects",{project_}},{"admin",false},
+                       {"scope",{{"rules",{{{"collection","something"},{"ops",{"read"}}}}}}}}
+            .dump(), "application/json");
+    ASSERT_TRUE(mk); ASSERT_EQ(mk->status, 201) << mk->body;
+    const std::string noFiles = nlohmann::json::parse(mk->body)["key"];
+    auto denied = request("GET", base, "", "", noFiles);
+    ASSERT_TRUE(denied);
+    EXPECT_EQ(denied->status, 403) << denied->body;
+
+    // Scoped to _files, it works.
+    auto mk2 = c.Post("/api/v1/keys",
+        nlohmann::json{{"label","yes-files"},{"projects",{project_}},{"admin",false},
+                       {"scope",{{"rules",{{{"collection","_files"},{"ops",{"read"}}}}}}}}
+            .dump(), "application/json");
+    ASSERT_TRUE(mk2); ASSERT_EQ(mk2->status, 201) << mk2->body;
+    const std::string withFiles = nlohmann::json::parse(mk2->body)["key"];
+    auto allowed = request("GET", base, "", "", withFiles);
+    ASSERT_TRUE(allowed);
+    EXPECT_EQ(allowed->status, 200) << allowed->body;
+    EXPECT_EQ(allowed->body, "secret-ish");
+
+    // But a scoped key still cannot WRITE one - that is project-manage.
+    auto write = request("PUT", base, "nope", "text/plain", withFiles);
+    ASSERT_TRUE(write);
+    EXPECT_EQ(write->status, 403) << write->body;
+}
+
 // --- Atomic increment (database 2.12.0) ------------------------------------
 
 TEST_F(ApiFixture, IncrementAddsAndReturnsNewValues) {

+ 86 - 0
tests/test_file_name.cpp

@@ -0,0 +1,86 @@
+#include "file_store.hpp"
+#include <gtest/gtest.h>
+
+using svapi::fileNameRejection;
+
+namespace {
+
+TEST(FileName, OrdinaryNamesAreAccepted) {
+    for (const char* ok : {"logo.png", "signature-2024.png", "a", "A_B-c.1.bin",
+                           "very.long.but.fine.name.webp"})
+        EXPECT_EQ(fileNameRejection(ok), "") << ok;
+}
+
+// The name arrives in a URL path, and httplib percent-decodes BEFORE a handler
+// sees it - so %2e%2e%2f becomes ../ inside what looked like one segment. These
+// are the cases that must never reach the store, whatever the router did.
+TEST(FileName, TraversalIsRefused) {
+    for (const char* bad : {"..", "../x", "a/../b", "..%2f", "a..b"})
+        EXPECT_NE(fileNameRejection(bad), "") << bad;
+    // The message names traversal rather than the slash, so a caller sending
+    // "../../etc/passwd" is told the actual problem.
+    EXPECT_NE(fileNameRejection("../../etc/passwd").find(".."), std::string::npos);
+}
+
+TEST(FileName, PathSeparatorsAreRefused) {
+    EXPECT_NE(fileNameRejection("a/b"), "");
+    EXPECT_NE(fileNameRejection("a\\b"), "");
+    EXPECT_NE(fileNameRejection("/abs"), "");
+}
+
+TEST(FileName, TheQualifySeparatorIsRefused) {
+    // ':' is what qualify() uses between a project and a collection. A file
+    // name never reaches qualify(), but refusing it costs nothing and removes
+    // the need to prove that it never will.
+    EXPECT_NE(fileNameRejection("a:b"), "");
+}
+
+TEST(FileName, ControlCharactersAndCrlfAreRefused) {
+    // CR or LF would be an echoed header injection: the name goes back in
+    // Content-Disposition.
+    EXPECT_NE(fileNameRejection(std::string("a\nb")), "");
+    EXPECT_NE(fileNameRejection(std::string("a\rb")), "");
+    EXPECT_NE(fileNameRejection(std::string("a\x7f") + "b"), "");
+    EXPECT_NE(fileNameRejection(std::string("a\0b", 3)), "");
+}
+
+TEST(FileName, QuotesAreRefused) {
+    // Also header injection: the name is wrapped in quotes in
+    // Content-Disposition, so a quote would break out of them.
+    EXPECT_NE(fileNameRejection("a\"b"), "");
+    EXPECT_NE(fileNameRejection("a'b"), "");
+}
+
+TEST(FileName, EmptyAndOverlongAreRefused) {
+    EXPECT_NE(fileNameRejection(""), "");
+    EXPECT_EQ(fileNameRejection(std::string(128, 'a')), "");
+    EXPECT_NE(fileNameRejection(std::string(129, 'a')), "");
+}
+
+TEST(FileName, ALeadingDotIsRefused) {
+    // No dotfiles. They are not useful here and they read as hidden, which is
+    // the wrong affordance for something a tenant is meant to manage.
+    EXPECT_NE(fileNameRejection(".env"), "");
+    EXPECT_NE(fileNameRejection(".x"), "");
+    EXPECT_EQ(fileNameRejection("x.env"), "");
+}
+
+TEST(FileName, SpacesAndUnicodeAreRefused) {
+    // Restrictive on purpose. A name is an identifier a caller types into a
+    // config file, not a display label, and every exotic character is one more
+    // thing that has to round-trip through a URL, a header and a log line.
+    EXPECT_NE(fileNameRejection("my logo.png"), "");
+    EXPECT_NE(fileNameRejection("logó.png"), "");
+}
+
+TEST(FileName, EveryRejectionExplainsItself) {
+    // A reason, never a bare "invalid": the caller has to be able to fix it.
+    for (const char* bad : {"", "..", "a/b", "a:b", ".x", "my logo.png",
+                            "a\"b"}) {
+        const std::string why = fileNameRejection(bad);
+        ASSERT_FALSE(why.empty()) << bad;
+        EXPECT_GT(why.size(), 10u) << "unhelpful message for '" << bad << "': " << why;
+    }
+}
+
+} // namespace