| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361 |
- #include "scope_refusal.hpp"
- #include "server.hpp"
- #include "captcha.hpp"
- #include "db_errors.hpp"
- #include "errors.hpp"
- #include "json_http.hpp"
- #include "rate_limiter.hpp"
- #include "access_log.hpp"
- #include "client_ip.hpp"
- #include <spdlog/spdlog.h>
- #include <chrono>
- #include <fstream>
- #include <sstream>
- namespace svapi {
- std::string projectFor(ServerDeps& d, const httplib::Request& req, size_t group) {
- const auto reg = d.settings.hostRegistry();
- const bool gatingOn = reg && reg->gating();
- const HostBinding host = reg ? reg->resolve(req.get_header_value("Host")) : HostBinding{};
- // An absent group is the short form. `req.matches` is sized by the pattern,
- // so a route whose optional project group did not participate yields an
- // empty string - but the size is guarded anyway, because a route registered
- // WITHOUT the group would otherwise read past the end, and that failure
- // would be a crash where this one is a 404.
- const std::string pathProject =
- group < req.matches.size() ? std::string(req.matches[group]) : std::string();
- const ProjectResolution r = resolveProject(pathProject, host, gatingOn);
- if (!r.ok)
- throw ApiError(ErrCode::NotFound, "not_found", "no such project on this hostname");
- return r.project;
- }
- ApiServer::ApiServer(ServerDeps deps) : d_(std::move(deps)) {}
- static bool keyExpired(const ApiKey& k) {
- if (!k.scope) return false;
- auto now = (uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
- std::chrono::system_clock::now().time_since_epoch()).count();
- return k.scope->expired(now);
- }
- std::optional<ApiKey> resolveKey(ServerDeps& d, const httplib::Request& req) {
- if (auto it = req.headers.find("Authorization"); it != req.headers.end())
- if (auto tok = bearerToken(it->second))
- if (auto k = d.keys.lookup(*tok)) { if (!keyExpired(*k)) return k; return std::nullopt; }
- if (auto it = req.headers.find("Cookie"); it != req.headers.end())
- if (auto c = cookieValue(it->second, "svapi_session"))
- if (auto keyVal = d.sessions.keyFor(*c, std::chrono::system_clock::now()))
- if (auto k = d.keys.lookup(*keyVal)) { if (!keyExpired(*k)) return k; return std::nullopt; }
- return std::nullopt;
- }
- ApiKey requireKey(ServerDeps& d, const httplib::Request& req) {
- if (auto k = resolveKey(d, req)) return *k;
- throw ApiError(ErrCode::Unauthorized, "unauthorized", "missing or invalid credentials");
- }
- // --- Principal forms: the real implementations --------------------------------
- void requireAdmin(const Principal& p) {
- if (!p.admin) throw ApiError(ErrCode::Forbidden, "forbidden", "admin privilege required");
- }
- void requireProjectAccess(const Principal& p, const std::string& project) {
- if (!p.canAccess(project))
- throw ApiError(ErrCode::Forbidden, "forbidden", "not granted project '" + project + "'");
- }
- void requireProjectManage(const Principal& p, const std::string& project) {
- requireProjectAccess(p, project);
- if (p.scope)
- throw ApiError(ErrCode::Forbidden, "forbidden", "scoped callers cannot manage collections");
- }
- void requireCapabilityCore(const Principal& p, const std::string& project,
- const std::string& collection, KeyOp op) {
- requireProjectAccess(p, project);
- if (!p.scope) return; // unscoped: full access
- const KeyScope& sc = *p.scope;
- if (!sc.findRule(collection, op)) {
- // Names the collection and the op, and echoes what this key IS
- // granted. Status stays 403 on purpose - see scope_refusal.hpp for
- // why 404-for-absent would reopen a closed leak.
- const ScopeRefusal r = describeScopeRefusal(sc, collection, op);
- throw ApiError(ErrCode::Forbidden, "forbidden", r.message, r.details);
- }
- if (!rateLimiter().allow(p.id, sc.rateLimitPerMin))
- throw ApiError(ErrCode::TooManyRequests, "rate_limited", "rate limit exceeded");
- }
- // --- ApiKey forms: kept so no handler changes, and so the HTTP-only checks
- // --- (Origin, captcha) stay where a request actually exists.
- void requireAdmin(const ApiKey& k) { requireAdmin(Principal::of(k)); }
- void requireProjectAccess(const ApiKey& k, const std::string& project) {
- // Message keeps saying "key" here: this form is only reached by a key holder.
- if (!k.canAccess(project))
- throw ApiError(ErrCode::Forbidden, "forbidden", "key not granted project '" + project + "'");
- }
- void requireProjectManage(const ApiKey& k, const std::string& project) {
- requireProjectAccess(k, project);
- if (k.scope)
- throw ApiError(ErrCode::Forbidden, "forbidden", "scoped keys cannot manage collections");
- }
- void requireAllowedOrigin(const ApiKey& k, const httplib::Request& req) {
- if (!k.scope) return; // legacy full-access key: no allow-list to enforce
- std::string origin;
- if (auto it = req.headers.find("Origin"); it != req.headers.end()) origin = it->second;
- // NOTE an ABSENT Origin is refused when a list is set, because
- // originAllowed("") is false for a non-empty list. That is pre-existing
- // behaviour on every capability-checked route, not something this gate
- // introduced, and it is why a key meant for server-side use must not
- // carry an allow-list at all. Kept identical here deliberately: the bug
- // being fixed was the listing behaving DIFFERENTLY from its siblings, so
- // a second, softer rule here would replace one inconsistency with another.
- if (!k.scope->originAllowed(origin))
- throw ApiError(ErrCode::Forbidden, "forbidden", "origin not allowed for this key");
- }
- void requireCapability(ServerDeps& d, const ApiKey& k, const httplib::Request& req,
- const std::string& project, const std::string& collection, KeyOp op) {
- // Grant, rule and rate limit are the caller-agnostic part.
- requireCapabilityCore(Principal::of(k), project, collection, op);
- if (!k.scope) return; // legacy full-access key
- const KeyScope& sc = *k.scope;
- const KeyScopeRule* rule = sc.findRule(collection, op); // re-read for requireHumanToken
- requireAllowedOrigin(k, req);
- if (rule->requireHumanToken) {
- std::string token;
- if (auto it = req.headers.find("X-Captcha-Token"); it != req.headers.end()) token = it->second;
- auto snap = d.settings.snapshot();
- if (!verifyCaptcha(*snap, token, req.remote_addr))
- throw ApiError(ErrCode::Forbidden, "captcha_required", "human verification required");
- }
- }
- void ApiServer::registerRoutes() {
- svr_.set_exception_handler([](const httplib::Request& req, httplib::Response& res, std::exception_ptr ep) {
- // RECORD THE SLUG. We build a structured reason for every refusal and
- // used to keep NONE of it for a 4xx, so a refused request left only its
- // status code behind - and a status code is shared by a dozen causes.
- // Twice that has decided a diagnosis: a three-day 403 where only the
- // access log knew anything, and one failed insert whose cause was
- // narrowed by five eliminations and then could not be closed at all,
- // because the one 422 in the window was already gone.
- //
- // What is logged is the SLUG, the status and the route. Deliberately
- // NOT `details`: it legitimately echoes the caller's own input - the
- // colliding values of a duplicate, the violating paths of a schema
- // refusal - and a diagnostic log is the wrong place for tenant data we
- // were only ever meant to hand straight back. The slug is ours and
- // names the decision we took, which is the part nobody can reconstruct
- // afterwards.
- //
- // A 4xx is at INFO rather than warn: it is the caller's business and
- // routine (prod sees a few hundred 409s in a quiet afternoon from one
- // consumer's idempotent writes), so warning on it would train people to
- // filter the level that also carries real faults. But it must stay
- // ABOVE debug - a record only kept when someone thought to raise the
- // level is no record at all, since nobody raises it before the failure
- // they could not explain. A 5xx is ours and warns.
- auto record = [&req](const ApiError& e) {
- const int status = httpStatus(e.code);
- if (status >= 500)
- spdlog::warn("request failed: {} {} -> {} {}", req.method, req.path, status, e.slug);
- else
- spdlog::info("request refused: {} {} -> {} {}", req.method, req.path, status, e.slug);
- };
- // One sender for every classified failure, so a database-raised 429
- // carries Retry-After exactly as one of ours does.
- auto send = [&res, &record](const ApiError& e) {
- record(e);
- // One decider (errors.hpp), so the header cannot drift from the
- // raise sites that set it - and so the handler never has to
- // recover the CAUSE by matching on a slug, which would be the
- // message-text trap one layer along.
- if (const int secs = retryAfterSeconds(e); secs > 0)
- res.set_header("Retry-After", std::to_string(secs));
- sendJson(res, httpStatus(e.code), errorBody(e.slug, e.what(), e.details));
- };
- try { std::rethrow_exception(ep); }
- catch (const ApiError& e) { send(e); }
- // A database failure that nothing caught at the call site. This arm is
- // the difference between 503 and 500 for a whole class of reads: the
- // client answers empty for a failed read on some calls and THROWS on
- // others, and a read whose "nothing there" value is also a valid answer
- // throws rather than lying. Without this arm an outage would reach the
- // caller as 500 "internal" carrying a gRPC sentence, which says "we are
- // broken, do not retry" where the truth is "wait and retry".
- //
- // MUST precede the std::exception arm: Client::Error derives from
- // std::runtime_error, so a more general arm placed first would swallow
- // every one of these and the mapping would silently never run.
- catch (const smartbotic::database::Client::Error& e) { send(apiErrorFor(e)); }
- catch (const std::exception& e) {
- // The one arm with no classification at all. It logs the exception
- // TEXT as well as the slug, because unlike every arm above there is
- // no slug that distinguishes one of these from another - this is
- // the branch where a 500 means "we do not know", and it is ours
- // rather than the caller's, so there is no tenant data concern.
- spdlog::error("request failed: {} {} -> 500 internal: {}", req.method, req.path,
- e.what());
- sendJson(res, 500, errorBody("internal", e.what()));
- }
- });
- // SPA history fallback: a hard navigation / refresh / direct URL to a client-side
- // route (e.g. /login, /settings) reaches the server as a 404 (no such static file).
- // Serve index.html so React Router can handle it. Excludes API/meta routes and asset
- // requests (paths with a file extension), which should keep their real 404.
- svr_.set_error_handler([this](const httplib::Request& req, httplib::Response& res) {
- if (res.status == 404 && req.method == "GET" && !d_.webuiDir.empty()
- && req.path.rfind("/api/", 0) != 0
- && req.path.rfind("/ui/", 0) != 0
- // /fn/* is user function dispatch: a path that matches no function
- // owes the caller a real 404, not the SPA shell with status 200.
- && req.path.rfind("/fn/", 0) != 0
- && req.path.rfind("/docs", 0) != 0
- && req.path != "/openapi.json" && req.path != "/llms.txt"
- && req.path != "/healthz" && req.path != "/readyz"
- && req.path.find('.') == std::string::npos) {
- std::ifstream f(d_.webuiDir + "/index.html", std::ios::binary);
- if (f) {
- std::stringstream ss; ss << f.rdbuf();
- res.set_content(ss.str(), "text/html");
- res.status = 200;
- return httplib::Server::HandlerResponse::Handled;
- }
- }
- return httplib::Server::HandlerResponse::Unhandled;
- });
- // Authenticate /api/* (authorization is per-handler).
- svr_.set_pre_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
- // START of the request: zero the clock and forget the previous
- // request's slug. See access_log.hpp on why that ordering matters.
- beginRequestTrace();
- // HOST GATE. Runs before everything, including authentication.
- //
- // It exists for the surfaces projectFor() cannot reach: the global
- // routes that name no project (/api/v1/keys, /settings, /stats,
- // /version), the web UI and the docs catalogue. Without it a project
- // hostname would serve the admin UI and the complete operation list -
- // which is precisely the surface withdrawn from the customer-facing
- // name in 0.15.0 after five hours, for the reason that it publishes a
- // catalogue of what to come back and try.
- //
- // SKIPPED ENTIRELY WHEN NOTHING IS REGISTERED, which is the default and
- // every deployment today: the test fixture, the devstack and anything
- // behind someone else's proxy all send a Host nobody registered, and
- // refusing those would be an outage caused by ADDING a control.
- if (const auto reg = d_.settings.hostRegistry(); reg && reg->gating()) {
- const HostBinding host = reg->resolve(req.get_header_value("Host"));
- if (host.kind == HostKind::Unknown) {
- // 404, never a redirect and never a fallback to a default
- // host: an unknown name is not a mistake we can correct for the
- // caller, and guessing is how one tenant answers for another.
- sendJson(res, 404, errorBody("not_found", "no such host"));
- return httplib::Server::HandlerResponse::Handled;
- }
- // A project hostname serves the API and functions only. `/healthz`
- // stays reachable everywhere so an outside monitor needs no
- // credential and no special name.
- if (host.kind == HostKind::Project && req.method != "OPTIONS" &&
- req.path.rfind("/api/", 0) != 0 && req.path.rfind("/fn/", 0) != 0 &&
- req.path != "/healthz") {
- sendJson(res, 404, errorBody("not_found", "not served on this host"));
- return httplib::Server::HandlerResponse::Handled;
- }
- }
- if (req.method != "OPTIONS" && req.path.rfind("/api/", 0) == 0) {
- if (!resolveKey(d_, req)) {
- sendJson(res, 401, errorBody("unauthorized", "missing or invalid credentials"));
- return httplib::Server::HandlerResponse::Handled;
- }
- }
- return httplib::Server::HandlerResponse::Unhandled;
- });
- // OUR OWN ACCESS LOG. Off unless an operator set a path.
- //
- // It carries the two halves that live in different files today: the
- // resolved caller address, which only nginx knows, and the error SLUG,
- // which only our journal knows. A fail2ban jail can therefore ban on
- // `code=unauthorized` rather than on every 401 the service emits, and the
- // address it acts on is one we resolved under the trusted-proxy rule rather
- // than whatever a header claimed.
- svr_.set_logger([this](const httplib::Request& req, const httplib::Response& res) {
- if (!accessLog().enabled()) return;
- auto snap = d_.settings.snapshot();
- AccessLogEntry e;
- e.clientIp = clientIpFor(req, *snap);
- e.method = req.method;
- e.path = req.path;
- e.status = res.status;
- e.errorCode = requestErrorCode();
- e.durationMs = requestElapsedMs();
- // The key is referenced by its stable id, NEVER the secret - the same
- // rule the rest of the service follows. An unauthenticated request
- // leaves it empty, which renders as `-`.
- if (auto key = resolveKey(d_, req)) e.keyId = key->id;
- accessLog().write(e);
- });
- svr_.set_post_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
- auto snap = d_.settings.snapshot();
- std::string responseOrigin;
- if (!snap->corsOrigins.empty() && snap->corsOrigins[0] == "*") {
- responseOrigin = "*";
- } else if (auto it = req.headers.find("Origin"); it != req.headers.end()) {
- for (const auto& a : snap->corsOrigins) if (a == it->second) { responseOrigin = it->second; break; }
- }
- if (!responseOrigin.empty()) {
- res.set_header("Access-Control-Allow-Origin", responseOrigin);
- if (responseOrigin != "*") res.set_header("Vary", "Origin");
- }
- res.set_header("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Captcha-Token, Cache-Control");
- res.set_header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
- });
- svr_.Options(R"(.*)", [](const httplib::Request&, httplib::Response& res) { res.status = 204; });
- registerMetaRoutes(*this);
- registerWebuiAuthRoutes(*this);
- registerProjectRoutes(*this);
- registerKeyRoutes(*this);
- registerCollectionRoutes(*this);
- registerIndexRoutes(*this);
- registerCollectionSchemaRoutes(*this);
- registerDocumentRoutes(*this);
- registerVectorRoutes(*this);
- registerStatsRoutes(*this);
- registerSettingsRoutes(*this);
- registerProjectSettingsRoutes(*this);
- registerProjectSecretRoutes(*this);
- registerFileRoutes(*this);
- registerExportRoutes(*this);
- registerRelationRoutes(*this);
- registerFunctionRoutes(*this);
- // LAST. Function dispatch owns /fn/* , and registering it after the
- // built-in routes means a user function can never shadow one of them even
- // if cpp-httplib's matching order ever changes.
- registerFunctionDispatchRoutes(*this);
- if (!d_.shareDir.empty()) svr_.set_mount_point("/docs", d_.shareDir + "/docs");
- if (!d_.webuiDir.empty()) svr_.set_mount_point("/", d_.webuiDir);
- }
- void ApiServer::setThreadPoolSize(uint32_t n) {
- if (n == 0) return; // leave cpp-httplib's own default alone
- svr_.new_task_queue = [n] { return new httplib::ThreadPool(n); };
- }
- int ApiServer::bindToAnyPort(const std::string& host) { return svr_.bind_to_any_port(host); }
- void ApiServer::listenAfterBind() { svr_.listen_after_bind(); }
- bool ApiServer::listen(const std::string& host, uint16_t port) { return svr_.listen(host, port); }
- void ApiServer::stop() { svr_.stop(); }
- } // namespace svapi
|