#include #include "apikey.hpp" #include "principal.hpp" using namespace svapi; namespace { ApiKey plainKey(std::vector projects, bool admin = false) { ApiKey k; k.id = "key-1"; k.projects = std::move(projects); k.admin = admin; return k; } ApiKey scopedKey(std::vector 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 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; } }