Explorar el Código

feat(functions): store functions with policy as server state

One document per function in <project>:vectorapi_functions. The field is
`function_id`, not `id`, because the database client strips a top-level
`id` from stored bodies - the same reason API keys store `key_id`.

The load-bearing rule is mergeForCodePush(): a code push can never widen
access. Policy is server state, set by an admin, so the merge takes the
policy from the stored row and never reads the one in the payload - not
unioned, not consulted as a fallback. A first registration inherits the
project default instead. `enabled` is server state for the same reason:
re-deploying must not quietly restart a function an operator turned off.

It is a pure function so the invariant is unit-tested directly rather
than inferred from handler behaviour, which is how the repo already
tests resolveEmbedding(). The pure half lives in function_record.hpp
with no database include, so it builds on the Void dev host.

Identity comes from the script's `on` block and `path` carries no
meaning, which is what makes a rename safe: moving kb-search.js to
lib/search/kb.js rewrites `path` and keeps the row, so the policy
travels with the function. A test pins that.

A function whose source stops compiling keeps its row, its policy and
gains last_error, so fixing a syntax error does not also mean
re-granting access.

builtinDefaultFunctionPolicy() currently grants nothing: unreviewed code
reaches no collection until someone says so. Marked TODO(policy) for
confirmation - it is the floor of the whole runtime.

21 tests.
fszontagh hace 1 mes
padre
commit
96c30ceeac

+ 2 - 0
src/CMakeLists.txt

