apikey.hpp 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #pragma once
  2. #include <nlohmann/json.hpp>
  3. #include <optional>
  4. #include <set>
  5. #include <string>
  6. #include <vector>
  7. namespace svapi {
  8. enum class KeyOp { Read, List, Search, Insert, Update, Delete };
  9. std::optional<KeyOp> keyOpFromString(const std::string& s);
  10. std::string keyOpToString(KeyOp op);
  11. struct KeyScopeRule {
  12. std::string collection; // exact ("presets") or prefix glob ("catalog_*")
  13. std::set<KeyOp> ops;
  14. bool requireHumanToken = false;
  15. };
  16. struct KeyScope {
  17. std::vector<KeyScopeRule> rules;
  18. std::vector<std::string> origins; // empty = any origin allowed
  19. /// CIDR ranges (or bare addresses) the caller must come from. EMPTY = any.
  20. ///
  21. /// ENFORCED ON FUNCTION POLICIES ONLY, and the key route REFUSES it rather
  22. /// than storing it, because a security control that is accepted and
  23. /// silently not applied is the worst thing in this file's vocabulary. The
  24. /// "refuse what you cannot honour" rule, applied to ourselves.
  25. ///
  26. /// It is the server-side sibling of `origins`, and it closes a gap that one
  27. /// cannot: an Origin header is sent by browsers, so a key meant for
  28. /// server-to-server use can never satisfy an origin allow-list and must
  29. /// carry none - which leaves exactly the keys with the widest blast radius
  30. /// with no network restriction available to them. An address can be
  31. /// checked for any caller.
  32. ///
  33. /// FAILS CLOSED: a non-empty list with no trustworthy client address
  34. /// refuses, which mirrors `originAllowed("")` being false for a non-empty
  35. /// origin list. The cost is stated rather than discovered - misconfigure
  36. /// `trusted_proxy_cidrs` and every caller is refused rather than the wrong
  37. /// ones - and the owner accepted that trade deliberately on 2026-11-19.
  38. ///
  39. /// The MEMBERSHIP TEST is `functions::addressAllowedBy`, not a method here:
  40. /// this struct is pure data compiled standalone by several narrow test
  41. /// targets, and giving it CIDR parsing broke four of them.
  42. std::vector<std::string> ipAllow;
  43. uint32_t rateLimitPerMin = 0; // 0 = unlimited
  44. uint64_t expiresAt = 0; // epoch seconds; 0 = never
  45. const KeyScopeRule* findRule(const std::string& collection, KeyOp op) const;
  46. /// Whether ANY rule mentions this collection, whatever the op.
  47. ///
  48. /// The question a LISTING asks, and it is deliberately weaker than
  49. /// `findRule(name, KeyOp::List)`. If a key may do anything at all with a
  50. /// collection - read one document, insert one - then its existence is not
  51. /// a secret from that key, and hiding the name buys nothing while costing
  52. /// the thing the listing was added for: a consumer had to hardcode four
  53. /// collection names into a backup script, so a collection added later was
  54. /// silently missed. What the listing must not do is enumerate collections
  55. /// the key cannot touch AT ALL.
  56. ///
  57. /// Pure and op-free, so it also charges no rate limit - unlike
  58. /// `requireCapabilityCore`, which would spend one token per collection
  59. /// examined and could rate-limit a caller for a single listing.
  60. bool reachesCollection(const std::string& collection) const;
  61. bool originAllowed(const std::string& origin) const;
  62. bool expired(uint64_t nowEpochSec) const;
  63. static KeyScope fromJson(const nlohmann::json& j);
  64. nlohmann::json toJson() const;
  65. };
  66. /// An API key with per-project grants and optional admin privilege.
  67. struct ApiKey {
  68. std::string id; // stable non-secret identifier (used as DB doc id)
  69. std::string key; // secret value (used for authentication only)
  70. std::string label;
  71. std::vector<std::string> projects; // may contain "*" (all projects)
  72. bool admin = false;
  73. uint64_t createdAt = 0;
  74. std::optional<KeyScope> scope;
  75. static ApiKey fromJson(const nlohmann::json& j);
  76. nlohmann::json toJson() const; // full (includes key) — for DB storage
  77. nlohmann::json toPublicJson() const; // masked: label, projects, admin, created_at, key_prefix
  78. /// Returns true if admin, or projects contains "*", or projects contains project.
  79. bool canAccess(const std::string& project) const;
  80. };
  81. /// Generate a 48-character lowercase hex key (24 random bytes via OpenSSL RAND_bytes).
  82. std::string generateApiKey();
  83. } // namespace svapi