apikey.hpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. uint32_t rateLimitPerMin = 0; // 0 = unlimited
  20. uint64_t expiresAt = 0; // epoch seconds; 0 = never
  21. const KeyScopeRule* findRule(const std::string& collection, KeyOp op) const;
  22. bool originAllowed(const std::string& origin) const;
  23. bool expired(uint64_t nowEpochSec) const;
  24. static KeyScope fromJson(const nlohmann::json& j);
  25. nlohmann::json toJson() const;
  26. };
  27. /// An API key with per-project grants and optional admin privilege.
  28. struct ApiKey {
  29. std::string id; // stable non-secret identifier (used as DB doc id)
  30. std::string key; // secret value (used for authentication only)
  31. std::string label;
  32. std::vector<std::string> projects; // may contain "*" (all projects)
  33. bool admin = false;
  34. uint64_t createdAt = 0;
  35. std::optional<KeyScope> scope;
  36. static ApiKey fromJson(const nlohmann::json& j);
  37. nlohmann::json toJson() const; // full (includes key) — for DB storage
  38. nlohmann::json toPublicJson() const; // masked: label, projects, admin, created_at, key_prefix
  39. /// Returns true if admin, or projects contains "*", or projects contains project.
  40. bool canAccess(const std::string& project) const;
  41. };
  42. /// Generate a 48-character lowercase hex key (24 random bytes via OpenSSL RAND_bytes).
  43. std::string generateApiKey();
  44. } // namespace svapi