From 54cbb335a8f2a22c26f0dd1eb11a130ce18df781 Mon Sep 17 00:00:00 2001 From: Mike Pasarella Date: Mon, 16 Nov 2026 11:31:42 +0100 Subject: [PATCH 1/5] feat(server): add --api-key, --api-key-file and --cors-origins --- examples/server/README.md | 11 ++++++++ examples/server/main.cpp | 49 ++++++++++++++++++++++++++++------ examples/server/runtime.cpp | 53 +++++++++++++++++++++++++++++++++++++ examples/server/runtime.h | 5 ++++ 4 files changed, 110 insertions(+), 8 deletions(-) diff --git a/examples/server/README.md b/examples/server/README.md index 8673eb80c4..f57fc3f6af 100644 --- a/examples/server/README.md +++ b/examples/server/README.md @@ -420,6 +420,17 @@ 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: `; comma-separated for several. Requests without a valid key get `401`. The web page at `/` stays open. | +| `--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 call the server, comma-separated; others get no CORS headers, so browsers keep their pages out | + ### Logging Logging defaults to `info`. Use `--log-level ` to select `debug`, `verbose`, diff --git a/examples/server/main.cpp b/examples/server/main.cpp index 391a1ec9ad..8414e15ba7 100644 --- a/examples/server/main.cpp +++ b/examples/server/main.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -62,6 +63,20 @@ static void parse_args(int argc, } } +// api_key_matches compares in constant time, so the answer's timing +// doesn't tell how much of a key was right. +static bool api_key_matches(const std::vector& keys, const std::string& key) { + bool found = false; + for (const auto& k : keys) { + unsigned char diff = k.size() != key.size(); + for (size_t i = 0; i < k.size(); i++) { + diff |= static_cast(k[i] ^ (i < key.size() ? key[i] : 0)); + } + found |= diff == 0; + } + return found; +} + void sd_log_cb(enum sd_log_level_t level, const char* log, void* data) { SDSvrParams* svr_params = (SDSvrParams*)data; log_print(level, log, svr_params->log_level, svr_params->color); @@ -136,20 +151,38 @@ int main(int argc, const char** argv) { 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 = "*"; + svr.set_pre_routing_handler([&svr_params](const httplib::Request& req, httplib::Response& res) { + // CORS: with --cors-origins only those origins get the headers, so a + // browser keeps other web pages out; without it, any origin (as before). + const auto& allowed = svr_params.cors_origins; + std::string origin = req.get_header_value("Origin"); + if (allowed.empty() || std::find(allowed.begin(), allowed.end(), origin) != allowed.end()) { + 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", "*"); + res.set_header("Access-Control-Allow-Headers", "*"); } - 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; } + + // API key: every request but the web page itself needs one. + if (!svr_params.api_keys.empty() && !(req.method == "GET" && req.path == "/")) { + std::string key = req.get_header_value("X-Api-Key"); + const std::string auth = req.get_header_value("Authorization"); + const std::string bearer = "Bearer "; + if (key.empty() && auth.compare(0, bearer.size(), bearer) == 0) { + key = auth.substr(bearer.size()); + } + if (!api_key_matches(svr_params.api_keys, key)) { + res.status = 401; + res.set_content(R"({"error":{"code":401,"message":"Invalid API Key","type":"authentication_error"}})", + "application/json"); + return httplib::Server::HandlerResponse::Handled; + } + } return httplib::Server::HandlerResponse::Unhandled; }); diff --git a/examples/server/runtime.cpp b/examples/server/runtime.cpp index 6ac3866c77..06a04c54e8 100644 --- a/examples/server/runtime.cpp +++ b/examples/server/runtime.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -392,8 +393,39 @@ ArgOptions SDSvrParams::get_options() { return -1; }; + auto split_list = [](const char* arg, std::vector& out) { + std::stringstream ss(arg); + std::string item; + while (std::getline(ss, item, ',')) { + if (!item.empty()) { + out.push_back(item); + } + } + }; + options.manual_options = { {"-h", "--help", "show this help message and exit", on_help_arg}, + {"", "--api-key", "API key clients must send (Authorization: Bearer KEY or X-Api-Key); comma-separated for several", + [this, split_list](int argc, const char** argv, int index) { + if (++index >= argc || argv[index][0] == '\0') + return -1; + split_list(argv[index], api_keys); + return 1; + }}, + {"", "--api-key-file", "file with API keys, one per line (keeps them off the command line)", + [this](int argc, const char** argv, int index) { + if (++index >= argc || argv[index][0] == '\0') + return -1; + api_key_file = argv_to_utf8(index, argv); + return 1; + }}, + {"", "--cors-origins", "web origins allowed to call the server, comma-separated (default: any)", + [this, split_list](int argc, const char** argv, int index) { + if (++index >= argc || argv[index][0] == '\0') + return -1; + split_list(argv[index], cors_origins); + return 1; + }}, {"", "--model-dir", "model root; repeat to search multiple directories (default: models)", [this](int argc, const char** argv, int index) { if (++index >= argc || argv[index][0] == '\0') @@ -438,6 +470,25 @@ bool SDSvrParams::resolve_and_validate() { if (!validate()) { return false; } + if (!api_key_file.empty()) { + std::ifstream file(fs::u8path(api_key_file)); + if (!file) { + LOG_ERROR("error: can't read api_key_file: %s", api_key_file.c_str()); + return false; + } + std::string line; + while (std::getline(file, line)) { + line.erase(line.find_last_not_of(" \t\r\n") + 1); + line.erase(0, line.find_first_not_of(" \t")); + if (!line.empty()) { + api_keys.push_back(line); + } + } + if (api_keys.empty()) { + LOG_ERROR("error: api_key_file has no keys: %s", api_key_file.c_str()); + return false; + } + } return true; } @@ -450,6 +501,8 @@ std::string SDSvrParams::to_string() const { << " max_pending_jobs: " << max_pending_jobs << ",\n" << " completed_ttl_seconds: " << completed_ttl_seconds << ",\n" << " serve_html_path: \"" << serve_html_path << "\",\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 abb9766f71..d6f6cbaa12 100644 --- a/examples/server/runtime.h +++ b/examples/server/runtime.h @@ -26,6 +26,11 @@ struct SDSvrParams { int completed_ttl_seconds = 600; std::string serve_html_path; std::vector model_dirs; + // Access: keys clients must send, and the web origins that may call the + // server. Empty: no key needed, any origin (as before). + 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; From 0fade58ede17f72827ea4b9fa0cd51e6f86688a5 Mon Sep 17 00:00:00 2001 From: Mike Pasarella Date: Mon, 16 Nov 2026 11:53:44 +0100 Subject: [PATCH 2/5] fix(server): address review of the access options - allow the headers a preflight asks for (Authorization isn't covered by a wildcard when credentials are allowed) - an empty --api-key or --cors-origins list, or a key file without keys, stops the server at startup instead of leaving it open - README: the bundled Web UI can't send a key; --cors-origins limits who may read answers, a key is what refuses requests --- examples/server/README.md | 14 ++++++++++++-- examples/server/main.cpp | 5 ++++- examples/server/runtime.cpp | 19 ++++++++++++++++--- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/examples/server/README.md b/examples/server/README.md index f57fc3f6af..f654ed5f83 100644 --- a/examples/server/README.md +++ b/examples/server/README.md @@ -427,9 +427,19 @@ 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: `; comma-separated for several. Requests without a valid key get `401`. The web page at `/` stays open. | +| `--api-key ` | none | Key clients must send as `Authorization: Bearer ` or `X-Api-Key: `; comma-separated for several. Requests without a valid key get `401`. | | `--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 call the server, comma-separated; others get no CORS headers, so browsers keep their pages out | +| `--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. + +`--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. + +An empty list (such as `--api-key ,`) or a key file without keys stops the +server at startup instead of leaving it open. ### Logging diff --git a/examples/server/main.cpp b/examples/server/main.cpp index 8414e15ba7..3daeec77f0 100644 --- a/examples/server/main.cpp +++ b/examples/server/main.cpp @@ -160,7 +160,10 @@ int main(int argc, const char** argv) { 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", "*"); - res.set_header("Access-Control-Allow-Headers", "*"); + // With credentials, browsers take "*" literally and never let + // Authorization through a wildcard: name the headers asked for. + std::string headers = req.get_header_value("Access-Control-Request-Headers"); + res.set_header("Access-Control-Allow-Headers", headers.empty() ? "*" : headers); } if (req.method == "OPTIONS") { diff --git a/examples/server/runtime.cpp b/examples/server/runtime.cpp index 06a04c54e8..2877fcf0eb 100644 --- a/examples/server/runtime.cpp +++ b/examples/server/runtime.cpp @@ -393,14 +393,20 @@ ArgOptions SDSvrParams::get_options() { return -1; }; + // split_list adds the comma-separated entries of arg to out; a list + // without any entry (like ",") is an error, so a restriction can't + // silently turn into none. auto split_list = [](const char* arg, std::vector& out) { std::stringstream ss(arg); std::string item; + size_t added = 0; while (std::getline(ss, item, ',')) { if (!item.empty()) { out.push_back(item); + added++; } } + return added > 0; }; options.manual_options = { @@ -409,7 +415,10 @@ ArgOptions SDSvrParams::get_options() { [this, split_list](int argc, const char** argv, int index) { if (++index >= argc || argv[index][0] == '\0') return -1; - split_list(argv[index], api_keys); + if (!split_list(argv[index], api_keys)) { + LOG_ERROR("error: --api-key needs at least one key"); + return -1; + } return 1; }}, {"", "--api-key-file", "file with API keys, one per line (keeps them off the command line)", @@ -423,7 +432,10 @@ ArgOptions SDSvrParams::get_options() { [this, split_list](int argc, const char** argv, int index) { if (++index >= argc || argv[index][0] == '\0') return -1; - split_list(argv[index], cors_origins); + if (!split_list(argv[index], cors_origins)) { + LOG_ERROR("error: --cors-origins needs at least one origin"); + return -1; + } return 1; }}, {"", "--model-dir", "model root; repeat to search multiple directories (default: models)", @@ -477,6 +489,7 @@ bool SDSvrParams::resolve_and_validate() { return false; } std::string line; + const size_t before = api_keys.size(); while (std::getline(file, line)) { line.erase(line.find_last_not_of(" \t\r\n") + 1); line.erase(0, line.find_first_not_of(" \t")); @@ -484,7 +497,7 @@ bool SDSvrParams::resolve_and_validate() { api_keys.push_back(line); } } - if (api_keys.empty()) { + if (api_keys.size() == before) { LOG_ERROR("error: api_key_file has no keys: %s", api_key_file.c_str()); return false; } From 9b4f86e42a1be29c5e723f372288548d201ef75d Mon Sep 17 00:00:00 2001 From: leejet Date: Wed, 25 Nov 2026 22:39:02 +0800 Subject: [PATCH 3/5] fix(server): harden API key authentication and CORS --- examples/common/common.cpp | 31 +++++++- examples/common/common.h | 1 + examples/server/README.md | 8 +- examples/server/main.cpp | 154 ++++++++++++++++++++++++++---------- examples/server/runtime.cpp | 29 +++---- 5 files changed, 162 insertions(+), 61 deletions(-) diff --git a/examples/common/common.cpp b/examples/common/common.cpp index 9beaaa525b..b5d7230ebc 100644 --- a/examples/common/common.cpp +++ b/examples/common/common.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -244,10 +245,13 @@ bool parse_options(int argc, const char** argv, const std::vector& o bool invalid_arg = false; std::string arg; + auto matches_name = [](const auto& option, std::string_view name) { + return (!option.short_name.empty() && name == option.short_name) || + (!option.long_name.empty() && name == option.long_name); + }; auto match_and_apply = [&](auto& opts, auto&& apply_fn) -> bool { for (auto& option : opts) { - if ((option.short_name.size() > 0 && arg == option.short_name) || - (option.long_name.size() > 0 && arg == option.long_name)) { + if (matches_name(option, arg)) { apply_fn(option); return true; } @@ -255,10 +259,24 @@ bool parse_options(int argc, const char** argv, const std::vector& o return false; }; + auto is_option = [&](std::string_view name) { + auto contains_name = [&](const auto& options) { + return std::any_of(options.begin(), options.end(), [&](const auto& option) { + return matches_name(option, name); + }); + }; + return std::any_of(options_list.begin(), options_list.end(), [&](const ArgOptions& options) { + return contains_name(options.string_options) || contains_name(options.int_options) || + contains_name(options.float_options) || contains_name(options.bool_options) || + contains_name(options.manual_options); + }); + }; + bool valid = false; for (int i = 1; i < argc; i++) { arg = argv[i]; bool found_arg = false; + bool missing_value = false; for (auto& options : options_list) { if (match_and_apply(options.string_options, [&](auto& option) { @@ -313,6 +331,11 @@ bool parse_options(int argc, const char** argv, const std::vector& o break; if (match_and_apply(options.manual_options, [&](auto& option) { + if (option.requires_value && + (i + 1 >= argc || argv[i + 1][0] == '\0' || is_option(argv[i + 1]))) { + missing_value = true; + return; + } int ret = option.cb(argc, argv, i, valid); if (ret < 0) { invalid_arg = true; @@ -324,6 +347,10 @@ bool parse_options(int argc, const char** argv, const std::vector& o break; } + if (missing_value) { + LOG_ERROR("error: missing value for argument \"%s\"", arg.c_str()); + return false; + } if (invalid_arg) { if (!valid) { LOG_ERROR("error: invalid parameter for argument \"%s\": \"%s\"", diff --git a/examples/common/common.h b/examples/common/common.h index f4418adf4d..2f553b2a9e 100644 --- a/examples/common/common.h +++ b/examples/common/common.h @@ -100,6 +100,7 @@ struct ManualOption { std::string long_name; std::string desc; ManualFunction cb; + bool requires_value = false; }; struct ArgOptions { diff --git a/examples/server/README.md b/examples/server/README.md index b627deac44..3ab90012ca 100644 --- a/examples/server/README.md +++ b/examples/server/README.md @@ -444,19 +444,21 @@ 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: `; comma-separated for several. Requests without a valid key get `401`. | +| `--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. -An empty list (such as `--api-key ,`) or a key file without keys stops the -server at startup instead of leaving it open. +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 diff --git a/examples/server/main.cpp b/examples/server/main.cpp index ebe0294a7c..c8c8b09a2c 100644 --- a/examples/server/main.cpp +++ b/examples/server/main.cpp @@ -1,8 +1,10 @@ #include +#include #include #include #include #include +#include #include #include @@ -65,7 +67,7 @@ static void parse_args(int argc, // api_key_matches compares in constant time, so the answer's timing // doesn't tell how much of a key was right. -static bool api_key_matches(const std::vector& keys, const std::string& key) { +static bool api_key_matches(const std::vector& keys, std::string_view key) { bool found = false; for (const auto& k : keys) { unsigned char diff = k.size() != key.size(); @@ -77,6 +79,115 @@ static bool api_key_matches(const std::vector& keys, const std::str return found; } +static bool needs_api_key(const httplib::Request& req) { + return req.method != "OPTIONS" && !(req.method == "GET" && req.path == "/"); +} + +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)); +} + +class SDHttpServer final : public httplib::Server { +public: + void close_after_response() { + close_after_response_ = true; + } + + bool will_close_after_response() const { + return close_after_response_; + } + +private: + // cpp-httplib writes Connection: close for errors but does not stop its + // keep-alive loop when a handler rejects a request before reading the body. + bool process_and_close_socket(socket_t socket) override { + 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; + } + + static inline thread_local bool close_after_response_ = false; +}; + +static void configure_server_access(SDHttpServer& svr, const SDSvrParams& params) { + using HandlerResponse = httplib::Server::HandlerResponse; + + svr.set_pre_routing_handler([&svr, ¶ms](const httplib::Request& req, httplib::Response& res) { + if (req.method == "OPTIONS") { + if (req.has_header("Transfer-Encoding") || req.get_header_value_u64("Content-Length") > 0) { + svr.close_after_response(); + } + res.status = 204; + return HandlerResponse::Handled; + } + if (!params.api_keys.empty() && needs_api_key(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"); + svr.close_after_response(); + return HandlerResponse::Handled; + } + return HandlerResponse::Unhandled; + }); + + svr.set_post_routing_handler([&svr, ¶ms](const httplib::Request& req, httplib::Response& res) { + if (svr.will_close_after_response()) { + res.headers.erase("Connection"); + res.headers.erase("Keep-Alive"); + res.set_header("Connection", "close"); + } + if (!params.api_keys.empty() && needs_api_key(req)) { + res.headers.erase("Cache-Control"); + res.set_header("Cache-Control", "no-store"); + } + + const bool preflight = req.method == "OPTIONS"; + res.set_header("Vary", preflight ? "Origin, Access-Control-Request-Headers" : "Origin"); + + const auto& allowed = params.cors_origins; + const auto origin = req.get_header_value("Origin"); + if (allowed.empty() || std::find(allowed.begin(), allowed.end(), origin) != allowed.end()) { + 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); + } + }); +} + void sd_log_cb(enum sd_log_level_t level, const char* log, void* data) { SDSvrParams* svr_params = (SDSvrParams*)data; log_print(level, log, svr_params->log_level, svr_params->color); @@ -155,45 +266,8 @@ 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([&svr_params](const httplib::Request& req, httplib::Response& res) { - // CORS: with --cors-origins only those origins get the headers, so a - // browser keeps other web pages out; without it, any origin (as before). - const auto& allowed = svr_params.cors_origins; - std::string origin = req.get_header_value("Origin"); - if (allowed.empty() || std::find(allowed.begin(), allowed.end(), origin) != allowed.end()) { - 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", "*"); - // With credentials, browsers take "*" literally and never let - // Authorization through a wildcard: name the headers asked for. - std::string headers = req.get_header_value("Access-Control-Request-Headers"); - res.set_header("Access-Control-Allow-Headers", headers.empty() ? "*" : headers); - } - - if (req.method == "OPTIONS") { - res.status = 204; - return httplib::Server::HandlerResponse::Handled; - } - - // API key: every request but the web page itself needs one. - if (!svr_params.api_keys.empty() && !(req.method == "GET" && req.path == "/")) { - std::string key = req.get_header_value("X-Api-Key"); - const std::string auth = req.get_header_value("Authorization"); - const std::string bearer = "Bearer "; - if (key.empty() && auth.compare(0, bearer.size(), bearer) == 0) { - key = auth.substr(bearer.size()); - } - if (!api_key_matches(svr_params.api_keys, key)) { - res.status = 401; - res.set_content(R"({"error":{"code":401,"message":"Invalid API Key","type":"authentication_error"}})", - "application/json"); - return httplib::Server::HandlerResponse::Handled; - } - } - return httplib::Server::HandlerResponse::Unhandled; - }); + SDHttpServer svr; + configure_server_access(svr, svr_params); std::string index_html; #ifdef HAVE_INDEX_HTML diff --git a/examples/server/runtime.cpp b/examples/server/runtime.cpp index 21c8ef4a7b..c316ef7dad 100644 --- a/examples/server/runtime.cpp +++ b/examples/server/runtime.cpp @@ -346,32 +346,29 @@ ArgOptions SDSvrParams::get_options() { options.manual_options = { {"-h", "--help", "show this help message and exit", on_help_arg}, {"", "--api-key", "API key clients must send (Authorization: Bearer KEY or X-Api-Key); comma-separated for several", - [this, split_list](int argc, const char** argv, int index) { - if (++index >= argc || argv[index][0] == '\0') - return -1; - if (!split_list(argv[index], api_keys)) { + [this, split_list](int, const char** argv, int index) { + if (!split_list(argv[index + 1], api_keys)) { LOG_ERROR("error: --api-key needs at least one key"); return -1; } return 1; - }}, + }, + true}, {"", "--api-key-file", "file with API keys, one per line (keeps them off the command line)", - [this](int argc, const char** argv, int index) { - if (++index >= argc || argv[index][0] == '\0') - return -1; - api_key_file = argv_to_utf8(index, argv); + [this](int, const char** argv, int index) { + api_key_file = argv_to_utf8(index + 1, argv); return 1; - }}, - {"", "--cors-origins", "web origins allowed to call the server, comma-separated (default: any)", - [this, split_list](int argc, const char** argv, int index) { - if (++index >= argc || argv[index][0] == '\0') - return -1; - if (!split_list(argv[index], cors_origins)) { + }, + true}, + {"", "--cors-origins", "web origins allowed to read cross-origin responses, comma-separated (default: any)", + [this, split_list](int, const char** argv, int index) { + if (!split_list(argv[index + 1], cors_origins)) { LOG_ERROR("error: --cors-origins needs at least one origin"); return -1; } return 1; - }}, + }, + true}, {"", "--weight-staging-ttl", "idle seconds before releasing GPU staging copies of RAM weights (-1 disabled, 0 immediate; default: -1)", [this](int argc, const char** argv, int index) { From b9be08729245cfc3ff6e8183ee269895c106b728 Mon Sep 17 00:00:00 2001 From: leejet Date: Wed, 25 Nov 2026 22:49:27 +0800 Subject: [PATCH 4/5] refactor(server): move access control into a dedicated module --- examples/common/common.cpp | 31 +---- examples/common/common.h | 1 - examples/server/CMakeLists.txt | 1 + examples/server/main.cpp | 133 +------------------- examples/server/runtime.cpp | 66 +--------- examples/server/runtime.h | 6 +- examples/server/server_access.cpp | 199 ++++++++++++++++++++++++++++++ examples/server/server_access.h | 15 +++ 8 files changed, 226 insertions(+), 226 deletions(-) create mode 100644 examples/server/server_access.cpp create mode 100644 examples/server/server_access.h diff --git a/examples/common/common.cpp b/examples/common/common.cpp index b5d7230ebc..9beaaa525b 100644 --- a/examples/common/common.cpp +++ b/examples/common/common.cpp @@ -12,7 +12,6 @@ #include #include #include -#include #include #include @@ -245,13 +244,10 @@ bool parse_options(int argc, const char** argv, const std::vector& o bool invalid_arg = false; std::string arg; - auto matches_name = [](const auto& option, std::string_view name) { - return (!option.short_name.empty() && name == option.short_name) || - (!option.long_name.empty() && name == option.long_name); - }; auto match_and_apply = [&](auto& opts, auto&& apply_fn) -> bool { for (auto& option : opts) { - if (matches_name(option, arg)) { + if ((option.short_name.size() > 0 && arg == option.short_name) || + (option.long_name.size() > 0 && arg == option.long_name)) { apply_fn(option); return true; } @@ -259,24 +255,10 @@ bool parse_options(int argc, const char** argv, const std::vector& o return false; }; - auto is_option = [&](std::string_view name) { - auto contains_name = [&](const auto& options) { - return std::any_of(options.begin(), options.end(), [&](const auto& option) { - return matches_name(option, name); - }); - }; - return std::any_of(options_list.begin(), options_list.end(), [&](const ArgOptions& options) { - return contains_name(options.string_options) || contains_name(options.int_options) || - contains_name(options.float_options) || contains_name(options.bool_options) || - contains_name(options.manual_options); - }); - }; - bool valid = false; for (int i = 1; i < argc; i++) { arg = argv[i]; bool found_arg = false; - bool missing_value = false; for (auto& options : options_list) { if (match_and_apply(options.string_options, [&](auto& option) { @@ -331,11 +313,6 @@ bool parse_options(int argc, const char** argv, const std::vector& o break; if (match_and_apply(options.manual_options, [&](auto& option) { - if (option.requires_value && - (i + 1 >= argc || argv[i + 1][0] == '\0' || is_option(argv[i + 1]))) { - missing_value = true; - return; - } int ret = option.cb(argc, argv, i, valid); if (ret < 0) { invalid_arg = true; @@ -347,10 +324,6 @@ bool parse_options(int argc, const char** argv, const std::vector& o break; } - if (missing_value) { - LOG_ERROR("error: missing value for argument \"%s\"", arg.c_str()); - return false; - } if (invalid_arg) { if (!valid) { LOG_ERROR("error: invalid parameter for argument \"%s\": \"%s\"", diff --git a/examples/common/common.h b/examples/common/common.h index 2f553b2a9e..f4418adf4d 100644 --- a/examples/common/common.h +++ b/examples/common/common.h @@ -100,7 +100,6 @@ struct ManualOption { std::string long_name; std::string desc; ManualFunction cb; - bool requires_value = false; }; struct ArgOptions { diff --git a/examples/server/CMakeLists.txt b/examples/server/CMakeLists.txt index 6246a57f7a..5d2f928db1 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/main.cpp b/examples/server/main.cpp index c8c8b09a2c..24a383321b 100644 --- a/examples/server/main.cpp +++ b/examples/server/main.cpp @@ -1,14 +1,12 @@ -#include -#include #include #include #include #include -#include #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" @@ -42,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); @@ -65,129 +64,6 @@ static void parse_args(int argc, } } -// api_key_matches compares in constant time, so the answer's timing -// doesn't tell how much of a key was right. -static bool api_key_matches(const std::vector& keys, std::string_view key) { - bool found = false; - for (const auto& k : keys) { - unsigned char diff = k.size() != key.size(); - for (size_t i = 0; i < k.size(); i++) { - diff |= static_cast(k[i] ^ (i < key.size() ? key[i] : 0)); - } - found |= diff == 0; - } - return found; -} - -static bool needs_api_key(const httplib::Request& req) { - return req.method != "OPTIONS" && !(req.method == "GET" && req.path == "/"); -} - -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)); -} - -class SDHttpServer final : public httplib::Server { -public: - void close_after_response() { - close_after_response_ = true; - } - - bool will_close_after_response() const { - return close_after_response_; - } - -private: - // cpp-httplib writes Connection: close for errors but does not stop its - // keep-alive loop when a handler rejects a request before reading the body. - bool process_and_close_socket(socket_t socket) override { - 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; - } - - static inline thread_local bool close_after_response_ = false; -}; - -static void configure_server_access(SDHttpServer& svr, const SDSvrParams& params) { - using HandlerResponse = httplib::Server::HandlerResponse; - - svr.set_pre_routing_handler([&svr, ¶ms](const httplib::Request& req, httplib::Response& res) { - if (req.method == "OPTIONS") { - if (req.has_header("Transfer-Encoding") || req.get_header_value_u64("Content-Length") > 0) { - svr.close_after_response(); - } - res.status = 204; - return HandlerResponse::Handled; - } - if (!params.api_keys.empty() && needs_api_key(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"); - svr.close_after_response(); - return HandlerResponse::Handled; - } - return HandlerResponse::Unhandled; - }); - - svr.set_post_routing_handler([&svr, ¶ms](const httplib::Request& req, httplib::Response& res) { - if (svr.will_close_after_response()) { - res.headers.erase("Connection"); - res.headers.erase("Keep-Alive"); - res.set_header("Connection", "close"); - } - if (!params.api_keys.empty() && needs_api_key(req)) { - res.headers.erase("Cache-Control"); - res.set_header("Cache-Control", "no-store"); - } - - const bool preflight = req.method == "OPTIONS"; - res.set_header("Vary", preflight ? "Origin, Access-Control-Request-Headers" : "Origin"); - - const auto& allowed = params.cors_origins; - const auto origin = req.get_header_value("Origin"); - if (allowed.empty() || std::find(allowed.begin(), allowed.end(), origin) != allowed.end()) { - 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); - } - }); -} - void sd_log_cb(enum sd_log_level_t level, const char* log, void* data) { SDSvrParams* svr_params = (SDSvrParams*)data; log_print(level, log, svr_params->log_level, svr_params->color); @@ -266,8 +142,7 @@ int main(int argc, const char** argv) { std::thread async_worker(async_job_worker, std::ref(runtime)); - SDHttpServer svr; - configure_server_access(svr, svr_params); + 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 c316ef7dad..120b8de071 100644 --- a/examples/server/runtime.cpp +++ b/examples/server/runtime.cpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include #include @@ -327,48 +326,8 @@ ArgOptions SDSvrParams::get_options() { return -1; }; - // split_list adds the comma-separated entries of arg to out; a list - // without any entry (like ",") is an error, so a restriction can't - // silently turn into none. - auto split_list = [](const char* arg, std::vector& out) { - std::stringstream ss(arg); - std::string item; - size_t added = 0; - while (std::getline(ss, item, ',')) { - if (!item.empty()) { - out.push_back(item); - added++; - } - } - return added > 0; - }; - options.manual_options = { {"-h", "--help", "show this help message and exit", on_help_arg}, - {"", "--api-key", "API key clients must send (Authorization: Bearer KEY or X-Api-Key); comma-separated for several", - [this, split_list](int, const char** argv, int index) { - if (!split_list(argv[index + 1], api_keys)) { - LOG_ERROR("error: --api-key needs at least one key"); - return -1; - } - return 1; - }, - true}, - {"", "--api-key-file", "file with API keys, one per line (keeps them off the command line)", - [this](int, const char** argv, int index) { - api_key_file = argv_to_utf8(index + 1, argv); - return 1; - }, - true}, - {"", "--cors-origins", "web origins allowed to read cross-origin responses, comma-separated (default: any)", - [this, split_list](int, const char** argv, int index) { - if (!split_list(argv[index + 1], cors_origins)) { - LOG_ERROR("error: --cors-origins needs at least one origin"); - return -1; - } - return 1; - }, - true}, {"", "--weight-staging-ttl", "idle seconds before releasing GPU staging copies of RAM weights (-1 disabled, 0 immediate; default: -1)", [this](int argc, const char** argv, int index) { @@ -424,30 +383,7 @@ bool SDSvrParams::validate() { } bool SDSvrParams::resolve_and_validate() { - if (!validate()) { - return false; - } - if (!api_key_file.empty()) { - std::ifstream file(fs::u8path(api_key_file)); - if (!file) { - LOG_ERROR("error: can't read api_key_file: %s", api_key_file.c_str()); - return false; - } - std::string line; - const size_t before = api_keys.size(); - while (std::getline(file, line)) { - line.erase(line.find_last_not_of(" \t\r\n") + 1); - line.erase(0, line.find_first_not_of(" \t")); - if (!line.empty()) { - api_keys.push_back(line); - } - } - if (api_keys.size() == before) { - LOG_ERROR("error: api_key_file has no keys: %s", api_key_file.c_str()); - return false; - } - } - return true; + return validate() && load_api_keys(); } std::string SDSvrParams::to_string() const { diff --git a/examples/server/runtime.h b/examples/server/runtime.h index 8709385341..debf97cb95 100644 --- a/examples/server/runtime.h +++ b/examples/server/runtime.h @@ -29,8 +29,6 @@ struct SDSvrParams { std::string serve_html_path; std::string dgl_dir = "dgl"; std::vector model_dirs; - // Access: keys clients must send, and the web origins that may call the - // server. Empty: no key needed, any origin (as before). std::vector api_keys; std::string api_key_file; std::vector cors_origins; @@ -39,9 +37,13 @@ struct SDSvrParams { 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 0000000000..1bd0aaf8b0 --- /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 0000000000..074aabac76 --- /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_; +}; From 12c85219a37fc4265e18b4a45d69b9508a950184 Mon Sep 17 00:00:00 2001 From: leejet Date: Wed, 25 Nov 2026 23:02:52 +0800 Subject: [PATCH 5/5] fix(server): return the correct status for cancelled DGL jobs --- examples/server/async_jobs.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp index ac9318f1cc..b521be5363 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)); });