Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/server/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 23 additions & 0 deletions examples/server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,29 @@ configured defaults.
| `--max-pending-jobs <count>` | `64` | Maximum async jobs queued or generating |
| `--completed-ttl-seconds <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 <key>` | none | Key clients must send as `Authorization: Bearer <key>` or `X-Api-Key: <key>`. Separate multiple keys with commas. |
| `--api-key-file <file>` | none | The same, one key per line, so keys don't show in the process list |
| `--cors-origins <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 |
Expand Down
2 changes: 1 addition & 1 deletion examples/server/async_jobs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,7 @@ static sd_status_t execute_dgl_job(ServerRuntime& runtime,
{
std::lock_guard<std::mutex> 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));
});
Expand Down
23 changes: 4 additions & 19 deletions examples/server/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
#include <thread>
#include <vector>

#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"
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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
Expand Down
7 changes: 3 additions & 4 deletions examples/server/runtime.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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();
}
Expand Down
7 changes: 7 additions & 0 deletions examples/server/runtime.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,21 @@ struct SDSvrParams {
std::string serve_html_path;
std::string dgl_dir = "dgl";
std::vector<std::string> model_dirs;
std::vector<std::string> api_keys;
std::string api_key_file;
std::vector<std::string> 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<ArgOptions>& groups);
bool validate();
bool resolve_and_validate();
std::string to_string() const;

private:
bool load_api_keys();
};

struct LoraEntry {
Expand Down
199 changes: 199 additions & 0 deletions examples/server/server_access.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
#include "server_access.h"

#include <algorithm>
#include <cctype>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <string_view>

#include "runtime.h"

static bool is_registered_option(const std::vector<ArgOptions>& 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<std::string>& 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<ArgOptions>& 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<std::string>& 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<unsigned char>(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<std::string>& 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<std::string>& 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([&params](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([&params](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;
}
15 changes: 15 additions & 0 deletions examples/server/server_access.h
Original file line number Diff line number Diff line change
@@ -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_;
};
Loading