Browse Source

feat(auth): express authorization over a Principal, not only an ApiKey

Groundwork for server-side functions. A function holds no API key: it never
authenticates over the wire, it IS the server, and giving it one would mean
storing a usable secret inside a function definition. It still needs the same
questions answered - may it reach this project, may it perform this op on this
collection - and those answers must come from the same code, or function access
and HTTP access drift apart. That drift is exactly the class of bug the 0.3.3
error-code work was spent undoing.

Principal is now the one notion of a caller. An ApiKey converts to it with an
explicit factory; a function identity will construct one directly.

requireCapability turned out to be doing two jobs. Project grant, scope rule and
rate limit apply to any caller; the Origin allow-list and the captcha header
need an HTTP request and are meaningless for a cron or event-triggered run. They
are now separated:

  requireCapabilityCore(Principal, project, collection, op)  - grant, rule, limit
  requireCapability(deps, ApiKey, req, ...)                  - core, then Origin + captcha

Because of that split NO handler changes: a naive refactor would have touched 32
call sites across 10 files. The existing ApiKey signatures stay and delegate.

Principal::of is an explicit factory rather than an implicit conversion, or
every existing requireAdmin(key) call would become ambiguous against the new
overload. A test pins Principal::canAccess against ApiKey::canAccess across
plain, wildcard, admin and scoped keys so the two cannot silently diverge.

The HTTP form re-reads the matching rule after calling the core, which looks
redundant and is not: the core returns void, so the rule pointer must be fetched
again to know whether THIS rule demands a human token. Folding that check into
the core would make every future cron run demand a captcha.

Also lands the approved design for the runtime (docs/superpowers/specs/).

173/173 via packaging/devstack/run-tests.sh.
fszontagh 1 tháng trước cách đây
mục cha
commit
94b852c370

+ 202 - 0
docs/superpowers/specs/2026-10-06-function-runtime-design.md

