server.cpp 7.1 KB

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