#include #include "apikey.hpp" using namespace svapi; TEST(KeyOp, StringRoundTrip) { EXPECT_EQ(keyOpToString(KeyOp::Search), "search"); EXPECT_EQ(*keyOpFromString("insert"), KeyOp::Insert); EXPECT_FALSE(keyOpFromString("bogus").has_value()); } TEST(KeyScope, ExactAndGlobRuleMatch) { KeyScope s; s.rules.push_back({"catalog_*", {KeyOp::Read, KeyOp::List}, false}); s.rules.push_back({"quotes", {KeyOp::Insert}, false}); EXPECT_NE(s.findRule("catalog_doors", KeyOp::Read), nullptr); EXPECT_EQ(s.findRule("catalog_doors", KeyOp::Insert), nullptr); EXPECT_NE(s.findRule("quotes", KeyOp::Insert), nullptr); EXPECT_EQ(s.findRule("designs", KeyOp::Read), nullptr); EXPECT_EQ(s.findRule("catalogX", KeyOp::Read), nullptr); } TEST(KeyScope, OriginAllowlist) { KeyScope s; EXPECT_TRUE(s.originAllowed("https://anything")); s.origins = {"https://konfig.megatoloajto.hu"}; EXPECT_TRUE(s.originAllowed("https://konfig.megatoloajto.hu")); EXPECT_FALSE(s.originAllowed("https://evil.example")); EXPECT_FALSE(s.originAllowed("")); } TEST(KeyScope, Expiry) { KeyScope s; EXPECT_FALSE(s.expired(1000)); s.expiresAt = 500; EXPECT_TRUE(s.expired(1000)); EXPECT_FALSE(s.expired(499)); } TEST(ApiKey, ScopeRoundTripsThroughJson) { ApiKey k; k.id = "k1"; k.key = "secretvalue"; k.projects = {"megatoloajto"}; KeyScope s; s.rules.push_back({"quotes", {KeyOp::Insert}, true}); s.origins = {"https://x"}; s.rateLimitPerMin = 120; s.expiresAt = 0; k.scope = s; ApiKey back = ApiKey::fromJson(k.toJson()); ASSERT_TRUE(back.scope.has_value()); ASSERT_NE(back.scope->findRule("quotes", KeyOp::Insert), nullptr); EXPECT_TRUE(back.scope->findRule("quotes", KeyOp::Insert)->requireHumanToken); EXPECT_EQ(back.scope->rateLimitPerMin, 120u); auto pub = k.toPublicJson(); EXPECT_TRUE(pub.contains("scope")); EXPECT_FALSE(pub.contains("key")); } TEST(ApiKey, NoScopeStaysAbsent) { ApiKey k; k.id = "k2"; EXPECT_FALSE(ApiKey::fromJson(k.toJson()).scope.has_value()); EXPECT_FALSE(k.toPublicJson().contains("scope")); } // --- a wildcard must not reach a RESERVED pseudo-collection ---------------- TEST(KeyScopeReserved, AStarRuleDoesNotGrantTheFilesPseudoCollection) { // `collMatches("*", x)` is a zero-length prefix comparison, so before this // a `*` rule matched the reserved `_files` as well as every real // collection. Nobody writing `*` means "and the reserved names too", and // the docs describe `_files` as something a policy NAMES. // // Checked against production before changing it: none of the 7 keys there // holds a `*` rule, so nothing loses access. svapi::KeyScope scope; scope.rules.push_back({"*", {svapi::KeyOp::Read, svapi::KeyOp::List}, false}); EXPECT_EQ(scope.findRule("_files", svapi::KeyOp::Read), nullptr) << "a wildcard must not confer file access implicitly"; // The pair that makes the assertion above mean something: `*` must still // match a real collection, or this test would pass against a function that // matched nothing at all. EXPECT_NE(scope.findRule("kb_chunks", svapi::KeyOp::Read), nullptr) << "`*` must still mean every REAL collection"; } TEST(KeyScopeReserved, AnExplicitFilesRuleStillWorks) { // The other direction: naming it must keep working, or the feature is gone // rather than narrowed. svapi::KeyScope scope; scope.rules.push_back({"_files", {svapi::KeyOp::Read}, false}); EXPECT_NE(scope.findRule("_files", svapi::KeyOp::Read), nullptr); EXPECT_EQ(scope.findRule("_files", svapi::KeyOp::Insert), nullptr) << "ops are still honoured on a reserved name"; } TEST(KeyScopeReserved, APrefixWildcardDoesNotReachUnderscoreNamesEither) { // Not just the bare `*`: any trailing-wildcard pattern must stop at a // reserved name. `_*` is the one someone would reach for to grant "all the // internal things", and it must not work by accident. for (const char* pat : {"*", "_*", "_f*", "_files*"}) { svapi::KeyScope scope; scope.rules.push_back({pat, {svapi::KeyOp::Read}, false}); EXPECT_EQ(scope.findRule("_files", svapi::KeyOp::Read), nullptr) << "pattern " << pat; } } TEST(KeyScopeReserved, ThisIsWhyItMattersForAnythingAddedLater) { // A reserved name reachable by wildcard is harmless while it only widens a // read. It stops being harmless for a grant that lets a function ACT - a // mail connection, say. Asserting the rule generally, with a name that // does not exist yet, so the precedent cannot be re-broken by whoever adds // the next reserved prefix. svapi::KeyScope scope; scope.rules.push_back({"*", {svapi::KeyOp::Read, svapi::KeyOp::Insert}, false}); EXPECT_EQ(scope.findRule("_conn:some_mailbox", svapi::KeyOp::Insert), nullptr) << "a future reserved prefix must inherit the literal-grant rule automatically"; } // ─── A READ-MODIFY-WRITE CLIENT MUST NOT BE ABLE TO LOSE A FIELD ────────── // // The function policy route is a full REPLACE, so the web UI reads a policy, // edits one control and sends the whole thing back. Every field `fromJson` // understands therefore has to appear in `toJson`, or the client cannot // return what it was given and the save silently resets it to a default. // // This was NOT hypothetical. `pages/Functions.tsx` built its policy object // from a literal of four fields, so saving an unrelated control wiped // `ip_allow` - an address allow-list removed by editing a rate limit, with a // success toast. The UI now spreads what it loaded; this test is what stops // the next field being added to the parser and not to the emitter, which is // the half a UI fix cannot protect. TEST(KeyScopeRoundTrip, EveryFieldFromJsonReadsIsAlsoEmittedByToJson) { svapi::KeyScope s; s.rules.push_back({"c", {svapi::KeyOp::Read}, false}); s.origins = {"https://example.test"}; s.ipAllow = {"203.0.113.0/24"}; s.allowSameOriginHost = true; s.rateLimitPerMin = 60; s.rateLimitPerCallerPerMin = 5; s.expiresAt = 1790000000ull; // The trip a read-modify-write client makes, with NO edit at all: whatever // comes out must go back in unchanged. const svapi::KeyScope back = svapi::KeyScope::fromJson(s.toJson()); EXPECT_EQ(back.rules.size(), 1u); EXPECT_EQ(back.origins, s.origins); EXPECT_EQ(back.ipAllow, s.ipAllow) << "an allow-list lost here is a security control " "removed by an unrelated edit"; EXPECT_EQ(back.allowSameOriginHost, s.allowSameOriginHost); EXPECT_EQ(back.rateLimitPerMin, s.rateLimitPerMin); EXPECT_EQ(back.rateLimitPerCallerPerMin, s.rateLimitPerCallerPerMin); EXPECT_EQ(back.expiresAt, s.expiresAt); } // THE PAIRING, naming the fields explicitly. The test above would still pass // if a field were dropped from BOTH sides at once, which is exactly what // happens when someone "tidies up" an unused member - so assert the key is // actually present in the wire shape rather than only that a round trip // agrees with itself. TEST(KeyScopeRoundTrip, TheWireShapeNamesEveryFieldEvenAtItsDefault) { const nlohmann::json j = svapi::KeyScope{}.toJson(); for (const char* k : {"rules", "origins", "ip_allow", "allow_same_origin_host", "rate_limit_per_min", "rate_limit_per_caller_per_min", "expires_at"}) { EXPECT_TRUE(j.contains(k)) << k << " is absent from the wire shape, so a client that reads a policy " "and sends it back cannot preserve it"; } }