@@ -0,0 +1,202 @@
+# Function runtime (QuickJS) - design
+
+Server-side JavaScript in smartbotic-vectorapi: user-supplied functions that
+serve HTTP routes, and later run on a schedule or on database events.
+
+Status: approved 2026-10-06. This document is the contract for implementation.
+
+## Why
+
+n8n covers orchestration well, but two things it cannot do: react to database
+changes (only vectorapi holds the `subscribe()` streams), and run logic next to
+the data (a chunk-embed-upsert loop costs one HTTP hop per item through n8n).
+
+## Shape
+
+```
+person / LLM ──POST /projects/{p}/functions──▶ vectorapi
+                                                 │ validate on a runner, then store
+                                                 ▼
+                                      <project>:vectorapi_functions
+                                                 │
+ HTTP request ──▶ route match ──dispatch(sync)──▶ ┌──────────┐
+                                                  │  runner  │  QuickJS pool
+ cron / DB event ──▶ enqueue ──claim──▶ job queue │  (N inst)│  reads registry + data itself
+                                                  └────┬─────┘
+                                                       ▼
+                                             smartbotic-database
+```
+
+The runner is a second binary in this repo linking `vectorapi_core`. It holds
+its own `DbGateway`, so `ctx.collections(...)` is a direct call - never loopback
+HTTP to vectorapi - and it enforces policy with the same `KeyScope` code
+vectorapi uses. One implementation of authorization, two processes.
+
+vectorapi does NOT link QuickJS.
+
+## Identity and policy
+
+A function is a principal, not a key holder. No secret: it never authenticates
+over the wire, it *is* the server.
+
+```cpp
+struct FunctionIdentity { std::string project; std::string id; KeyScope scope; };
+```
+
+- **`id` is declared in the script** (`export const on = { id: 'kb-search', ... }`).
+  The file path is incidental, so renames and moves carry the policy with them.
+  Duplicate ids fail the load (both marked invalid). A missing id is an error,
+  never a silent path fallback.
+- **Policy is server state**, stored on the function's registry row and edited by
+  an admin. Pushing code can never widen access.
+- **First registration inherits** `default_function_policy` from the project's
+  settings document (beside the per-project embedding overrides).
+- A function whose source is removed keeps its row marked `missing` rather than
+  being deleted, so a mistake cannot silently drop a policy.
+
+### The Principal refactor
+
+`requireCapability()` today takes an `ApiKey`. It becomes:
+
+```cpp
+struct Principal { std::vector<std::string> projects; bool admin; const KeyScope* scope; };
+```
+
+with `ApiKey` and `FunctionIdentity` both convertible to it. This is the only
+way function access and HTTP access cannot drift apart. Mechanical but broad: it
+touches every handler's auth call.
+
+## The ctx.* surface
+
+Mirrors vectorapi's own concepts and its documented `field:op:value` filter
+grammar, so knowledge transfers from the HTTP API.
+
+```js
+export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method: 'GET' };
+
+export default async function (ctx) {
+  const docs = await ctx.collections('kb_chunks')
+      .filter(`topic:eq:${ctx.params.topic}`).limit(20).find();
+  const hits = await ctx.collections('kb_chunks')
+      .search({ query_text: ctx.query.q, top_k: 5, filters: ['lang:eq:hu'] });
+  await ctx.collections('audit').insert({ topic: ctx.params.topic });
+  return { status: 200, body: { docs, hits } };
+}
+```
+
+- documents: `.filter() .limit() .offset() .sort()` then
+  `.find() .get(id) .insert(doc) .update(id, doc) .patch(id, fields) .delete(id)`
+- vectors: `.search({query_text|query_vector, top_k, min_score, filters})`,
+  `.store({text|vector, metadata})` - embedding resolves through the existing
+  precedence, so a project's provider override applies
+- `ctx.env` (secrets), `ctx.fetch` (SSRF-guarded egress), `ctx.log`
+- NOT in slice 1: filesystem, storage
+
+Host calls are synchronous; `await` works because awaiting a non-promise is a
+no-op. The ergonomic builder is a JS prelude over a few native bindings
+(`__hostDb`, `__hostFetch`), keeping common logic in C++ and scripts small.
+
+`ctx.*` makes no loopback HTTP call. `.search({query_text})` does make an
+OUTBOUND call to the embedding provider - that is not loopback.
+
+## Storage
+
+One document per function in `<project>:vectorapi_functions`:
+
+```
+{ function_id, path, source, content_hash, descriptor, policy,
+  enabled, valid, last_error, created_at, updated_at }
+```
+
+`function_id`, not `id`: the database client strips a top-level `id` from stored
+bodies (the same reason API keys store `key_id`).
+
+## HTTP surface
+
+| Route | Who |
+|---|---|
+| `GET/POST /api/v1/projects/{p}/functions` | project-manage |
+| `GET/PUT/DELETE .../functions/{id}` | project-manage |
+| `PUT .../functions/{id}/policy` | **admin** |
+| `PUT .../functions/{id}/enabled` | project-manage |
+| `POST .../functions/{id}/invoke` | project-manage |
+| `GET .../functions/{id}/logs` | project-manage |
+
+Code and capability are split on purpose: developers write functions, admins
+grant what they may touch - mirroring keys, which are already admin-only.
+
+**Validation runs on a runner**, not in vectorapi: a write is compiled and its
+`on` block parsed before storage, and rejected with the compile error otherwise.
+The engine that validates is therefore the engine that will execute. Creating a
+function with no healthy runner returns 503.
+
+## Runner protocol
+
+Runner discovery is a static list in vectorapi's config, health-checked.
+Dynamic registration waits until autoscaling actually exists.
+
+HTTP functions, synchronous, retried on the next healthy runner:
+
+```
+POST /run  { project, function_id, trigger:{method,path,params,query,headers,body} }
+    ->     { status, headers, body, console[], duration_ms, error? }
+POST /validate { source, path }  -> { ok, descriptor?, error? }
+GET  /health
+```
+
+The payload is small because the runner reads source, `content_hash` and policy
+from the registry itself and caches compiled bytecode by hash.
+
+Cron and DB-event jobs go through one global `vectorapi_function_jobs`
+collection with a `project` field:
+
+```
+{ project, function_id, trigger, state: pending|claimed|done|failed,
+  claimed_by, claimed_at, attempts, depth, run_after }
+```
+
+A runner claims with `updateIfVersion()`; a version conflict means another
+runner won it. A claim older than a timeout returns to `pending`, which is how a
+runner dying mid-job gets retried elsewhere.
+
+The **scheduler stays in vectorapi**: there must be exactly one, or N runners
+each fire every cron. vectorapi is already the singleton and already holds the
+subscribe streams DB events will need.
+
+## Safety
+
+- Per-run limits: memory, wall time (descriptor `timeoutMs`, clamped to a
+  configured max), stack. A fresh `JSContext` per run so nothing leaks between
+  tenants. The pool recycles a runtime whose allocation stays high.
+- SSRF guard: CIDR blocklist from settings with built-in defaults, DNS resolve
+  then classify every returned address, fail closed on unparseable input. It
+  blocks loopback, so a function cannot call its own API. Intentional.
+- `rateLimitPerMin` already exists in `KeyScope` and applies unchanged.
+- The job record carries `depth` from day one, though nothing reads it until DB
+  events land: retrofitting a self-trigger guard is how you get an infinite loop
+  in production.
+
+## Slice 1
+
+**In**: runner binary (pool, host context, policy enforcement, `/run`,
+`/validate`, `/health`), functions CRUD, HTTP dispatch on route match, manual
+invoke, run logs.
+
+**Out**, each its own later cycle: cron, DB events, shared modules (needs a
+module loader with path jailing - a security boundary, not a convenience),
+filesystem, storage API, git export.
+
+## Testing
+
+Unit: descriptor parsing, route matching, policy enforcement, limit enforcement,
+SSRF classification. Integration through `packaging/devstack`, extended to run a
+runner alongside: deploy a function, call it, then assert the things that must
+FAIL - a denied collection, a wall-time timeout, a blocked egress.
+
+## Risks
+
+- Two binaries that must version together, the same discipline as the client ABI
+  pin.
+- The `Principal` refactor is broad, touching every handler's auth call.
+- HTTP functions gain a network hop; measure the latency before anyone builds a
+  chatty endpoint on it.