@@ -13,6 +13,8 @@ add_library(vectorapi_core STATIC
     key_store.cpp
     settings_store.cpp
     collection_registry.cpp
+    function_record.cpp
+    function_registry.cpp
     embeddings.cpp
     embedding_cache.cpp
     rate_limiter.cpp

+ 94 - 0
src/function_record.cpp

@@ -0,0 +1,94 @@
+#include "function_record.hpp"
+#include <openssl/evp.h>
+#include <array>
+
+namespace svapi {
+
+std::string functionContentHash(const std::string& source) {
+    std::array<unsigned char, EVP_MAX_MD_SIZE> digest{};
+    unsigned int len = 0;
+    // EVP rather than the deprecated SHA256() one-shot: OpenSSL 3 marks the
+    // legacy low-level calls deprecated and the build turns warnings into noise.
+    EVP_MD_CTX* ctx = EVP_MD_CTX_new();
+    if (ctx == nullptr) return {};
+    if (EVP_DigestInit_ex(ctx, EVP_sha256(), nullptr) == 1 &&
+        EVP_DigestUpdate(ctx, source.data(), source.size()) == 1) {
+        EVP_DigestFinal_ex(ctx, digest.data(), &len);
+    }
+    EVP_MD_CTX_free(ctx);
+
+    static const char* kHex = "0123456789abcdef";
+    std::string out;
+    out.reserve(static_cast<std::size_t>(len) * 2);
+    for (unsigned int i = 0; i < len; ++i) {
+        out.push_back(kHex[digest[i] >> 4]);
+        out.push_back(kHex[digest[i] & 0x0f]);
+    }
+    return out;
+}
+
+KeyScope builtinDefaultFunctionPolicy() {
+    // Deny everything. A function with no rules can run, log and call out
+    // through ctx.fetch, but it cannot touch a single collection until someone
+    // grants it one. The failure mode of the alternative is silent: a function
+    // that quietly reads data nobody meant to expose looks exactly like a
+    // function that works.
+    return KeyScope{};
+}
+
+FunctionRecord FunctionRecord::fromJson(const nlohmann::json& j) {
+    FunctionRecord f;
+    f.functionId  = j.value("function_id", "");
+    f.path        = j.value("path", "");
+    f.source      = j.value("source", "");
+    f.contentHash = j.value("content_hash", "");
+    if (j.contains("descriptor") && j.at("descriptor").is_object()) f.descriptor = j.at("descriptor");
+    // An absent policy grants nothing. Defaulting to anything else would mean a
+    // truncated or hand-edited row silently widens what a function may touch.
+    if (j.contains("policy") && j.at("policy").is_object()) f.policy = KeyScope::fromJson(j.at("policy"));
+    f.enabled   = j.value("enabled", true);
+    f.valid     = j.value("valid", true);
+    f.lastError = j.value("last_error", "");
+    f.createdAt = j.value("created_at", 0ull);
+    f.updatedAt = j.value("updated_at", 0ull);
+    return f;
+}
+
+nlohmann::json FunctionRecord::toJson() const {
+    nlohmann::json j = toSummaryJson();
+    j["source"] = source;
+    return j;
+}
+
+nlohmann::json FunctionRecord::toSummaryJson() const {
+    // `function_id`, never `id`: the database client strips a top-level `id`
+    // from stored bodies, which would leave the row with no identity.
+    return {{"function_id", functionId},
+            {"path", path},
+            {"content_hash", contentHash},
+            {"descriptor", descriptor},
+            {"policy", policy.toJson()},
+            {"enabled", enabled},
+            {"valid", valid},
+            {"last_error", lastError},
+            {"created_at", createdAt},
+            {"updated_at", updatedAt}};
+}
+
+FunctionRecord mergeForCodePush(const FunctionRecord* existing, FunctionRecord incoming,
+                                const KeyScope& projectDefault) {
+    // Code and trigger declaration come from the push; identity, policy and
+    // operator state come from the server. `incoming.policy` is deliberately
+    // never read - not unioned, not consulted as a fallback - so there is no
+    // path by which pushing code changes what the code may reach.
+    if (existing == nullptr) {
+        incoming.policy = projectDefault;
+        return incoming;
+    }
+    incoming.policy    = existing->policy;
+    incoming.enabled   = existing->enabled;
+    incoming.createdAt = existing->createdAt;
+    return incoming;
+}
+
+} // namespace svapi

+ 86 - 0
src/function_record.hpp

@@ -0,0 +1,86 @@
+#pragma once
+#include "apikey.hpp"
+#include <nlohmann/json.hpp>
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace svapi {
+
+/// One stored function: its code, its trigger declaration, and the policy that
+/// says what it may touch.
+///
+/// `functionId` is declared in the script's `on` block and is the row's
+/// identity; `path` is where the author happened to keep the file and carries
+/// no meaning. That is what makes a rename safe: moving kb-search.js to
+/// lib/search.js rewrites `path` and keeps the same row, so the policy an admin
+/// granted travels with the function instead of being silently reset.
+///
+/// Stored as one document per function in the project's
+/// `vectorapi_functions` collection under `functionId`. The field is
+/// `function_id`, not
+/// `id`, because the database client strips a top-level `id` from stored bodies
+/// (the same reason API keys store `key_id`).
+struct FunctionRecord {
+    std::string functionId;
+    std::string path;
+    std::string source;
+    std::string contentHash;
+    /// The validated `on` block, as functions::FunctionDescriptor::toJson().
+    /// Held as JSON so this header stays independent of the runner's parser.
+    nlohmann::json descriptor = nlohmann::json::object();
+    /// What the function may do, in exactly the vocabulary API keys already use.
+    /// A function is a principal, not a key holder: same questions, same answers,
+    /// one implementation.
+    KeyScope policy;
+    bool enabled = true;
+    /// False when the last push failed to compile, or when the runner rejected
+    /// the `on` block. An invalid function keeps its row, and its policy.
+    bool valid = true;
+    std::string lastError;
+    uint64_t createdAt = 0;
+    uint64_t updatedAt = 0;
+
+    static FunctionRecord fromJson(const nlohmann::json& j);
+    /// Full form, for storage.
+    nlohmann::json toJson() const;
+    /// Without `source`, for list responses - a registry listing should not
+    /// ship every function's whole body.
+    nlohmann::json toSummaryJson() const;
+};
+
+/// Combine an incoming code push with whatever is already stored.
+///
+/// THE RULE: pushing code can never widen access. Policy is server state, set
+/// by an admin, so this function takes the policy from `existing` and ignores
+/// anything the push claimed. A first registration - `existing == nullptr` -
+/// inherits `projectDefault` instead.
+///
+/// Everything else (source, hash, descriptor, path, validity) comes from the
+/// push. `enabled` is likewise server state: re-pushing code must not silently
+/// re-enable a function an operator deliberately turned off.
+///
+/// Pure, so the invariant is unit-tested here rather than inferred from handler
+/// behaviour.
+FunctionRecord mergeForCodePush(const FunctionRecord* existing, FunctionRecord incoming,
+                                const KeyScope& projectDefault);
+
+/// The policy a FIRST registration inherits when the project has not configured
+/// its own `default_function_policy`.
+///
+/// This is the floor of the whole function runtime: whatever it returns is what
+/// code reaches production with before any admin has looked at it. It therefore
+/// errs toward nothing - an author who needs access asks for it, and the grant
+/// is visible in the registry row.
+///
+/// TODO(policy): confirm this posture. Alternatives, in increasing convenience
+/// and decreasing safety: read+list on every collection (a function can always
+/// read its project's data), read+list on a configured prefix, or full access
+/// within the project. See the note in handlers/functions.cpp when that lands.
+KeyScope builtinDefaultFunctionPolicy();
+
+/// sha256 of `source`, lower-case hex. The runner caches compiled bytecode by
+/// this, so it must change whenever a byte of the source does.
+std::string functionContentHash(const std::string& source);
+
+} // namespace svapi

+ 73 - 0
src/function_registry.cpp

@@ -0,0 +1,73 @@
+#include "function_registry.hpp"
+#include <ctime>
+
+namespace svapi {
+namespace {
+uint64_t nowSec() { return static_cast<uint64_t>(std::time(nullptr)); }
+} // namespace
+
+FunctionRegistry::FunctionRegistry(DbGateway& db) : db_(db) {}
+
+void FunctionRegistry::ensure(const std::string& project) {
+    const std::string c = coll(project);
+    if (!db_.client().getCollectionInfo(c).has_value())
+        db_.client().createCollection(c, 0, false, 0, 0);
+}
+
+void FunctionRegistry::bootstrap(const std::vector<std::string>& projects) {
+    for (const auto& p : projects) ensure(p);
+}
+
+std::optional<FunctionRecord> FunctionRegistry::get(const std::string& project,
+                                                    const std::string& functionId) {
+    if (auto doc = db_.client().get(coll(project), functionId))
+        return FunctionRecord::fromJson(*doc);
+    return std::nullopt;
+}
+
+std::vector<FunctionRecord> FunctionRegistry::list(const std::string& project) {
+    std::vector<FunctionRecord> out;
+    smartbotic::database::Client::QueryOptions opts;
+    opts.limit = 100000;
+    for (const auto& doc : db_.client().find(coll(project), opts))
+        out.push_back(FunctionRecord::fromJson(doc));
+    return out;
+}
+
+FunctionRecord FunctionRegistry::put(const std::string& project, const FunctionRecord& incoming,
+                                     const KeyScope& projectDefault) {
+    ensure(project);
+    const std::optional<FunctionRecord> existing = get(project, incoming.functionId);
+    FunctionRecord row =
+        mergeForCodePush(existing ? &*existing : nullptr, incoming, projectDefault);
+    if (row.createdAt == 0) row.createdAt = nowSec();
+    row.updatedAt = nowSec();
+    db_.client().upsert(coll(project), row.toJson(), row.functionId);
+    return row;
+}
+
+bool FunctionRegistry::setPolicy(const std::string& project, const std::string& functionId,
+                                 const KeyScope& policy) {
+    std::optional<FunctionRecord> row = get(project, functionId);
+    if (!row) return false;
+    row->policy = policy;
+    row->updatedAt = nowSec();
+    db_.client().upsert(coll(project), row->toJson(), functionId);
+    return true;
+}
+
+bool FunctionRegistry::setEnabled(const std::string& project, const std::string& functionId,
+                                  bool enabled) {
+    std::optional<FunctionRecord> row = get(project, functionId);
+    if (!row) return false;
+    row->enabled = enabled;
+    row->updatedAt = nowSec();
+    db_.client().upsert(coll(project), row->toJson(), functionId);
+    return true;
+}
+
+bool FunctionRegistry::remove(const std::string& project, const std::string& functionId) {
+    return db_.client().remove(coll(project), functionId);
+}
+
+} // namespace svapi

+ 49 - 0
src/function_registry.hpp

@@ -0,0 +1,49 @@
+#pragma once
+#include "db_gateway.hpp"
+#include "function_record.hpp"
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace svapi {
+
+/// Project-scoped function registry.
+class FunctionRegistry {
+public:
+    explicit FunctionRegistry(DbGateway& db);
+
+    /// Ensure the registry collection for `project` exists (idempotent).
+    void ensure(const std::string& project);
+
+    /// Re-open every project's function collection. The database only surfaces
+    /// a collection through find()/list() once it has been opened in the current
+    /// process, so without this a restart leaves every registry invisible even
+    /// though the data survives (same reason CollectionRegistry::bootstrap
+    /// exists).
+    void bootstrap(const std::vector<std::string>& projects);
+
+    std::optional<FunctionRecord> get(const std::string& project, const std::string& functionId);
+    std::vector<FunctionRecord> list(const std::string& project);
+
+    /// Store a code push, preserving server-held policy via mergeForCodePush.
+    /// Returns the record as stored.
+    FunctionRecord put(const std::string& project, const FunctionRecord& incoming,
+                       const KeyScope& projectDefault);
+
+    /// Replace a function's policy. Admin-only at the HTTP layer; this is the
+    /// only way a policy ever changes.
+    bool setPolicy(const std::string& project, const std::string& functionId,
+                   const KeyScope& policy);
+
+    bool setEnabled(const std::string& project, const std::string& functionId, bool enabled);
+
+    bool remove(const std::string& project, const std::string& functionId);
+
+private:
+    DbGateway& db_;
+    std::string coll(const std::string& project) const {
+        return qualify(project, "vectorapi_functions");
+    }
+};
+
+} // namespace svapi

+ 11 - 0
tests/CMakeLists.txt

@@ -100,3 +100,14 @@ add_executable(test_functions_net_guard
 target_include_directories(test_functions_net_guard PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_functions_net_guard PRIVATE GTest::gtest_main)
 gtest_discover_tests(test_functions_net_guard)
+
+# Pure half of the function registry (record shape + the code-push merge rule);
+# no database client, so it builds on the Void dev host too.
+add_executable(test_function_record
+    test_function_record.cpp
+    ${CMAKE_SOURCE_DIR}/src/function_record.cpp
+    ${CMAKE_SOURCE_DIR}/src/apikey.cpp)
+target_include_directories(test_function_record PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_function_record PRIVATE
+    nlohmann_json::nlohmann_json OpenSSL::Crypto GTest::gtest_main)
+gtest_discover_tests(test_function_record)

+ 251 - 0
tests/test_function_record.cpp

@@ -0,0 +1,251 @@
+#include <gtest/gtest.h>
+#include "function_record.hpp"
+using namespace svapi;
+
+namespace {
+
+KeyScope scopeWith(const std::string& collection, std::set<KeyOp> ops,
+                   uint32_t rateLimit = 0) {
+    KeyScope s;
+    KeyScopeRule r;
+    r.collection = collection;
+    r.ops = std::move(ops);
+    s.rules.push_back(r);
+    s.rateLimitPerMin = rateLimit;
+    return s;
+}
+
+FunctionRecord stored(const std::string& id, KeyScope policy) {
+    FunctionRecord f;
+    f.functionId = id;
+    f.path = "functions/" + id + ".js";
+    f.source = "export default () => 1";
+    f.contentHash = functionContentHash(f.source);
+    f.descriptor = {{"id", id}, {"type", "http"}, {"route", "/" + id}};
+    f.policy = std::move(policy);
+    f.enabled = true;
+    f.valid = true;
+    f.createdAt = 1000;
+    f.updatedAt = 1000;
+    return f;
+}
+
+/// Does `policy` let `op` through on `collection`?
+bool allows(const KeyScope& policy, const std::string& collection, KeyOp op) {
+    return policy.findRule(collection, op) != nullptr;
+}
+
+} // namespace
+
+// ----------------------------------------------------------- content hash
+
+TEST(FunctionContentHash, IsStableAndLowerCaseHex) {
+    const std::string h = functionContentHash("export default () => 1");
+    EXPECT_EQ(h.size(), 64u) << "sha256 hex is 64 characters";
+    EXPECT_EQ(h, functionContentHash("export default () => 1"));
+    for (const char c : h)
+        EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) << "not lower-case hex: " << c;
+}
+
+TEST(FunctionContentHash, ChangesWhenASingleByteChanges) {
+    // The runner caches compiled bytecode by this hash. A collision between two
+    // different sources would run yesterday's code.
+    EXPECT_NE(functionContentHash("a"), functionContentHash("b"));
+    EXPECT_NE(functionContentHash("return 1"), functionContentHash("return 1 "));
+}
+
+TEST(FunctionContentHash, HandlesEmptySource) {
+    EXPECT_EQ(functionContentHash("").size(), 64u);
+}
+
+// ------------------------------------------------------------ JSON shape
+
+TEST(FunctionRecord, RoundTripsThroughJson) {
+    const FunctionRecord in = stored("kb-search", scopeWith("kb_chunks", {KeyOp::Read, KeyOp::List}, 60));
+    const FunctionRecord out = FunctionRecord::fromJson(in.toJson());
+
+    EXPECT_EQ(out.functionId, in.functionId);
+    EXPECT_EQ(out.path, in.path);
+    EXPECT_EQ(out.source, in.source);
+    EXPECT_EQ(out.contentHash, in.contentHash);
+    EXPECT_EQ(out.descriptor, in.descriptor);
+    EXPECT_EQ(out.enabled, in.enabled);
+    EXPECT_EQ(out.valid, in.valid);
+    EXPECT_EQ(out.createdAt, in.createdAt);
+    EXPECT_EQ(out.updatedAt, in.updatedAt);
+    EXPECT_TRUE(allows(out.policy, "kb_chunks", KeyOp::Read));
+    EXPECT_FALSE(allows(out.policy, "kb_chunks", KeyOp::Delete));
+    EXPECT_EQ(out.policy.rateLimitPerMin, 60u);
+}
+
+TEST(FunctionRecord, StoresIdentityAsFunctionIdNotId) {
+    // The database client strips a top-level `id` from stored bodies, so a
+    // record keyed on `id` would come back with no identity at all.
+    const nlohmann::json j = stored("kb-search", KeyScope{}).toJson();
+    EXPECT_TRUE(j.contains("function_id"));
+    EXPECT_EQ(j.at("function_id"), "kb-search");
+    EXPECT_FALSE(j.contains("id")) << "a top-level id would be stripped by the DB client";
+}
+
+TEST(FunctionRecord, SummaryOmitsTheSourceButKeepsTheHash) {
+    // Listing every function should not ship every function's whole body; the
+    // hash is what a client needs to tell whether its copy is current.
+    const nlohmann::json j = stored("kb-search", KeyScope{}).toSummaryJson();
+    EXPECT_FALSE(j.contains("source"));
+    EXPECT_TRUE(j.contains("content_hash"));
+    EXPECT_EQ(j.at("function_id"), "kb-search");
+}
+
+TEST(FunctionRecord, MissingFieldsParseToSafeDefaults) {
+    const FunctionRecord f = FunctionRecord::fromJson(nlohmann::json::object());
+    EXPECT_TRUE(f.functionId.empty());
+    EXPECT_TRUE(f.policy.rules.empty()) << "an absent policy must grant nothing";
+    EXPECT_TRUE(f.descriptor.is_object());
+}
+
+// --------------------------------------------- the code-push merge rule
+
+TEST(MergeForCodePush, FirstRegistrationInheritsTheProjectDefault) {
+    const KeyScope projectDefault = scopeWith("kb_*", {KeyOp::Read, KeyOp::List});
+    FunctionRecord incoming = stored("kb-search", KeyScope{});
+
+    const FunctionRecord out = mergeForCodePush(nullptr, incoming, projectDefault);
+
+    EXPECT_TRUE(allows(out.policy, "kb_chunks", KeyOp::Read));
+    EXPECT_FALSE(allows(out.policy, "kb_chunks", KeyOp::Delete));
+}
+
+TEST(MergeForCodePush, APushCannotWidenItsOwnPolicy) {
+    // The whole point. A function author pushing code is not an admin, so a
+    // policy in the payload is ignored - never merged, never unioned.
+    const FunctionRecord existing = stored("kb-search", scopeWith("kb_chunks", {KeyOp::Read}));
+    FunctionRecord incoming = stored("kb-search", scopeWith("*", {KeyOp::Read, KeyOp::Insert,
+                                                                  KeyOp::Update, KeyOp::Delete}));
+
+    const FunctionRecord out = mergeForCodePush(&existing, incoming, KeyScope{});
+
+    EXPECT_TRUE(allows(out.policy, "kb_chunks", KeyOp::Read));
+    EXPECT_FALSE(allows(out.policy, "kb_chunks", KeyOp::Delete)) << "the push widened its policy";
+    EXPECT_FALSE(allows(out.policy, "secrets", KeyOp::Read)) << "the push reached a new collection";
+}
+
+TEST(MergeForCodePush, APushCannotNarrowOrClearItsPolicyEither) {
+    // Not a security hole, but the same rule: policy is server state. A push
+    // carrying an empty policy must not wipe what an admin granted, or every
+    // deploy from a client that omits the field would silently break the
+    // function.
+    const FunctionRecord existing = stored("kb-search", scopeWith("kb_chunks", {KeyOp::Read}));
+    FunctionRecord incoming = stored("kb-search", KeyScope{});
+
+    const FunctionRecord out = mergeForCodePush(&existing, incoming, KeyScope{});
+
+    EXPECT_TRUE(allows(out.policy, "kb_chunks", KeyOp::Read));
+}
+
+TEST(MergeForCodePush, FirstRegistrationIgnoresAClaimedPolicyToo) {
+    // A first push must not be able to grant itself anything by arriving with a
+    // policy before any admin has looked at it.
+    FunctionRecord incoming = stored("kb-search", scopeWith("*", {KeyOp::Delete}));
+
+    const FunctionRecord out = mergeForCodePush(nullptr, incoming, scopeWith("kb_*", {KeyOp::Read}));
+
+    EXPECT_FALSE(allows(out.policy, "anything", KeyOp::Delete));
+    EXPECT_TRUE(allows(out.policy, "kb_chunks", KeyOp::Read));
+}
+
+TEST(MergeForCodePush, CodeAndDescriptorComeFromThePush) {
+    const FunctionRecord existing = stored("kb-search", scopeWith("kb_chunks", {KeyOp::Read}));
+    FunctionRecord incoming = stored("kb-search", KeyScope{});
+    incoming.source = "export default () => 2";
+    incoming.contentHash = functionContentHash(incoming.source);
+    incoming.descriptor = {{"id", "kb-search"}, {"type", "http"}, {"route", "/kb/v2"}};
+
+    const FunctionRecord out = mergeForCodePush(&existing, incoming, KeyScope{});
+
+    EXPECT_EQ(out.source, "export default () => 2");
+    EXPECT_EQ(out.contentHash, functionContentHash("export default () => 2"));
+    EXPECT_EQ(out.descriptor.at("route"), "/kb/v2");
+}
+
+TEST(MergeForCodePush, ARenameKeepsThePolicyAndMovesThePath) {
+    // Identity lives in the script's `on` block, so moving the file changes
+    // `path` and nothing else. If policy were keyed on the path, every rename
+    // would silently reset a function's privileges.
+    const FunctionRecord existing = stored("kb-search", scopeWith("kb_chunks", {KeyOp::Read}));
+    FunctionRecord incoming = stored("kb-search", KeyScope{});
+    incoming.path = "lib/search/kb.js";
+
+    const FunctionRecord out = mergeForCodePush(&existing, incoming, KeyScope{});
+
+    EXPECT_EQ(out.path, "lib/search/kb.js");
+    EXPECT_EQ(out.functionId, "kb-search");
+    EXPECT_TRUE(allows(out.policy, "kb_chunks", KeyOp::Read)) << "a rename dropped the policy";
+}
+
+TEST(MergeForCodePush, ADisabledFunctionStaysDisabledAcrossAPush) {
+    // An operator turned this off, probably because it was misbehaving.
+    // Re-deploying must not quietly start it again.
+    FunctionRecord existing = stored("kb-search", KeyScope{});
+    existing.enabled = false;
+    FunctionRecord incoming = stored("kb-search", KeyScope{});
+    incoming.enabled = true;
+
+    EXPECT_FALSE(mergeForCodePush(&existing, incoming, KeyScope{}).enabled);
+}
+
+TEST(MergeForCodePush, PreservesTheOriginalCreationTime) {
+    const FunctionRecord existing = stored("kb-search", KeyScope{});
+    FunctionRecord incoming = stored("kb-search", KeyScope{});
+    incoming.createdAt = 9999;
+
+    const FunctionRecord out = mergeForCodePush(&existing, incoming, KeyScope{});
+    EXPECT_EQ(out.createdAt, 1000u) << "created_at belongs to the first registration";
+}
+
+TEST(MergeForCodePush, AFailedPushMarksTheRowInvalidWithoutLosingThePolicy) {
+    // A function whose source no longer compiles keeps its row and its policy,
+    // so fixing the syntax error does not also mean re-granting access.
+    const FunctionRecord existing = stored("kb-search", scopeWith("kb_chunks", {KeyOp::Read}));
+    FunctionRecord incoming = stored("kb-search", KeyScope{});
+    incoming.valid = false;
+    incoming.lastError = "SyntaxError: unexpected token";
+
+    const FunctionRecord out = mergeForCodePush(&existing, incoming, KeyScope{});
+
+    EXPECT_FALSE(out.valid);
+    EXPECT_EQ(out.lastError, "SyntaxError: unexpected token");
+    EXPECT_TRUE(allows(out.policy, "kb_chunks", KeyOp::Read));
+}
+
+TEST(MergeForCodePush, ASuccessfulPushClearsAPreviousError) {
+    FunctionRecord existing = stored("kb-search", KeyScope{});
+    existing.valid = false;
+    existing.lastError = "SyntaxError: unexpected token";
+    FunctionRecord incoming = stored("kb-search", KeyScope{});
+
+    const FunctionRecord out = mergeForCodePush(&existing, incoming, KeyScope{});
+
+    EXPECT_TRUE(out.valid);
+    EXPECT_TRUE(out.lastError.empty()) << "a stale error would be reported forever";
+}
+
+// ------------------------------------------------------- the default floor
+
+TEST(BuiltinDefaultFunctionPolicy, GrantsNoCollectionAccess) {
+    // Whatever this policy is, it is what unreviewed code runs with. If the
+    // posture is ever widened, widen it here and this test says so out loud
+    // rather than the change passing unnoticed.
+    const KeyScope p = builtinDefaultFunctionPolicy();
+    EXPECT_TRUE(p.rules.empty());
+    for (const KeyOp op : {KeyOp::Read, KeyOp::List, KeyOp::Search, KeyOp::Insert,
+                           KeyOp::Update, KeyOp::Delete})
+        EXPECT_EQ(p.findRule("any_collection", op), nullptr);
+}
+
+TEST(MergeForCodePush, AProjectWithNoConfiguredDefaultGrantsNothing) {
+    FunctionRecord incoming;
+    incoming.functionId = "kb-search";
+    const FunctionRecord out =
+        mergeForCodePush(nullptr, incoming, builtinDefaultFunctionPolicy());
+    EXPECT_TRUE(out.policy.rules.empty());
+}