test_apikey.cpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. #include <gtest/gtest.h>
  2. #include "apikey.hpp"
  3. using namespace svapi;
  4. TEST(KeyOp, StringRoundTrip) {
  5. EXPECT_EQ(keyOpToString(KeyOp::Search), "search");
  6. EXPECT_EQ(*keyOpFromString("insert"), KeyOp::Insert);
  7. EXPECT_FALSE(keyOpFromString("bogus").has_value());
  8. }
  9. TEST(KeyScope, ExactAndGlobRuleMatch) {
  10. KeyScope s;
  11. s.rules.push_back({"catalog_*", {KeyOp::Read, KeyOp::List}, false});
  12. s.rules.push_back({"quotes", {KeyOp::Insert}, false});
  13. EXPECT_NE(s.findRule("catalog_doors", KeyOp::Read), nullptr);
  14. EXPECT_EQ(s.findRule("catalog_doors", KeyOp::Insert), nullptr);
  15. EXPECT_NE(s.findRule("quotes", KeyOp::Insert), nullptr);
  16. EXPECT_EQ(s.findRule("designs", KeyOp::Read), nullptr);
  17. EXPECT_EQ(s.findRule("catalogX", KeyOp::Read), nullptr);
  18. }
  19. TEST(KeyScope, OriginAllowlist) {
  20. KeyScope s; EXPECT_TRUE(s.originAllowed("https://anything"));
  21. s.origins = {"https://konfig.megatoloajto.hu"};
  22. EXPECT_TRUE(s.originAllowed("https://konfig.megatoloajto.hu"));
  23. EXPECT_FALSE(s.originAllowed("https://evil.example"));
  24. EXPECT_FALSE(s.originAllowed(""));
  25. }
  26. TEST(KeyScope, Expiry) {
  27. KeyScope s; EXPECT_FALSE(s.expired(1000));
  28. s.expiresAt = 500; EXPECT_TRUE(s.expired(1000)); EXPECT_FALSE(s.expired(499));
  29. }
  30. TEST(ApiKey, ScopeRoundTripsThroughJson) {
  31. ApiKey k; k.id = "k1"; k.key = "secretvalue"; k.projects = {"megatoloajto"};
  32. KeyScope s; s.rules.push_back({"quotes", {KeyOp::Insert}, true});
  33. s.origins = {"https://x"}; s.rateLimitPerMin = 120; s.expiresAt = 0;
  34. k.scope = s;
  35. ApiKey back = ApiKey::fromJson(k.toJson());
  36. ASSERT_TRUE(back.scope.has_value());
  37. ASSERT_NE(back.scope->findRule("quotes", KeyOp::Insert), nullptr);
  38. EXPECT_TRUE(back.scope->findRule("quotes", KeyOp::Insert)->requireHumanToken);
  39. EXPECT_EQ(back.scope->rateLimitPerMin, 120u);
  40. auto pub = k.toPublicJson();
  41. EXPECT_TRUE(pub.contains("scope"));
  42. EXPECT_FALSE(pub.contains("key"));
  43. }
  44. TEST(ApiKey, NoScopeStaysAbsent) {
  45. ApiKey k; k.id = "k2";
  46. EXPECT_FALSE(ApiKey::fromJson(k.toJson()).scope.has_value());
  47. EXPECT_FALSE(k.toPublicJson().contains("scope"));
  48. }
  49. // --- a wildcard must not reach a RESERVED pseudo-collection ----------------
  50. TEST(KeyScopeReserved, AStarRuleDoesNotGrantTheFilesPseudoCollection) {
  51. // `collMatches("*", x)` is a zero-length prefix comparison, so before this
  52. // a `*` rule matched the reserved `_files` as well as every real
  53. // collection. Nobody writing `*` means "and the reserved names too", and
  54. // the docs describe `_files` as something a policy NAMES.
  55. //
  56. // Checked against production before changing it: none of the 7 keys there
  57. // holds a `*` rule, so nothing loses access.
  58. svapi::KeyScope scope;
  59. scope.rules.push_back({"*", {svapi::KeyOp::Read, svapi::KeyOp::List}, false});
  60. EXPECT_EQ(scope.findRule("_files", svapi::KeyOp::Read), nullptr)
  61. << "a wildcard must not confer file access implicitly";
  62. // The pair that makes the assertion above mean something: `*` must still
  63. // match a real collection, or this test would pass against a function that
  64. // matched nothing at all.
  65. EXPECT_NE(scope.findRule("kb_chunks", svapi::KeyOp::Read), nullptr)
  66. << "`*` must still mean every REAL collection";
  67. }
  68. TEST(KeyScopeReserved, AnExplicitFilesRuleStillWorks) {
  69. // The other direction: naming it must keep working, or the feature is gone
  70. // rather than narrowed.
  71. svapi::KeyScope scope;
  72. scope.rules.push_back({"_files", {svapi::KeyOp::Read}, false});
  73. EXPECT_NE(scope.findRule("_files", svapi::KeyOp::Read), nullptr);
  74. EXPECT_EQ(scope.findRule("_files", svapi::KeyOp::Insert), nullptr)
  75. << "ops are still honoured on a reserved name";
  76. }
  77. TEST(KeyScopeReserved, APrefixWildcardDoesNotReachUnderscoreNamesEither) {
  78. // Not just the bare `*`: any trailing-wildcard pattern must stop at a
  79. // reserved name. `_*` is the one someone would reach for to grant "all the
  80. // internal things", and it must not work by accident.
  81. for (const char* pat : {"*", "_*", "_f*", "_files*"}) {
  82. svapi::KeyScope scope;
  83. scope.rules.push_back({pat, {svapi::KeyOp::Read}, false});
  84. EXPECT_EQ(scope.findRule("_files", svapi::KeyOp::Read), nullptr) << "pattern " << pat;
  85. }
  86. }
  87. TEST(KeyScopeReserved, ThisIsWhyItMattersForAnythingAddedLater) {
  88. // A reserved name reachable by wildcard is harmless while it only widens a
  89. // read. It stops being harmless for a grant that lets a function ACT - a
  90. // mail connection, say. Asserting the rule generally, with a name that
  91. // does not exist yet, so the precedent cannot be re-broken by whoever adds
  92. // the next reserved prefix.
  93. svapi::KeyScope scope;
  94. scope.rules.push_back({"*", {svapi::KeyOp::Read, svapi::KeyOp::Insert}, false});
  95. EXPECT_EQ(scope.findRule("_conn:some_mailbox", svapi::KeyOp::Insert), nullptr)
  96. << "a future reserved prefix must inherit the literal-grant rule automatically";
  97. }
  98. // ─── A READ-MODIFY-WRITE CLIENT MUST NOT BE ABLE TO LOSE A FIELD ──────────
  99. //
  100. // The function policy route is a full REPLACE, so the web UI reads a policy,
  101. // edits one control and sends the whole thing back. Every field `fromJson`
  102. // understands therefore has to appear in `toJson`, or the client cannot
  103. // return what it was given and the save silently resets it to a default.
  104. //
  105. // This was NOT hypothetical. `pages/Functions.tsx` built its policy object
  106. // from a literal of four fields, so saving an unrelated control wiped
  107. // `ip_allow` - an address allow-list removed by editing a rate limit, with a
  108. // success toast. The UI now spreads what it loaded; this test is what stops
  109. // the next field being added to the parser and not to the emitter, which is
  110. // the half a UI fix cannot protect.
  111. TEST(KeyScopeRoundTrip, EveryFieldFromJsonReadsIsAlsoEmittedByToJson) {
  112. svapi::KeyScope s;
  113. s.rules.push_back({"c", {svapi::KeyOp::Read}, false});
  114. s.origins = {"https://example.test"};
  115. s.ipAllow = {"203.0.113.0/24"};
  116. s.allowSameOriginHost = true;
  117. s.rateLimitPerMin = 60;
  118. s.rateLimitPerCallerPerMin = 5;
  119. s.expiresAt = 1790000000ull;
  120. // The trip a read-modify-write client makes, with NO edit at all: whatever
  121. // comes out must go back in unchanged.
  122. const svapi::KeyScope back = svapi::KeyScope::fromJson(s.toJson());
  123. EXPECT_EQ(back.rules.size(), 1u);
  124. EXPECT_EQ(back.origins, s.origins);
  125. EXPECT_EQ(back.ipAllow, s.ipAllow) << "an allow-list lost here is a security control "
  126. "removed by an unrelated edit";
  127. EXPECT_EQ(back.allowSameOriginHost, s.allowSameOriginHost);
  128. EXPECT_EQ(back.rateLimitPerMin, s.rateLimitPerMin);
  129. EXPECT_EQ(back.rateLimitPerCallerPerMin, s.rateLimitPerCallerPerMin);
  130. EXPECT_EQ(back.expiresAt, s.expiresAt);
  131. }
  132. // THE PAIRING, naming the fields explicitly. The test above would still pass
  133. // if a field were dropped from BOTH sides at once, which is exactly what
  134. // happens when someone "tidies up" an unused member - so assert the key is
  135. // actually present in the wire shape rather than only that a round trip
  136. // agrees with itself.
  137. TEST(KeyScopeRoundTrip, TheWireShapeNamesEveryFieldEvenAtItsDefault) {
  138. const nlohmann::json j = svapi::KeyScope{}.toJson();
  139. for (const char* k : {"rules", "origins", "ip_allow", "allow_same_origin_host",
  140. "rate_limit_per_min", "rate_limit_per_caller_per_min",
  141. "expires_at"}) {
  142. EXPECT_TRUE(j.contains(k))
  143. << k << " is absent from the wire shape, so a client that reads a policy "
  144. "and sends it back cannot preserve it";
  145. }
  146. }