+ 1 - 0
src/CMakeLists.txt

@@ -9,6 +9,7 @@ add_library(vectorapi_core STATIC
     project_settings.cpp
     outbound_http.cpp
     apikey.cpp
+    principal.cpp
     key_store.cpp
     settings_store.cpp
     collection_registry.cpp

+ 17 - 0
src/principal.cpp

@@ -0,0 +1,17 @@
+#include "principal.hpp"
+#include <algorithm>
+
+namespace svapi {
+
+bool Principal::canAccess(const std::string& project) const {
+    if (admin) return true;
+    if (!projects) return false;
+    return std::find(projects->begin(), projects->end(), "*") != projects->end()
+        || std::find(projects->begin(), projects->end(), project) != projects->end();
+}
+
+Principal Principal::of(const ApiKey& k) {
+    return Principal{k.id, &k.projects, k.admin, k.scope ? &*k.scope : nullptr};
+}
+
+} // namespace svapi

+ 48 - 0
src/principal.hpp

@@ -0,0 +1,48 @@
+#pragma once
+#include "apikey.hpp"
+#include <string>
+#include <vector>
+
+namespace svapi {
+
+/// Who is asking.
+///
+/// Authorization used to be expressed directly in terms of ApiKey, which was
+/// fine while every caller held one. A server-side function holds no key: it
+/// never authenticates over the wire, it IS the server, and giving it one would
+/// mean storing a usable secret inside a function definition. It still needs
+/// the same questions answered - may it reach this project, may it perform this
+/// op on this collection - and those answers must come from the SAME code, or
+/// function access and HTTP access will drift apart.
+///
+/// So Principal is the one notion of a caller: an ApiKey converts to it, and so
+/// does a function identity.
+///
+/// Holds non-owning pointers, so it must not outlive whatever it was built
+/// from. That is always a stack-local key or identity for the duration of one
+/// request or one function run.
+struct Principal {
+    /// Identifies the caller for rate limiting and attribution: a key id, or a
+    /// function id. Distinct namespaces, so a function cannot consume a key's
+    /// rate-limit budget.
+    std::string id;
+
+    /// May contain "*". Never null.
+    const std::vector<std::string>* projects = nullptr;
+
+    bool admin = false;
+
+    /// Null means unscoped: full access within the granted projects. A scoped
+    /// caller is restricted to the rules it carries.
+    const KeyScope* scope = nullptr;
+
+    /// True if admin, or the project list contains "*" or this project.
+    /// Deliberately mirrors ApiKey::canAccess, and a test pins them together.
+    bool canAccess(const std::string& project) const;
+
+    /// Explicit on purpose: an implicit conversion would make every existing
+    /// requireAdmin(key) call ambiguous against the Principal overload.
+    static Principal of(const ApiKey& k);
+};
+
+} // namespace svapi

+ 33 - 8
src/server.cpp

@@ -32,10 +32,38 @@ ApiKey requireKey(ServerDeps& d, const httplib::Request& req) {
     if (auto k = resolveKey(d, req)) return *k;
     throw ApiError(ErrCode::Unauthorized, "unauthorized", "missing or invalid credentials");
 }
-void requireAdmin(const ApiKey& k) {
-    if (!k.admin) throw ApiError(ErrCode::Forbidden, "forbidden", "admin privilege required");
+// --- Principal forms: the real implementations --------------------------------
+
+void requireAdmin(const Principal& p) {
+    if (!p.admin) throw ApiError(ErrCode::Forbidden, "forbidden", "admin privilege required");
+}
+void requireProjectAccess(const Principal& p, const std::string& project) {
+    if (!p.canAccess(project))
+        throw ApiError(ErrCode::Forbidden, "forbidden", "not granted project '" + project + "'");
+}
+void requireProjectManage(const Principal& p, const std::string& project) {
+    requireProjectAccess(p, project);
+    if (p.scope)
+        throw ApiError(ErrCode::Forbidden, "forbidden", "scoped callers cannot manage collections");
+}
+
+void requireCapabilityCore(const Principal& p, const std::string& project,
+                           const std::string& collection, KeyOp op) {
+    requireProjectAccess(p, project);
+    if (!p.scope) return;                                   // unscoped: full access
+    const KeyScope& sc = *p.scope;
+    if (!sc.findRule(collection, op))
+        throw ApiError(ErrCode::Forbidden, "forbidden", "scope does not permit this operation");
+    if (!rateLimiter().allow(p.id, sc.rateLimitPerMin))
+        throw ApiError(ErrCode::TooManyRequests, "rate_limited", "rate limit exceeded");
 }
+
+// --- ApiKey forms: kept so no handler changes, and so the HTTP-only checks
+// --- (Origin, captcha) stay where a request actually exists.
+
+void requireAdmin(const ApiKey& k) { requireAdmin(Principal::of(k)); }
 void requireProjectAccess(const ApiKey& k, const std::string& project) {
+    // Message keeps saying "key" here: this form is only reached by a key holder.
     if (!k.canAccess(project))
         throw ApiError(ErrCode::Forbidden, "forbidden", "key not granted project '" + project + "'");
 }
@@ -47,18 +75,15 @@ void requireProjectManage(const ApiKey& k, const std::string& project) {
 
 void requireCapability(ServerDeps& d, const ApiKey& k, const httplib::Request& req,
                        const std::string& project, const std::string& collection, KeyOp op) {
-    requireProjectAccess(k, project);
+    // Grant, rule and rate limit are the caller-agnostic part.
+    requireCapabilityCore(Principal::of(k), project, collection, op);
     if (!k.scope) return;                                   // legacy full-access key
     const KeyScope& sc = *k.scope;
-    const KeyScopeRule* rule = sc.findRule(collection, op);
-    if (!rule)
-        throw ApiError(ErrCode::Forbidden, "forbidden", "key scope does not permit this operation");
+    const KeyScopeRule* rule = sc.findRule(collection, op);  // re-read for requireHumanToken
     std::string origin;
     if (auto it = req.headers.find("Origin"); it != req.headers.end()) origin = it->second;
     if (!sc.originAllowed(origin))
         throw ApiError(ErrCode::Forbidden, "forbidden", "origin not allowed for this key");
-    if (!rateLimiter().allow(k.id, sc.rateLimitPerMin))
-        throw ApiError(ErrCode::TooManyRequests, "rate_limited", "rate limit exceeded");
     if (rule->requireHumanToken) {
         std::string token;
         if (auto it = req.headers.find("X-Captcha-Token"); it != req.headers.end()) token = it->second;

+ 15 - 0
src/server.hpp

@@ -3,6 +3,7 @@
 #include "auth.hpp"
 #include "collection_registry.hpp"
 #include "db_gateway.hpp"
+#include "principal.hpp"
 #include "key_store.hpp"
 #include "settings_store.hpp"
 #include <httplib.h>
@@ -48,6 +49,20 @@ void   requireProjectManage(const ApiKey& k, const std::string& project);  // th
 void   requireCapability(ServerDeps& d, const ApiKey& k, const httplib::Request& req,
                          const std::string& project, const std::string& collection, KeyOp op);
 
+// The same checks expressed for any caller, not just a key holder. The ApiKey
+// forms above delegate here, and a server-side function - which has no key, no
+// origin and no captcha token - calls these directly, so both paths are
+// authorized by one implementation.
+void   requireAdmin(const Principal& p);
+void   requireProjectAccess(const Principal& p, const std::string& project);
+void   requireProjectManage(const Principal& p, const std::string& project);
+
+// Project grant + scope rule + rate limit. Everything that needs an HTTP
+// request (Origin allow-list, captcha) stays in the ApiKey overload above,
+// because those questions are meaningless for a cron or event-triggered run.
+void   requireCapabilityCore(const Principal& p, const std::string& project,
+                             const std::string& collection, KeyOp op);
+
 // Shared with handlers/relations.cpp; documents.cpp needs them for the 409 payload
 // on a relation-blocked delete.
 std::string unqualify(const std::string& project, const std::string& name);

+ 4 - 0
tests/CMakeLists.txt

@@ -77,3 +77,7 @@ gtest_discover_tests(test_project_settings)
 add_executable(test_outbound_http test_outbound_http.cpp)
 target_link_libraries(test_outbound_http PRIVATE vectorapi_core GTest::gtest_main)
 gtest_discover_tests(test_outbound_http)
+
+add_executable(test_principal test_principal.cpp)
+target_link_libraries(test_principal PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_principal)

+ 75 - 0
tests/test_principal.cpp

@@ -0,0 +1,75 @@
+#include <gtest/gtest.h>
+#include "apikey.hpp"
+#include "principal.hpp"
+using namespace svapi;
+
+namespace {
+ApiKey plainKey(std::vector<std::string> projects, bool admin = false) {
+    ApiKey k;
+    k.id = "key-1";
+    k.projects = std::move(projects);
+    k.admin = admin;
+    return k;
+}
+ApiKey scopedKey(std::vector<std::string> projects, KeyScope scope) {
+    ApiKey k = plainKey(std::move(projects));
+    k.scope = std::move(scope);
+    return k;
+}
+KeyScope readOnly(const std::string& collection) {
+    KeyScope s;
+    KeyScopeRule r;
+    r.collection = collection;
+    r.ops = {KeyOp::Read, KeyOp::List};
+    s.rules.push_back(r);
+    return s;
+}
+}  // namespace
+
+TEST(Principal, MirrorsTheKeyItWasBuiltFrom) {
+    const ApiKey k = plainKey({"acme"});
+    const Principal p = Principal::of(k);
+    EXPECT_EQ(p.id, "key-1");
+    EXPECT_FALSE(p.admin);
+    EXPECT_EQ(p.scope, nullptr) << "an unscoped key must present as unscoped";
+    EXPECT_TRUE(p.canAccess("acme"));
+    EXPECT_FALSE(p.canAccess("other"));
+}
+
+TEST(Principal, AdminAndWildcardReachEveryProject) {
+    EXPECT_TRUE(Principal::of(plainKey({}, /*admin*/ true)).canAccess("anything"));
+    EXPECT_TRUE(Principal::of(plainKey({"*"})).canAccess("anything"));
+}
+
+TEST(Principal, CarriesTheScopeByReference) {
+    const ApiKey k = scopedKey({"acme"}, readOnly("docs"));
+    const Principal p = Principal::of(k);
+    ASSERT_NE(p.scope, nullptr);
+    EXPECT_NE(p.scope->findRule("docs", KeyOp::Read), nullptr);
+    EXPECT_EQ(p.scope->findRule("docs", KeyOp::Delete), nullptr);
+}
+
+// A function is a principal with no key behind it: no secret, no origin, no
+// captcha - just a project and a scope. Constructing one directly is what lets
+// the runner reuse the same authorization code as an HTTP request.
+TEST(Principal, CanBeBuiltWithoutAnApiKey) {
+    const std::vector<std::string> projects{"acme"};
+    const KeyScope scope = readOnly("kb_chunks");
+    const Principal p{"fn:kb-search", &projects, false, &scope};
+    EXPECT_TRUE(p.canAccess("acme"));
+    EXPECT_FALSE(p.canAccess("other"));
+    ASSERT_NE(p.scope, nullptr);
+    EXPECT_NE(p.scope->findRule("kb_chunks", KeyOp::List), nullptr);
+}
+
+TEST(Principal, AccessChecksAgreeWithTheKeysOwnAnswer) {
+    // The two must never diverge: Principal is meant to be the single notion of
+    // "who is asking", not a second one that drifts.
+    for (const ApiKey& k : {plainKey({"acme"}), plainKey({"*"}), plainKey({}, true),
+                            scopedKey({"acme"}, readOnly("docs"))}) {
+        const Principal p = Principal::of(k);
+        for (const char* project : {"acme", "other", "default"})
+            EXPECT_EQ(p.canAccess(project), k.canAccess(project))
+                << "disagreement on project " << project;
+    }
+}