server.cpp 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. #include "server.hpp"
  2. #include "errors.hpp"
  3. #include "json_http.hpp"
  4. #include "rate_limiter.hpp"
  5. #include <chrono>
  6. #include <fstream>
  7. #include <sstream>
  8. namespace svapi {
  9. ApiServer::ApiServer(ServerDeps deps) : d_(std::move(deps)) {}
  10. static bool keyExpired(const ApiKey& k) {
  11. if (!k.scope) return false;
  12. auto now = (uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
  13. std::chrono::system_clock::now().time_since_epoch()).count();
  14. return k.scope->expired(now);
  15. }
  16. std::optional<ApiKey> resolveKey(ServerDeps& d, const httplib::Request& req) {
  17. if (auto it = req.headers.find("Authorization"); it != req.headers.end())
  18. if (auto tok = bearerToken(it->second))
  19. if (auto k = d.keys.lookup(*tok)) { if (!keyExpired(*k)) return k; return std::nullopt; }
  20. if (auto it = req.headers.find("Cookie"); it != req.headers.end())
  21. if (auto c = cookieValue(it->second, "svapi_session"))
  22. if (auto keyVal = d.sessions.keyFor(*c, std::chrono::system_clock::now()))
  23. if (auto k = d.keys.lookup(*keyVal)) { if (!keyExpired(*k)) return k; return std::nullopt; }
  24. return std::nullopt;
  25. }
  26. ApiKey requireKey(ServerDeps& d, const httplib::Request& req) {
  27. if (auto k = resolveKey(d, req)) return *k;
  28. throw ApiError(ErrCode::Unauthorized, "unauthorized", "missing or invalid credentials");
  29. }
  30. void requireAdmin(const ApiKey& k) {
  31. if (!k.admin) throw ApiError(ErrCode::Forbidden, "forbidden", "admin privilege required");
  32. }
  33. void requireProjectAccess(const ApiKey& k, const std::string& project) {
  34. if (!k.canAccess(project))
  35. throw ApiError(ErrCode::Forbidden, "forbidden", "key not granted project '" + project + "'");
  36. }
  37. void requireCapability(ServerDeps& d, const ApiKey& k, const httplib::Request& req,
  38. const std::string& project, const std::string& collection, KeyOp op) {
  39. requireProjectAccess(k, project);
  40. if (!k.scope) return; // legacy full-access key
  41. const KeyScope& sc = *k.scope;
  42. const KeyScopeRule* rule = sc.findRule(collection, op);
  43. if (!rule)
  44. throw ApiError(ErrCode::Forbidden, "forbidden", "key scope does not permit this operation");
  45. std::string origin;
  46. if (auto it = req.headers.find("Origin"); it != req.headers.end()) origin = it->second;
  47. if (!sc.originAllowed(origin))
  48. throw ApiError(ErrCode::Forbidden, "forbidden", "origin not allowed for this key");
  49. if (!rateLimiter().allow(k.id, sc.rateLimitPerMin))
  50. throw ApiError(ErrCode::TooManyRequests, "rate_limited", "rate limit exceeded");
  51. // Phase 2 (CAPTCHA) inserts the rule->requireHumanToken check here.
  52. (void)d;
  53. }
  54. void ApiServer::registerRoutes() {
  55. svr_.set_exception_handler([](const httplib::Request&, httplib::Response& res, std::exception_ptr ep) {
  56. try { std::rethrow_exception(ep); }
  57. catch (const ApiError& e) {
  58. if (e.code == ErrCode::TooManyRequests) res.set_header("Retry-After", "60");
  59. sendJson(res, httpStatus(e.code), errorBody(e.slug, e.what()));
  60. }
  61. catch (const std::exception& e) { sendJson(res, 500, errorBody("internal", e.what())); }
  62. });
  63. // SPA history fallback: a hard navigation / refresh / direct URL to a client-side
  64. // route (e.g. /login, /settings) reaches the server as a 404 (no such static file).
  65. // Serve index.html so React Router can handle it. Excludes API/meta routes and asset
  66. // requests (paths with a file extension), which should keep their real 404.
  67. svr_.set_error_handler([this](const httplib::Request& req, httplib::Response& res) {
  68. if (res.status == 404 && req.method == "GET" && !d_.webuiDir.empty()
  69. && req.path.rfind("/api/", 0) != 0
  70. && req.path.rfind("/ui/", 0) != 0
  71. && req.path.rfind("/docs", 0) != 0
  72. && req.path != "/openapi.json" && req.path != "/llms.txt"
  73. && req.path != "/healthz" && req.path != "/readyz"
  74. && req.path.find('.') == std::string::npos) {
  75. std::ifstream f(d_.webuiDir + "/index.html", std::ios::binary);
  76. if (f) {
  77. std::stringstream ss; ss << f.rdbuf();
  78. res.set_content(ss.str(), "text/html");
  79. res.status = 200;
  80. return httplib::Server::HandlerResponse::Handled;
  81. }
  82. }
  83. return httplib::Server::HandlerResponse::Unhandled;
  84. });
  85. // Authenticate /api/* (authorization is per-handler).
  86. svr_.set_pre_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
  87. if (req.method != "OPTIONS" && req.path.rfind("/api/", 0) == 0) {
  88. if (!resolveKey(d_, req)) {
  89. sendJson(res, 401, errorBody("unauthorized", "missing or invalid credentials"));
  90. return httplib::Server::HandlerResponse::Handled;
  91. }
  92. }
  93. return httplib::Server::HandlerResponse::Unhandled;
  94. });
  95. svr_.set_post_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
  96. auto snap = d_.settings.snapshot();
  97. std::string responseOrigin;
  98. if (!snap->corsOrigins.empty() && snap->corsOrigins[0] == "*") {
  99. responseOrigin = "*";
  100. } else if (auto it = req.headers.find("Origin"); it != req.headers.end()) {
  101. for (const auto& a : snap->corsOrigins) if (a == it->second) { responseOrigin = it->second; break; }
  102. }
  103. if (!responseOrigin.empty()) {
  104. res.set_header("Access-Control-Allow-Origin", responseOrigin);
  105. if (responseOrigin != "*") res.set_header("Vary", "Origin");
  106. }
  107. res.set_header("Access-Control-Allow-Headers", "Authorization, Content-Type");
  108. res.set_header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
  109. });
  110. svr_.Options(R"(.*)", [](const httplib::Request&, httplib::Response& res) { res.status = 204; });
  111. registerMetaRoutes(*this);
  112. registerWebuiAuthRoutes(*this);
  113. registerProjectRoutes(*this);
  114. registerKeyRoutes(*this);
  115. registerCollectionRoutes(*this);
  116. registerDocumentRoutes(*this);
  117. registerVectorRoutes(*this);
  118. registerStatsRoutes(*this);
  119. registerSettingsRoutes(*this);
  120. if (!d_.shareDir.empty()) svr_.set_mount_point("/docs", d_.shareDir + "/docs");
  121. if (!d_.webuiDir.empty()) svr_.set_mount_point("/", d_.webuiDir);
  122. }
  123. int ApiServer::bindToAnyPort(const std::string& host) { return svr_.bind_to_any_port(host); }
  124. void ApiServer::listenAfterBind() { svr_.listen_after_bind(); }
  125. bool ApiServer::listen(const std::string& host, uint16_t port) { return svr_.listen(host, port); }
  126. void ApiServer::stop() { svr_.stop(); }
  127. } // namespace svapi