server.cpp 5.5 KB

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