server.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. #include "scope_refusal.hpp"
  2. #include "server.hpp"
  3. #include "captcha.hpp"
  4. #include "db_errors.hpp"
  5. #include "errors.hpp"
  6. #include "json_http.hpp"
  7. #include "rate_limiter.hpp"
  8. #include "access_log.hpp"
  9. #include "client_ip.hpp"
  10. #include <spdlog/spdlog.h>
  11. #include <chrono>
  12. #include <fstream>
  13. #include <sstream>
  14. namespace svapi {
  15. std::string projectFor(ServerDeps& d, const httplib::Request& req, size_t group) {
  16. const auto reg = d.settings.hostRegistry();
  17. const bool gatingOn = reg && reg->gating();
  18. const HostBinding host = reg ? reg->resolve(req.get_header_value("Host")) : HostBinding{};
  19. // An absent group is the short form. `req.matches` is sized by the pattern,
  20. // so a route whose optional project group did not participate yields an
  21. // empty string - but the size is guarded anyway, because a route registered
  22. // WITHOUT the group would otherwise read past the end, and that failure
  23. // would be a crash where this one is a 404.
  24. const std::string pathProject =
  25. group < req.matches.size() ? std::string(req.matches[group]) : std::string();
  26. const ProjectResolution r = resolveProject(pathProject, host, gatingOn);
  27. if (!r.ok)
  28. throw ApiError(ErrCode::NotFound, "not_found", "no such project on this hostname");
  29. return r.project;
  30. }
  31. ApiServer::ApiServer(ServerDeps deps) : d_(std::move(deps)) {}
  32. static bool keyExpired(const ApiKey& k) {
  33. if (!k.scope) return false;
  34. auto now = (uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
  35. std::chrono::system_clock::now().time_since_epoch()).count();
  36. return k.scope->expired(now);
  37. }
  38. std::optional<ApiKey> resolveKey(ServerDeps& d, const httplib::Request& req) {
  39. if (auto it = req.headers.find("Authorization"); it != req.headers.end())
  40. if (auto tok = bearerToken(it->second))
  41. if (auto k = d.keys.lookup(*tok)) { if (!keyExpired(*k)) return k; return std::nullopt; }
  42. if (auto it = req.headers.find("Cookie"); it != req.headers.end())
  43. if (auto c = cookieValue(it->second, "svapi_session"))
  44. if (auto keyVal = d.sessions.keyFor(*c, std::chrono::system_clock::now()))
  45. if (auto k = d.keys.lookup(*keyVal)) { if (!keyExpired(*k)) return k; return std::nullopt; }
  46. return std::nullopt;
  47. }
  48. ApiKey requireKey(ServerDeps& d, const httplib::Request& req) {
  49. if (auto k = resolveKey(d, req)) return *k;
  50. throw ApiError(ErrCode::Unauthorized, "unauthorized", "missing or invalid credentials");
  51. }
  52. // --- Principal forms: the real implementations --------------------------------
  53. void requireAdmin(const Principal& p) {
  54. if (!p.admin) throw ApiError(ErrCode::Forbidden, "forbidden", "admin privilege required");
  55. }
  56. void requireProjectAccess(const Principal& p, const std::string& project) {
  57. if (!p.canAccess(project))
  58. throw ApiError(ErrCode::Forbidden, "forbidden", "not granted project '" + project + "'");
  59. }
  60. void requireProjectManage(const Principal& p, const std::string& project) {
  61. requireProjectAccess(p, project);
  62. if (p.scope)
  63. throw ApiError(ErrCode::Forbidden, "forbidden", "scoped callers cannot manage collections");
  64. }
  65. void requireCapabilityCore(const Principal& p, const std::string& project,
  66. const std::string& collection, KeyOp op) {
  67. requireProjectAccess(p, project);
  68. if (!p.scope) return; // unscoped: full access
  69. const KeyScope& sc = *p.scope;
  70. if (!sc.findRule(collection, op)) {
  71. // Names the collection and the op, and echoes what this key IS
  72. // granted. Status stays 403 on purpose - see scope_refusal.hpp for
  73. // why 404-for-absent would reopen a closed leak.
  74. const ScopeRefusal r = describeScopeRefusal(sc, collection, op);
  75. throw ApiError(ErrCode::Forbidden, "forbidden", r.message, r.details);
  76. }
  77. if (!rateLimiter().allow(p.id, sc.rateLimitPerMin))
  78. throw ApiError(ErrCode::TooManyRequests, "rate_limited", "rate limit exceeded");
  79. }
  80. // --- ApiKey forms: kept so no handler changes, and so the HTTP-only checks
  81. // --- (Origin, captcha) stay where a request actually exists.
  82. void requireAdmin(const ApiKey& k) { requireAdmin(Principal::of(k)); }
  83. void requireProjectAccess(const ApiKey& k, const std::string& project) {
  84. // Message keeps saying "key" here: this form is only reached by a key holder.
  85. if (!k.canAccess(project))
  86. throw ApiError(ErrCode::Forbidden, "forbidden", "key not granted project '" + project + "'");
  87. }
  88. void requireProjectManage(const ApiKey& k, const std::string& project) {
  89. requireProjectAccess(k, project);
  90. if (k.scope)
  91. throw ApiError(ErrCode::Forbidden, "forbidden", "scoped keys cannot manage collections");
  92. }
  93. void requireAllowedOrigin(const ApiKey& k, const httplib::Request& req) {
  94. if (!k.scope) return; // legacy full-access key: no allow-list to enforce
  95. std::string origin;
  96. if (auto it = req.headers.find("Origin"); it != req.headers.end()) origin = it->second;
  97. // NOTE an ABSENT Origin is refused when a list is set, because
  98. // originAllowed("") is false for a non-empty list. That is pre-existing
  99. // behaviour on every capability-checked route, not something this gate
  100. // introduced, and it is why a key meant for server-side use must not
  101. // carry an allow-list at all. Kept identical here deliberately: the bug
  102. // being fixed was the listing behaving DIFFERENTLY from its siblings, so
  103. // a second, softer rule here would replace one inconsistency with another.
  104. if (!k.scope->originAllowed(origin))
  105. throw ApiError(ErrCode::Forbidden, "forbidden", "origin not allowed for this key");
  106. }
  107. void requireCapability(ServerDeps& d, const ApiKey& k, const httplib::Request& req,
  108. const std::string& project, const std::string& collection, KeyOp op) {
  109. // Grant, rule and rate limit are the caller-agnostic part.
  110. requireCapabilityCore(Principal::of(k), project, collection, op);
  111. if (!k.scope) return; // legacy full-access key
  112. const KeyScope& sc = *k.scope;
  113. const KeyScopeRule* rule = sc.findRule(collection, op); // re-read for requireHumanToken
  114. requireAllowedOrigin(k, req);
  115. if (rule->requireHumanToken) {
  116. std::string token;
  117. if (auto it = req.headers.find("X-Captcha-Token"); it != req.headers.end()) token = it->second;
  118. auto snap = d.settings.snapshot();
  119. if (!verifyCaptcha(*snap, token, req.remote_addr))
  120. throw ApiError(ErrCode::Forbidden, "captcha_required", "human verification required");
  121. }
  122. }
  123. void ApiServer::registerRoutes() {
  124. svr_.set_exception_handler([](const httplib::Request& req, httplib::Response& res, std::exception_ptr ep) {
  125. // RECORD THE SLUG. We build a structured reason for every refusal and
  126. // used to keep NONE of it for a 4xx, so a refused request left only its
  127. // status code behind - and a status code is shared by a dozen causes.
  128. // Twice that has decided a diagnosis: a three-day 403 where only the
  129. // access log knew anything, and one failed insert whose cause was
  130. // narrowed by five eliminations and then could not be closed at all,
  131. // because the one 422 in the window was already gone.
  132. //
  133. // What is logged is the SLUG, the status and the route. Deliberately
  134. // NOT `details`: it legitimately echoes the caller's own input - the
  135. // colliding values of a duplicate, the violating paths of a schema
  136. // refusal - and a diagnostic log is the wrong place for tenant data we
  137. // were only ever meant to hand straight back. The slug is ours and
  138. // names the decision we took, which is the part nobody can reconstruct
  139. // afterwards.
  140. //
  141. // A 4xx is at INFO rather than warn: it is the caller's business and
  142. // routine (prod sees a few hundred 409s in a quiet afternoon from one
  143. // consumer's idempotent writes), so warning on it would train people to
  144. // filter the level that also carries real faults. But it must stay
  145. // ABOVE debug - a record only kept when someone thought to raise the
  146. // level is no record at all, since nobody raises it before the failure
  147. // they could not explain. A 5xx is ours and warns.
  148. auto record = [&req](const ApiError& e) {
  149. const int status = httpStatus(e.code);
  150. if (status >= 500)
  151. spdlog::warn("request failed: {} {} -> {} {}", req.method, req.path, status, e.slug);
  152. else
  153. spdlog::info("request refused: {} {} -> {} {}", req.method, req.path, status, e.slug);
  154. };
  155. // One sender for every classified failure, so a database-raised 429
  156. // carries Retry-After exactly as one of ours does.
  157. auto send = [&res, &record](const ApiError& e) {
  158. record(e);
  159. // One decider (errors.hpp), so the header cannot drift from the
  160. // raise sites that set it - and so the handler never has to
  161. // recover the CAUSE by matching on a slug, which would be the
  162. // message-text trap one layer along.
  163. if (const int secs = retryAfterSeconds(e); secs > 0)
  164. res.set_header("Retry-After", std::to_string(secs));
  165. sendJson(res, httpStatus(e.code), errorBody(e.slug, e.what(), e.details));
  166. };
  167. try { std::rethrow_exception(ep); }
  168. catch (const ApiError& e) { send(e); }
  169. // A database failure that nothing caught at the call site. This arm is
  170. // the difference between 503 and 500 for a whole class of reads: the
  171. // client answers empty for a failed read on some calls and THROWS on
  172. // others, and a read whose "nothing there" value is also a valid answer
  173. // throws rather than lying. Without this arm an outage would reach the
  174. // caller as 500 "internal" carrying a gRPC sentence, which says "we are
  175. // broken, do not retry" where the truth is "wait and retry".
  176. //
  177. // MUST precede the std::exception arm: Client::Error derives from
  178. // std::runtime_error, so a more general arm placed first would swallow
  179. // every one of these and the mapping would silently never run.
  180. catch (const smartbotic::database::Client::Error& e) { send(apiErrorFor(e)); }
  181. catch (const std::exception& e) {
  182. // The one arm with no classification at all. It logs the exception
  183. // TEXT as well as the slug, because unlike every arm above there is
  184. // no slug that distinguishes one of these from another - this is
  185. // the branch where a 500 means "we do not know", and it is ours
  186. // rather than the caller's, so there is no tenant data concern.
  187. spdlog::error("request failed: {} {} -> 500 internal: {}", req.method, req.path,
  188. e.what());
  189. sendJson(res, 500, errorBody("internal", e.what()));
  190. }
  191. });
  192. // SPA history fallback: a hard navigation / refresh / direct URL to a client-side
  193. // route (e.g. /login, /settings) reaches the server as a 404 (no such static file).
  194. // Serve index.html so React Router can handle it. Excludes API/meta routes and asset
  195. // requests (paths with a file extension), which should keep their real 404.
  196. svr_.set_error_handler([this](const httplib::Request& req, httplib::Response& res) {
  197. if (res.status == 404 && req.method == "GET" && !d_.webuiDir.empty()
  198. && req.path.rfind("/api/", 0) != 0
  199. && req.path.rfind("/ui/", 0) != 0
  200. // /fn/* is user function dispatch: a path that matches no function
  201. // owes the caller a real 404, not the SPA shell with status 200.
  202. && req.path.rfind("/fn/", 0) != 0
  203. && req.path.rfind("/docs", 0) != 0
  204. && req.path != "/openapi.json" && req.path != "/llms.txt"
  205. && req.path != "/healthz" && req.path != "/readyz"
  206. && req.path.find('.') == std::string::npos) {
  207. std::ifstream f(d_.webuiDir + "/index.html", std::ios::binary);
  208. if (f) {
  209. std::stringstream ss; ss << f.rdbuf();
  210. res.set_content(ss.str(), "text/html");
  211. res.status = 200;
  212. return httplib::Server::HandlerResponse::Handled;
  213. }
  214. }
  215. return httplib::Server::HandlerResponse::Unhandled;
  216. });
  217. // Authenticate /api/* (authorization is per-handler).
  218. svr_.set_pre_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
  219. // START of the request: zero the clock and forget the previous
  220. // request's slug. See access_log.hpp on why that ordering matters.
  221. beginRequestTrace();
  222. // HOST GATE. Runs before everything, including authentication.
  223. //
  224. // It exists for the surfaces projectFor() cannot reach: the global
  225. // routes that name no project (/api/v1/keys, /settings, /stats,
  226. // /version), the web UI and the docs catalogue. Without it a project
  227. // hostname would serve the admin UI and the complete operation list -
  228. // which is precisely the surface withdrawn from the customer-facing
  229. // name in 0.15.0 after five hours, for the reason that it publishes a
  230. // catalogue of what to come back and try.
  231. //
  232. // SKIPPED ENTIRELY WHEN NOTHING IS REGISTERED, which is the default and
  233. // every deployment today: the test fixture, the devstack and anything
  234. // behind someone else's proxy all send a Host nobody registered, and
  235. // refusing those would be an outage caused by ADDING a control.
  236. if (const auto reg = d_.settings.hostRegistry(); reg && reg->gating()) {
  237. const HostBinding host = reg->resolve(req.get_header_value("Host"));
  238. if (host.kind == HostKind::Unknown) {
  239. // 404, never a redirect and never a fallback to a default
  240. // host: an unknown name is not a mistake we can correct for the
  241. // caller, and guessing is how one tenant answers for another.
  242. sendJson(res, 404, errorBody("not_found", "no such host"));
  243. return httplib::Server::HandlerResponse::Handled;
  244. }
  245. // A project hostname serves the API and functions only. `/healthz`
  246. // stays reachable everywhere so an outside monitor needs no
  247. // credential and no special name.
  248. if (host.kind == HostKind::Project && req.method != "OPTIONS" &&
  249. req.path.rfind("/api/", 0) != 0 && req.path.rfind("/fn/", 0) != 0 &&
  250. req.path != "/healthz") {
  251. sendJson(res, 404, errorBody("not_found", "not served on this host"));
  252. return httplib::Server::HandlerResponse::Handled;
  253. }
  254. }
  255. if (req.method != "OPTIONS" && req.path.rfind("/api/", 0) == 0) {
  256. if (!resolveKey(d_, req)) {
  257. sendJson(res, 401, errorBody("unauthorized", "missing or invalid credentials"));
  258. return httplib::Server::HandlerResponse::Handled;
  259. }
  260. }
  261. return httplib::Server::HandlerResponse::Unhandled;
  262. });
  263. // OUR OWN ACCESS LOG. Off unless an operator set a path.
  264. //
  265. // It carries the two halves that live in different files today: the
  266. // resolved caller address, which only nginx knows, and the error SLUG,
  267. // which only our journal knows. A fail2ban jail can therefore ban on
  268. // `code=unauthorized` rather than on every 401 the service emits, and the
  269. // address it acts on is one we resolved under the trusted-proxy rule rather
  270. // than whatever a header claimed.
  271. svr_.set_logger([this](const httplib::Request& req, const httplib::Response& res) {
  272. if (!accessLog().enabled()) return;
  273. auto snap = d_.settings.snapshot();
  274. AccessLogEntry e;
  275. e.clientIp = clientIpFor(req, *snap);
  276. e.method = req.method;
  277. e.path = req.path;
  278. e.status = res.status;
  279. e.errorCode = requestErrorCode();
  280. e.durationMs = requestElapsedMs();
  281. // The key is referenced by its stable id, NEVER the secret - the same
  282. // rule the rest of the service follows. An unauthenticated request
  283. // leaves it empty, which renders as `-`.
  284. if (auto key = resolveKey(d_, req)) e.keyId = key->id;
  285. accessLog().write(e);
  286. });
  287. svr_.set_post_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
  288. auto snap = d_.settings.snapshot();
  289. std::string responseOrigin;
  290. if (!snap->corsOrigins.empty() && snap->corsOrigins[0] == "*") {
  291. responseOrigin = "*";
  292. } else if (auto it = req.headers.find("Origin"); it != req.headers.end()) {
  293. for (const auto& a : snap->corsOrigins) if (a == it->second) { responseOrigin = it->second; break; }
  294. }
  295. if (!responseOrigin.empty()) {
  296. res.set_header("Access-Control-Allow-Origin", responseOrigin);
  297. if (responseOrigin != "*") res.set_header("Vary", "Origin");
  298. }
  299. res.set_header("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Captcha-Token, Cache-Control");
  300. res.set_header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
  301. });
  302. svr_.Options(R"(.*)", [](const httplib::Request&, httplib::Response& res) { res.status = 204; });
  303. registerMetaRoutes(*this);
  304. registerWebuiAuthRoutes(*this);
  305. registerProjectRoutes(*this);
  306. registerKeyRoutes(*this);
  307. registerCollectionRoutes(*this);
  308. registerIndexRoutes(*this);
  309. registerCollectionSchemaRoutes(*this);
  310. registerDocumentRoutes(*this);
  311. registerVectorRoutes(*this);
  312. registerStatsRoutes(*this);
  313. registerSettingsRoutes(*this);
  314. registerProjectSettingsRoutes(*this);
  315. registerProjectSecretRoutes(*this);
  316. registerFileRoutes(*this);
  317. registerExportRoutes(*this);
  318. registerRelationRoutes(*this);
  319. registerFunctionRoutes(*this);
  320. // LAST. Function dispatch owns /fn/* , and registering it after the
  321. // built-in routes means a user function can never shadow one of them even
  322. // if cpp-httplib's matching order ever changes.
  323. registerFunctionDispatchRoutes(*this);
  324. if (!d_.shareDir.empty()) svr_.set_mount_point("/docs", d_.shareDir + "/docs");
  325. if (!d_.webuiDir.empty()) svr_.set_mount_point("/", d_.webuiDir);
  326. }
  327. void ApiServer::setThreadPoolSize(uint32_t n) {
  328. if (n == 0) return; // leave cpp-httplib's own default alone
  329. svr_.new_task_queue = [n] { return new httplib::ThreadPool(n); };
  330. }
  331. int ApiServer::bindToAnyPort(const std::string& host) { return svr_.bind_to_any_port(host); }
  332. void ApiServer::listenAfterBind() { svr_.listen_after_bind(); }
  333. bool ApiServer::listen(const std::string& host, uint16_t port) { return svr_.listen(host, port); }
  334. void ApiServer::stop() { svr_.stop(); }
  335. } // namespace svapi