From c33eebc5a66b7c8fe6374d26387d296a67df200d Mon Sep 17 00:00:00 2001 From: Mike Pasarella <80829054+jasmaine@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:12:55 +0100 Subject: [PATCH] feat(server): add --api-key, --api-key-file and --cors-origins (#2367) Co-authored-by: leejet --- examples/server/CMakeLists.txt | 1 + examples/server/README.md | 23 ++++ examples/server/async_jobs.cpp | 2 +- examples/server/main.cpp | 23 +--- examples/server/runtime.cpp | 7 +- examples/server/runtime.h | 7 ++ examples/server/server_access.cpp | 199 ++++++++++++++++++++++++++++++ examples/server/server_access.h | 15 +++ 8 files changed, 253 insertions(+), 24 deletions(-) create mode 100644 examples/server/server_access.cpp create mode 100644 examples/server/server_access.h diff --git a/examples/server/CMakeLists.txt b/examples/server/CMakeLists.txt index 6246a57f..5d2f928d 100644 --- a/examples/server/CMakeLists.txt +++ b/examples/server/CMakeLists.txt @@ -68,6 +68,7 @@ add_executable(${TARGET} ../common/media_io.cpp ../common/media_metadata.cpp main.cpp + server_access.cpp runtime.cpp model_catalog.cpp routes_models.cpp diff --git a/examples/server/README.md b/examples/server/README.md index b8c91c97..3ab90012 100644 --- a/examples/server/README.md +++ b/examples/server/README.md @@ -437,6 +437,29 @@ configured defaults. | `--max-pending-jobs ` | `64` | Maximum async jobs queued or generating | | `--completed-ttl-seconds ` | `600` | Retention time for completed async jobs | +### Access + +By default any program on the machine, and any web page open in a browser on +it, can call the server. To limit that: + +| Option | Default | Purpose | +| --- | --- | --- | +| `--api-key ` | none | Key clients must send as `Authorization: Bearer ` or `X-Api-Key: `. Separate multiple keys with commas. | +| `--api-key-file ` | none | The same, one key per line, so keys don't show in the process list | +| `--cors-origins ` | any | Web origins allowed to read the server's answers in a browser, comma-separated | + +With a key, the page at `/` still loads, but the bundled Web UI can't send +the key, so its calls get `401`; it is meant for use without a key. +Authentication failures return `401` with a `WWW-Authenticate` Bearer challenge. +Protected responses include `Cache-Control: no-store`. + +`--cors-origins` only decides which web pages may read the answers: other +pages get no CORS headers, but their requests still reach the server. To +refuse requests, set a key as well. + +Startup fails if an access option is missing its value, a list is empty +(such as `--api-key ,`), or the key file contains no keys. + ### Idle weight release | Option | Default | Memory released when idle | diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp index ac9318f1..b521be53 100644 --- a/examples/server/async_jobs.cpp +++ b/examples/server/async_jobs.cpp @@ -698,7 +698,7 @@ static sd_status_t execute_dgl_job(ServerRuntime& runtime, { std::lock_guard lock(*runtime.sd_ctx_mutex); if (job.cancel_requested.load()) - return false; + return SD_STATUS_CANCELLED; JobCancellationMonitor cancellation(job, [ctx = runtime.sd_ctx]() { sd_dgl_ctx_cancel(sd_ctx_get_dgl_ctx(ctx)); }); diff --git a/examples/server/main.cpp b/examples/server/main.cpp index b0b44cce..24a38332 100644 --- a/examples/server/main.cpp +++ b/examples/server/main.cpp @@ -5,7 +5,8 @@ #include #include -#include "httplib.h" +// cpp-httplib must include Winsock2 before other headers include windows.h. +#include "server_access.h" #include "async_jobs.h" #include "common/common.h" @@ -39,6 +40,7 @@ static void parse_args(int argc, ctx_params.get_options(), default_gen_params.get_options(), }; + svr_params.add_access_options(options_vec[0], options_vec); if (!parse_options(argc, argv, options_vec)) { print_usage(argv[0], options_vec); @@ -140,24 +142,7 @@ int main(int argc, const char** argv) { std::thread async_worker(async_job_worker, std::ref(runtime)); - httplib::Server svr; - - svr.set_pre_routing_handler([](const httplib::Request& req, httplib::Response& res) { - std::string origin = req.get_header_value("Origin"); - if (origin.empty()) { - origin = "*"; - } - res.set_header("Access-Control-Allow-Origin", origin); - res.set_header("Access-Control-Allow-Credentials", "true"); - res.set_header("Access-Control-Allow-Methods", "*"); - res.set_header("Access-Control-Allow-Headers", "*"); - - if (req.method == "OPTIONS") { - res.status = 204; - return httplib::Server::HandlerResponse::Handled; - } - return httplib::Server::HandlerResponse::Unhandled; - }); + SDHttpServer svr(svr_params); std::string index_html; #ifdef HAVE_INDEX_HTML diff --git a/examples/server/runtime.cpp b/examples/server/runtime.cpp index 46cd87a1..120b8de0 100644 --- a/examples/server/runtime.cpp +++ b/examples/server/runtime.cpp @@ -383,10 +383,7 @@ bool SDSvrParams::validate() { } bool SDSvrParams::resolve_and_validate() { - if (!validate()) { - return false; - } - return true; + return validate() && load_api_keys(); } std::string SDSvrParams::to_string() const { @@ -401,6 +398,8 @@ std::string SDSvrParams::to_string() const { << " weight_residency_ttl: " << weight_residency_ttl << ",\n" << " serve_html_path: \"" << serve_html_path << "\",\n" << " dgl_dir: \"" << dgl_dir << "\",\n" + << " api_keys: " << api_keys.size() << ",\n" + << " cors_origins: " << cors_origins.size() << ",\n" << "}"; return oss.str(); } diff --git a/examples/server/runtime.h b/examples/server/runtime.h index dbd8a7a7..debf97cb 100644 --- a/examples/server/runtime.h +++ b/examples/server/runtime.h @@ -29,14 +29,21 @@ struct SDSvrParams { std::string serve_html_path; std::string dgl_dir = "dgl"; std::vector model_dirs; + std::vector api_keys; + std::string api_key_file; + std::vector cors_origins; bool normal_exit = false; sd_log_level_t log_level = SD_LOG_INFO; bool color = false; ArgOptions get_options(); + void add_access_options(ArgOptions& options, const std::vector& groups); bool validate(); bool resolve_and_validate(); std::string to_string() const; + +private: + bool load_api_keys(); }; struct LoraEntry { diff --git a/examples/server/server_access.cpp b/examples/server/server_access.cpp new file mode 100644 index 00000000..1bd0aaf8 --- /dev/null +++ b/examples/server/server_access.cpp @@ -0,0 +1,199 @@ +#include "server_access.h" + +#include +#include +#include +#include +#include +#include + +#include "runtime.h" + +static bool is_registered_option(const std::vector& groups, std::string_view name) { + const auto contains = [name](const auto& options) { + return std::any_of(options.begin(), options.end(), [name](const auto& option) { + return name == option.short_name || name == option.long_name; + }); + }; + return std::any_of(groups.begin(), groups.end(), [&](const ArgOptions& options) { + return contains(options.string_options) || contains(options.int_options) || + contains(options.float_options) || contains(options.bool_options) || + contains(options.manual_options); + }); +} + +static bool append_option_list(const char* name, const char* value, const char* entry_name, std::vector& values) { + std::istringstream input(value); + const auto previous_count = values.size(); + for (std::string entry; std::getline(input, entry, ',');) { + if (!entry.empty()) { + values.push_back(entry); + } + } + if (values.size() == previous_count) { + LOG_ERROR("error: %s needs at least one %s", name, entry_name); + return false; + } + return true; +} + +void SDSvrParams::add_access_options(ArgOptions& options, const std::vector& groups) { + const auto add_option = [&](const char* name, const char* description, auto apply) { + const auto parse_value = [&groups, apply](int argc, const char** argv, int index, bool& error_reported) { + const int value_index = index + 1; + if (value_index >= argc || !argv[value_index][0] || is_registered_option(groups, argv[value_index])) { + LOG_ERROR("error: missing value for argument \"%s\"", argv[index]); + error_reported = true; + return -1; + } + return apply(value_index, argv) ? 1 : -1; + }; + options.manual_options.push_back({"", name, description, parse_value}); + }; + add_option("--api-key", "API key clients must send (Authorization: Bearer KEY or X-Api-Key); comma-separated for several", + [this](int index, const char** argv) { + return append_option_list(argv[index - 1], argv[index], "key", api_keys); + }); + add_option("--api-key-file", "file with API keys, one per line (keeps them off the command line)", + [this](int index, const char** argv) { + api_key_file = argv_to_utf8(index, argv); + return true; + }); + add_option("--cors-origins", "web origins allowed to read cross-origin responses, comma-separated (default: any)", + [this](int index, const char** argv) { + return append_option_list(argv[index - 1], argv[index], "origin", cors_origins); + }); +} + +bool SDSvrParams::load_api_keys() { + if (api_key_file.empty()) { + return true; + } + std::ifstream file(std::filesystem::u8path(api_key_file)); + if (!file) { + LOG_ERROR("error: can't read api_key_file: %s", api_key_file.c_str()); + return false; + } + const auto previous_count = api_keys.size(); + for (std::string line; std::getline(file, line);) { + const auto last = line.find_last_not_of(" \t\r\n"); + if (last != std::string::npos) { + const auto first = line.find_first_not_of(" \t"); + api_keys.push_back(line.substr(first, last - first + 1)); + } + } + if (api_keys.size() == previous_count) { + LOG_ERROR("error: api_key_file has no keys: %s", api_key_file.c_str()); + return false; + } + return true; +} + +static bool requires_api_key(const SDSvrParams& params, const httplib::Request& req) { + return !params.api_keys.empty() && req.method != "OPTIONS" && !(req.method == "GET" && req.path == "/"); +} + +static bool api_key_matches(const std::vector& keys, std::string_view key) { + bool found = false; + // Compare every byte of every configured key without a prefix-dependent early return. + for (const auto& configured_key : keys) { + unsigned char diff = configured_key.size() != key.size(); + for (size_t i = 0; i < configured_key.size(); i++) { + diff |= static_cast(configured_key[i] ^ (i < key.size() ? key[i] : 0)); + } + found |= diff == 0; + } + return found; +} + +static bool has_valid_api_key(const httplib::Request& req, const std::vector& keys) { + const auto key = req.get_header_value("X-Api-Key"); + if (!key.empty()) { + return api_key_matches(keys, key); + } + + constexpr std::string_view scheme = "bearer"; + const auto auth = req.get_header_value("Authorization"); + const auto separator = auth.find(' '); + if (separator != scheme.size() || + !std::equal(scheme.begin(), scheme.end(), auth.begin(), [](char expected, unsigned char actual) { + return expected == std::tolower(actual); + })) { + return false; + } + const auto key_start = auth.find_first_not_of(' ', separator); + return key_start != std::string::npos && api_key_matches(keys, std::string_view(auth).substr(key_start)); +} + +static void set_cors_headers(const httplib::Request& req, httplib::Response& res, const std::vector& allowed) { + const bool preflight = req.method == "OPTIONS"; + res.set_header("Vary", preflight ? "Origin, Access-Control-Request-Headers" : "Origin"); + + const auto origin = req.get_header_value("Origin"); + if (!allowed.empty() && std::find(allowed.begin(), allowed.end(), origin) == allowed.end()) { + return; + } + res.set_header("Access-Control-Allow-Origin", origin.empty() ? "*" : origin); + res.set_header("Access-Control-Allow-Credentials", "true"); + res.set_header("Access-Control-Allow-Methods", "*"); + const auto headers = preflight ? req.get_header_value("Access-Control-Request-Headers") : std::string{}; + res.set_header("Access-Control-Allow-Headers", headers.empty() ? "*" : headers); +} + +SDHttpServer::SDHttpServer(const SDSvrParams& params) { + set_pre_routing_handler([¶ms](const httplib::Request& req, httplib::Response& res) { + if (req.method == "OPTIONS") { + close_after_response_ = req.has_header("Transfer-Encoding") || req.get_header_value_u64("Content-Length") > 0; + res.status = 204; + return HandlerResponse::Handled; + } + if (requires_api_key(params, req) && !has_valid_api_key(req, params.api_keys)) { + res.status = 401; + res.set_header("WWW-Authenticate", "Bearer realm=\"sd-server\""); + res.set_content(R"({"error":{"code":401,"message":"Invalid API Key","type":"authentication_error"}})", + "application/json"); + close_after_response_ = true; + return HandlerResponse::Handled; + } + return HandlerResponse::Unhandled; + }); + + set_post_routing_handler([¶ms](const httplib::Request& req, httplib::Response& res) { + if (close_after_response_) { + res.headers.erase("Connection"); + res.headers.erase("Keep-Alive"); + res.set_header("Connection", "close"); + } + if (requires_api_key(params, req)) { + res.headers.erase("Cache-Control"); + res.set_header("Cache-Control", "no-store"); + } + set_cors_headers(req, res, params.cors_origins); + }); +} + +thread_local bool SDHttpServer::close_after_response_ = false; + +// cpp-httplib can send Connection: close without stopping its keep-alive loop. +// Stop the loop after early responses so unread request bytes are discarded. +bool SDHttpServer::process_and_close_socket(socket_t socket) { + std::string remote_addr; + std::string local_addr; + int remote_port = 0; + int local_port = 0; + httplib::detail::get_remote_ip_and_port(socket, remote_addr, remote_port); + httplib::detail::get_local_ip_and_port(socket, local_addr, local_port); + const bool result = httplib::detail::process_server_socket( + svr_sock_, socket, keep_alive_max_count_, keep_alive_timeout_sec_, + read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, write_timeout_usec_, + [&](httplib::Stream& stream, bool close_connection, bool& connection_closed) { + close_after_response_ = false; + const bool written = process_request(stream, remote_addr, remote_port, local_addr, + local_port, close_connection, connection_closed, nullptr); + connection_closed |= close_after_response_; + return written; + }); + httplib::detail::shutdown_socket(socket); + httplib::detail::close_socket(socket); + return result; +} diff --git a/examples/server/server_access.h b/examples/server/server_access.h new file mode 100644 index 00000000..074aabac --- /dev/null +++ b/examples/server/server_access.h @@ -0,0 +1,15 @@ +#pragma once + +#include "httplib.h" + +struct SDSvrParams; + +class SDHttpServer final : public httplib::Server { +public: + explicit SDHttpServer(const SDSvrParams& params); + +private: + bool process_and_close_socket(socket_t socket) override; + + static thread_local bool close_after_response_; +};