Spaces:
Sleeping
Sleeping
Dmitry Beresnev commited on
Commit ·
6471a06
1
Parent(s): 27c1c3c
fix critical secutity issues
Browse filesFiles changed (17)
- .gitignore+3
- Dockerfile+21-15
- README.md+32
- config.toml.example+34-2
- cpp/config.cpp+144-2
- cpp/http_helpers.cpp+113-3
- cpp/http_helpers.h+13-1
- cpp/llm_manager.cpp+41-12
- cpp/llm_manager_types.h+63
- cpp/model_manager.cpp+5-4
- cpp/request_parsing.cpp+36-12
- cpp/request_parsing.h+4
- cpp/runtime_components.cpp+43-10
- cpp/runtime_components.h+4-1
- cpp/server.cpp+156-60
- cpp/server.h+22-16
- cpp/sha256.hAdded+88
71 unmodified lines72737475767778798071 unmodified lineslogs/agi.log
# Runtime config holds API key secrets — never commit itconfig.toml
# Environment variables.env.env.local17 unmodified lines1819202122212324252666 unmodified lines9394959495969798991001019697989910010110210310410810911010510610710810911011711811911111211311424 unmodified lines13914014114214314414514614714814915015115215315415515615715817 unmodified lines# Clone and build llama.cpp with SSL support for HuggingFace HubWORKDIR /buildARG CACHEBUST=6# Pinned release tag (supply chain: never build from a moving branch). Bump# deliberately and re-run the endpoint tests.ARG LLAMA_CPP_REF=masterARG LLAMA_CPP_REF=b12367#ARG BUILD_PROFILE=fast_buildARG BUILD_PROFILE=fast_runtimeARG BUILD_JOBS=166 unmodified lines# Update library cacheRUN ldconfig
# Install Python and FastAPI dependenciesRUN apt-get update && apt-get install -y --no-install-recommends \ python3 \ python3-pip \ && rm -rf /var/lib/apt/lists/*
# Install Python packagesRUN pip3 install --no-cache-dir fastapi uvicorn aiohttp pydantic duckduckgo-search beautifulsoup4 lxml --break-system-packages# The legacy Python app (python/) is intentionally NOT shipped: it has# unauthenticated admin endpoints and a pile of unpinned dependencies. The# runtime image contains only llama-server and the C++ manager.
# Create non-root userRUN useradd -m -u 1000 user && \ mkdir -p /home/user/.cache/llama.cpp && \ chown -R user:user /home/user
# Copy application codeCOPY --chown=user:user python/ /home/user/python/
USER userWORKDIR /home/user
# Set environment variablesENV HOME=/home/user \ LLAMA_CACHE=/home/user/.cache/llama.cpp \ PATH=/home/user/.local/bin:$PATH \ PYTHONPATH=/home/user/python \ PYTHONUNBUFFERED=1 PATH=/home/user/.local/bin:$PATH
EXPOSE 7860
24 unmodified lines# batches worth multiplying (was 64/32). RAM headroom (~16 GB vs ~5 GB used)# covers the larger compute buffers.# Validate any change with tests/bench.py (see PERFORMANCE_REFACTORING_PLAN.md).## Security (see docs/SECURITY_AUDIT_AND_FIX_PLAN.md):# - API keys are NOT baked into the image. Set the API_KEYS secret on the# Space: API_KEYS="admin-main:admin:<32+ char secret>,user-main:user:<secret>"# (a secret may also be given as sha256:<hex>). Without it the manager# fails closed and every authenticated endpoint returns 401.# - ALLOWED_MODELS restricts /switch-model; the default model is always allowed.# - PER_IP_REQUESTS_PER_MINUTE is a pre-auth limit per client address# (X-Forwarded-For from the HF proxy).ENV ALLOWED_MODELS=QuantFactory/Qwen2.5-7B-Instruct-GGUF:q4_k_m \ PER_IP_REQUESTS_PER_MINUTE=120 \ MANAGER_MAX_SESSIONS=256 \ MAX_REQUEST_BODY_BYTES=1048576 \ LOG_REQUEST_BODIES=falseENV DEFAULT_MODEL=QuantFactory/Qwen2.5-7B-Instruct-GGUF:q4_k_m \ MANAGER_HOST=0.0.0.0 \ MANAGER_PORT=7860 \24 unmodified lines252627282930313233343536373839404142434445464748495051525354555657585960616224 unmodified lines
The legacy Python application is still present under [`python/`](/Users/dmitryberesnev/Project/huggingface/agi/AGI/python), but the repository is now centered around the C++ manager implementation in [`cpp/`](/Users/dmitryberesnev/Project/huggingface/agi/AGI/cpp).
## Security Setup (read before deploying)
The manager **fails closed**: with no usable API keys configured every authenticated endpoint(`/v1/chat/completions`, `/switch-model`, `/stop`, cancel, `/props`, `/slots`, `/metrics`) returns 401.Keys are never baked into the image. Configure them as an environment variable / HF Space secret:
```bash# key_id:role:secret[,key_id:role:secret...]; role is admin or userAPI_KEYS="admin-main:admin:$(openssl rand -hex 24),user-main:user:$(openssl rand -hex 24)"# a secret may also be given as sha256:<hex> so the plaintext is never stored```
Rules enforced at startup (violations disable the key and are logged):
- secrets must be at least 32 characters (`AUTH_MIN_SECRET_LENGTH`)- placeholder secrets (`change-me…`, `test…`, `replace…`, …) are refused- `AUTH_ALLOW_ANONYMOUS=true` lets unauthenticated callers in with the **user** role only
Other security-relevant settings (all overridable by environment variable):
| Setting | Env | Purpose ||---------|-----|---------|| `[models] allowed` | `ALLOWED_MODELS` | Allowlist for `/switch-model`; default model always allowed || `[rate_limit] per_ip_requests_per_minute` | `PER_IP_REQUESTS_PER_MINUTE` | Pre-auth per-address limit (uses `X-Forwarded-For` when `trust_proxy_headers`) || `[server] max_sessions` | `MANAGER_MAX_SESSIONS` | Connection cap; excess gets a fast 503 || `[limits] max_request_body_bytes` | `MAX_REQUEST_BODY_BYTES` | 413 for oversized bodies || `[logging] log_request_bodies` | `LOG_REQUEST_BODIES` | Prompts stay out of logs unless enabled |
Cancellation is soft: cancelling a running request closes only that request's upstream connection.Only the admin `/stop` endpoint restarts the worker. The full audit and rationale is in`docs/SECURITY_AUDIT_AND_FIX_PLAN.md`.
## Features
- Dynamic model switching through a single manager endpoint.1234567891018 unmodified lines29303132333435363738394041424344454610 unmodified lines5758596061626364656667686970717273747576777879808152828384858687885889909192[server]host = "0.0.0.0"port = 7860# Max concurrently open client connections (each pins a thread); excess get 503.max_sessions = 256# Per-recv timeout for client sockets (idle keep-alive, slow senders).read_timeout_sec = 30
[worker]default_model = "QuantFactory/Qwen2.5-7B-Instruct-GGUF:q4_k_m"18 unmodified lines[auth]header = "Authorization"scheme = "Bearer"# Fail closed: with no usable api keys every authenticated endpoint is 401.# Set true to let unauthenticated callers in with the "user" role (never admin).allow_anonymous = false# Plaintext secrets shorter than this are refused at load time.min_secret_length = 32
[limits]default_max_tokens = 256max_tokens_per_request = 2048request_timeout_sec = 30# Bodies above this get 413 before parsing.max_request_body_bytes = 1048576
[queue]max_size = 10010 unmodified lines[rate_limit]requests_per_minute = 60estimated_tokens_per_minute = 6000# Pre-auth limit per client address, applied to every request (0 = off).per_ip_requests_per_minute = 120# Use the first X-Forwarded-For hop as the client address (true behind the# HF proxy or any trusted reverse proxy; false if clients connect directly).trust_proxy_headers = true
[logging]# Request bodies contain user prompts; only enable for local debugging.log_request_bodies = false
[models]# Models /switch-model may load (the default model is always allowed).allowed = ["QuantFactory/Qwen2.5-7B-Instruct-GGUF:q4_k_m"]
# API keys. Prefer the API_KEYS environment variable (HF Space secret) in# production: "key_id:role:secret,key_id:role:secret". When API_KEYS is set# the entries below are ignored. Placeholder secrets ("change-me...", "test",# ...) and secrets shorter than min_secret_length are disabled at load time.# Generate one with: openssl rand -hex 24# Hash one with: printf '%s' "$SECRET" | sha256sum[[api_keys]]key_id = "admin-main"secret = "change-me-admin"# Either a plaintext secret ...secret = "REPLACE-WITH-32-PLUS-RANDOM-CHARS-admin"role = "admin"enabled = true
[[api_keys]]key_id = "user-main"secret = "change-me-user"# ... or only its SHA-256 so the plaintext never sits in the config file.secret_sha256 = "0000000000000000000000000000000000000000000000000000000000000000"role = "user"enabled = true1234567891011121314151699 unmodified lines11611711811511912012112226 unmodified lines14915015115215315415530 unmodified lines1861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962978 unmodified lines30630730830931031131231310 unmodified lines3243253263273283293303313323333343353363373384 unmodified lines343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374234375376377378379380381#include "config.h"
#include "http_helpers.h"#include "sha256.h"
#include <algorithm>#include <cctype>#include <cstdlib>#include <filesystem>#include <fstream>#include <sstream>#include <unordered_map>#include <unordered_set>
std::string get_env_or(const char *name, const std::string &fallback) { const char *v = std::getenv(name);99 unmodified lines bool has_any_field = false;
auto flush_current = [&]() { if (has_any_field && !current.key_id.empty() && !current.secret.empty()) { if (has_any_field && !current.key_id.empty() && (!current.secret.empty() || !current.secret_sha256.empty())) { keys.push_back(current); } current = ApiKeyRecord{};26 unmodified lines
if (key == "key_id") current.key_id = value; else if (key == "secret") current.secret = value; else if (key == "secret_sha256") current.secret_sha256 = value; else if (key == "role") current.role = parse_role_or(value, current.role); else if (key == "enabled") current.enabled = parse_bool_or(value, current.enabled); }30 unmodified lines }}
// Splits a comma-separated list, trimming and dropping empty entries.static std::vector<std::string> split_csv(const std::string &value) { std::vector<std::string> out; std::stringstream ss(value); std::string item; while (std::getline(ss, item, ',')) { item = strip_quotes(trim_copy(item)); if (!item.empty()) out.push_back(item); } return out;}
// Parses a one-line TOML string array: allowed = ["a", "b"]. The simple// parser stores the raw right-hand side, brackets included.static std::vector<std::string> parse_toml_string_array(const std::string &raw) { std::string inner = trim_copy(raw); if (inner.size() >= 2 && inner.front() == '[' && inner.back() == ']') { inner = inner.substr(1, inner.size() - 2); } return split_csv(inner);}
// API_KEYS="key_id:role:secret,key_id:role:secret". A secret may contain ':'// (only the first two separators are significant) and may be given as// "sha256:<hex>" to avoid putting the plaintext in the environment.static std::vector<ApiKeyRecord> parse_api_keys_env(const std::string &raw) { std::vector<ApiKeyRecord> keys; for (const auto &entry : split_csv(raw)) { const auto first = entry.find(':'); if (first == std::string::npos) { log_line("config: ignoring malformed API_KEYS entry (expected key_id:role:secret)"); continue; } const auto second = entry.find(':', first + 1); if (second == std::string::npos) { log_line("config: ignoring malformed API_KEYS entry (expected key_id:role:secret)"); continue; } ApiKeyRecord record; record.key_id = trim_copy(entry.substr(0, first)); record.role = parse_role_or(entry.substr(first + 1, second - first - 1), Role::USER); std::string secret = trim_copy(entry.substr(second + 1)); if (secret.rfind("sha256:", 0) == 0) { record.secret_sha256 = secret.substr(7); } else { record.secret = secret; } if (record.key_id.empty() || (record.secret.empty() && record.secret_sha256.empty())) { log_line("config: ignoring API_KEYS entry with empty key_id or secret"); continue; } keys.push_back(record); } return keys;}
static bool is_hex_digest(const std::string &value) { if (value.size() != 64) return false; return std::all_of(value.begin(), value.end(), [](unsigned char c) { return std::isxdigit(c) != 0; });}
// Normalises every record to a lowercase hex digest, refuses placeholder and// short secrets, and drops duplicates. Refused keys are disabled rather than// silently accepted so a misconfigured deployment fails closed.static void finalize_api_keys(std::vector<ApiKeyRecord> &keys, const AuthConfig &auth) { static const char *kPlaceholders[] = {"change-me", "changeme", "replace", "secret", "password", "test", "example"}; std::unordered_set<std::string> seen_ids; for (auto &record : keys) { if (!seen_ids.insert(record.key_id).second) { log_line("config: duplicate api key id '" + record.key_id + "' — disabling later entry"); record.enabled = false; continue; } if (!record.secret.empty()) { std::string lowered = record.secret; std::transform(lowered.begin(), lowered.end(), lowered.begin(), [](unsigned char c) { return static_cast<char>(std::tolower(c)); }); for (const char *placeholder : kPlaceholders) { if (lowered.rfind(placeholder, 0) == 0) { log_line("config: api key '" + record.key_id + "' uses a placeholder secret — disabled"); record.enabled = false; break; } } if (record.enabled && static_cast<int>(record.secret.size()) < auth.min_secret_length) { log_line("config: api key '" + record.key_id + "' secret shorter than " + std::to_string(auth.min_secret_length) + " chars — disabled"); record.enabled = false; } record.secret_sha256 = sha256_hex(record.secret); // The plaintext is not needed after hashing; drop it from memory. record.secret.clear(); } else { std::transform(record.secret_sha256.begin(), record.secret_sha256.end(), record.secret_sha256.begin(), [](unsigned char c) { return static_cast<char>(std::tolower(c)); }); if (!is_hex_digest(record.secret_sha256)) { log_line("config: api key '" + record.key_id + "' has an invalid secret_sha256 — disabled"); record.enabled = false; } } }}
ManagerConfig load_manager_config() { ManagerConfig cfg;
8 unmodified lines
cfg.server.host = get_env_or("MANAGER_HOST", get_toml_string_or(toml, "server", "host", cfg.server.host)); cfg.server.port = get_env_int_or("MANAGER_PORT", get_toml_int_or(toml, "server", "port", cfg.server.port)); cfg.server.max_sessions = std::max(1, get_env_int_or("MANAGER_MAX_SESSIONS", get_toml_int_or(toml, "server", "max_sessions", cfg.server.max_sessions))); cfg.server.read_timeout_sec = std::max(1, get_env_int_or("MANAGER_READ_TIMEOUT_SEC", get_toml_int_or(toml, "server", "read_timeout_sec", cfg.server.read_timeout_sec)));
cfg.worker.default_model = get_env_or("DEFAULT_MODEL", get_toml_string_or(toml, "worker", "default_model", cfg.worker.default_model)); cfg.worker.llama_server_bin = get_env_or("LLAMA_SERVER_BIN", get_toml_string_or(toml, "worker", "llama_server_bin", cfg.worker.llama_server_bin));10 unmodified lines
cfg.auth.header = get_env_or("AUTH_HEADER", get_toml_string_or(toml, "auth", "header", cfg.auth.header)); cfg.auth.scheme = get_env_or("AUTH_SCHEME", get_toml_string_or(toml, "auth", "scheme", cfg.auth.scheme)); cfg.auth.allow_anonymous = parse_bool_or( get_env_or("AUTH_ALLOW_ANONYMOUS", get_toml_string_or(toml, "auth", "allow_anonymous", cfg.auth.allow_anonymous ? "true" : "false")), cfg.auth.allow_anonymous); cfg.auth.min_secret_length = std::max(1, get_env_int_or("AUTH_MIN_SECRET_LENGTH", get_toml_int_or(toml, "auth", "min_secret_length", cfg.auth.min_secret_length)));
cfg.limits.default_max_tokens = get_env_int_or("DEFAULT_MAX_TOKENS", get_toml_int_or(toml, "limits", "default_max_tokens", cfg.limits.default_max_tokens)); cfg.limits.max_tokens_per_request = get_env_int_or("MAX_TOKENS_PER_REQUEST", get_toml_int_or(toml, "limits", "max_tokens_per_request", cfg.limits.max_tokens_per_request)); cfg.limits.request_timeout_sec = get_env_int_or("REQUEST_TIMEOUT_SEC", get_toml_int_or(toml, "limits", "request_timeout_sec", cfg.limits.request_timeout_sec)); cfg.limits.max_request_body_bytes = std::max(1024, get_env_int_or("MAX_REQUEST_BODY_BYTES", get_toml_int_or(toml, "limits", "max_request_body_bytes", cfg.limits.max_request_body_bytes)));
cfg.queue.max_size = static_cast<size_t>(std::max( 1,4 unmodified lines
cfg.rate_limit.requests_per_minute = get_env_int_or("REQUESTS_PER_MINUTE", get_toml_int_or(toml, "rate_limit", "requests_per_minute", cfg.rate_limit.requests_per_minute)); cfg.rate_limit.estimated_tokens_per_minute = get_env_int_or("ESTIMATED_TOKENS_PER_MINUTE", get_toml_int_or(toml, "rate_limit", "estimated_tokens_per_minute", cfg.rate_limit.estimated_tokens_per_minute)); cfg.rate_limit.per_ip_requests_per_minute = get_env_int_or("PER_IP_REQUESTS_PER_MINUTE", get_toml_int_or(toml, "rate_limit", "per_ip_requests_per_minute", cfg.rate_limit.per_ip_requests_per_minute)); cfg.rate_limit.trust_proxy_headers = parse_bool_or( get_env_or("TRUST_PROXY_HEADERS", get_toml_string_or(toml, "rate_limit", "trust_proxy_headers", cfg.rate_limit.trust_proxy_headers ? "true" : "false")), cfg.rate_limit.trust_proxy_headers); cfg.logging.log_request_bodies = parse_bool_or( get_env_or("LOG_REQUEST_BODIES", get_toml_string_or(toml, "logging", "log_request_bodies", cfg.logging.log_request_bodies ? "true" : "false")), cfg.logging.log_request_bodies);
cfg.scheduler.max_concurrent = get_env_int_or("SCHEDULER_MAX_CONCURRENT", get_toml_int_or(toml, "scheduler", "max_concurrent", cfg.scheduler.max_concurrent)); cfg.streaming.enabled = parse_bool_or( get_env_or("STREAMING_ENABLED", get_toml_string_or(toml, "streaming", "enabled", cfg.streaming.enabled ? "true" : "false")), cfg.streaming.enabled);
// Model allowlist: env overrides file; the default model is always allowed. const std::string allowed_env = get_env_or("ALLOWED_MODELS", ""); if (!allowed_env.empty()) { cfg.models.allowed = split_csv(allowed_env); } else { cfg.models.allowed = parse_toml_string_array(get_toml_string_or(toml, "models", "allowed", "")); } if (std::find(cfg.models.allowed.begin(), cfg.models.allowed.end(), cfg.worker.default_model) == cfg.models.allowed.end()) { cfg.models.allowed.push_back(cfg.worker.default_model); }
// API keys: the environment (HF Space secrets) takes precedence over the // file so a committed config can never override deployed credentials. const std::string api_keys_env = get_env_or("API_KEYS", ""); if (!api_keys_env.empty()) { cfg.api_keys = parse_api_keys_env(api_keys_env); if (!config_path.empty() && std::filesystem::exists(config_path)) { } else if (!config_path.empty() && std::filesystem::exists(config_path)) { cfg.api_keys = parse_api_keys_toml(config_path); } finalize_api_keys(cfg.api_keys, cfg.auth);
return cfg;}3 unmodified lines456789101112131415161718192021229 unmodified lines32333435363738394041424344454626474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212 unmodified lines135136137451381391401411421431441451461471481491501511521531541551561571581591601611621631645616516616716811 unmodified lines1801811821831841851863 unmodified lines#include <boost/beast/core.hpp>#include <boost/beast/http.hpp>
#include <cctype>#include <cstdio>#include <ctime>#include <iomanip>#include <iostream>#include <mutex>#include <random>#include <sstream>#include <stdexcept>#include <vector>
#include <sys/socket.h>#include <sys/time.h>
namespace asio = boost::asio;namespace beast = boost::beast;9 unmodified lines}
void log_line(const std::string &line) { std::string safe; safe.reserve(line.size()); for (unsigned char c : line) { if (c == '\n') safe += "\\n"; else if (c == '\r') safe += "\\r"; else if (c == '\t') safe += "\\t"; else if (c < 0x20 || c == 0x7f) { char buf[8]; std::snprintf(buf, sizeof(buf), "\\x%02x", c); safe += buf; } else safe.push_back(static_cast<char>(c)); } std::cout << "[" << now_utc_iso() << "] " << line << std::endl; std::cout << "[" << now_utc_iso() << "] " << safe << std::endl;}
void set_socket_timeouts(int fd, int recv_sec, int send_sec) { timeval rcv{}; rcv.tv_sec = recv_sec; setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char *>(&rcv), sizeof(rcv)); timeval snd{}; snd.tv_sec = send_sec; setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char *>(&snd), sizeof(snd));}
std::string generate_request_id() { static std::mutex mu; static std::mt19937_64 rng = [] { std::random_device rd; std::seed_seq seed{rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd()}; return std::mt19937_64(seed); }(); uint64_t hi, lo; { std::lock_guard<std::mutex> lock(mu); hi = rng(); lo = rng(); } char buf[33]; std::snprintf(buf, sizeof(buf), "%016llx%016llx", static_cast<unsigned long long>(hi), static_cast<unsigned long long>(lo)); return std::string(buf);}
std::optional<std::string> normalize_path(const std::string &raw_path) { // Percent-decode first: llama-server (cpp-httplib) decodes before routing, // so the manager must compare the same form it will be routed as. std::string decoded; decoded.reserve(raw_path.size()); for (size_t i = 0; i < raw_path.size(); ++i) { const char c = raw_path[i]; if (c == '%') { if (i + 2 >= raw_path.size() || !std::isxdigit(static_cast<unsigned char>(raw_path[i + 1])) || !std::isxdigit(static_cast<unsigned char>(raw_path[i + 2]))) { return std::nullopt; } decoded.push_back(static_cast<char>(std::stoi(raw_path.substr(i + 1, 2), nullptr, 16))); i += 2; } else { decoded.push_back(c); } } for (unsigned char c : decoded) { if (c < 0x20 || c == 0x7f || c == '\\') return std::nullopt; } if (decoded.empty() || decoded.front() != '/') return std::nullopt;
std::vector<std::string> segments; std::stringstream ss(decoded); std::string seg; while (std::getline(ss, seg, '/')) { if (seg.empty() || seg == ".") continue; if (seg == "..") { if (segments.empty()) return std::nullopt; segments.pop_back(); continue; } segments.push_back(seg); } std::string out = "/"; for (size_t i = 0; i < segments.size(); ++i) { if (i) out += "/"; out += segments[i]; } return out;}
std::string truncate_body(const std::string &body, size_t max_len) {12 unmodified lines return request_id;}
std::pair<int, std::string> forward_chat(const WorkerInfo &worker, const std::string &body) {std::pair<int, std::string> forward_chat(const WorkerInfo &worker, const std::shared_ptr<RequestContext> &ctx) { asio::io_context ioc; asio::ip::tcp::resolver resolver(ioc); beast::tcp_stream stream(ioc); auto const results = resolver.resolve("127.0.0.1", std::to_string(worker.port)); stream.connect(results); // Generation can legitimately take minutes; the client-side request // timeout cancels (and thereby unblocks) this read long before this // safety net fires. set_socket_timeouts(stream.socket().native_handle(), 3600, 60);
// Register the abort hook: a cancel from another thread shuts the socket // down, which makes the blocking read below fail. The guard disarms it // before the socket is destroyed so the hook can never touch a dead fd. const int fd = stream.socket().native_handle(); struct AbortGuard { const std::shared_ptr<RequestContext> &ctx; ~AbortGuard() { ctx->disarm_abort(); } } abort_guard{ctx}; if (!ctx->arm_abort([fd]() { ::shutdown(fd, SHUT_RDWR); })) { throw std::runtime_error("request cancelled before upstream call"); }
http::request<http::string_body> req{http::verb::post, "/v1/chat/completions", 11}; req.set(http::field::host, "127.0.0.1"); req.set(http::field::content_type, "application/json"); req.set(http::field::user_agent, "llm-manager"); req.body() = body; req.body() = ctx->request_body; req.prepare_payload(); http::write(stream, req);
11 unmodified lines beast::tcp_stream stream(ioc); auto const results = resolver.resolve("127.0.0.1", std::to_string(worker.port)); stream.connect(results); set_socket_timeouts(stream.socket().native_handle(), 30, 30);
http::request<http::string_body> req{http::verb::get, target, 11}; req.set(http::field::host, "127.0.0.1");6 unmodified lines7891011121314151617181920212213232425266 unmodified lines#include "llm_manager_types.h"
std::string now_utc_iso();// Writes one log line; control characters in `line` are escaped so a client// cannot forge log entries.void log_line(const std::string &line);std::string truncate_body(const std::string &body, size_t max_len = 2000);std::optional<std::string> extract_cancel_request_id(const std::string &path);// Percent-decodes and canonicalises a URL path (collapses "//", resolves "."// and ".."). Returns nullopt for paths that escape the root or contain// control characters, so callers can match against an exact allowlist.std::optional<std::string> normalize_path(const std::string &raw_path);// Generates a 128-bit random request id as lowercase hex.std::string generate_request_id();// Forwards the request to the worker. While the upstream connection is open// it is registered on `ctx` so a concurrent cancel can shut it down.std::pair<int, std::string> forward_chat(const WorkerInfo &worker, const std::string &body);std::pair<int, std::string> forward_chat(const WorkerInfo &worker, const std::shared_ptr<RequestContext> &ctx);ProxiedGetResult forward_get_to_worker(const WorkerInfo &worker, const std::string &target);// Applies SO_RCVTIMEO/SO_SNDTIMEO to a native socket.void set_socket_timeouts(int fd, int recv_sec, int send_sec);12345616 unmodified lines232425262728293031323334353637313839404142434433454647484950515220 unmodified lines73747560616263646566676869767778798081828384858687888990919293949596979899100#include <boost/asio.hpp>
#include <atomic>#include <chrono>#include <functional>#include <string>16 unmodified lines ModelManager manager(config); ApiKeyAuth auth(config); RateLimiterStore rate_limiter(config.rate_limit); RateLimitConfig ip_limit_config; ip_limit_config.requests_per_minute = config.rate_limit.per_ip_requests_per_minute; ip_limit_config.estimated_tokens_per_minute = 0; RateLimiterStore ip_rate_limiter(ip_limit_config); RequestRegistry registry; MetricsRegistry metrics; Scheduler scheduler(manager, registry, metrics, config.queue); std::atomic<int> active_sessions{0}; ServerDeps deps{manager, config, auth, rate_limiter, ip_rate_limiter, registry, metrics, scheduler, active_sessions};
std::string init_error; if (auth.enabled()) { log_line("auth: enabled api_keys=" + std::to_string(config.api_keys.size())); size_t usable = 0; for (const auto &k : config.api_keys) if (k.enabled) ++usable; log_line("auth: enabled api_keys=" + std::to_string(usable) + "/" + std::to_string(config.api_keys.size()) + (config.auth.allow_anonymous ? " allow_anonymous=true(role=user)" : "")); } else if (config.auth.allow_anonymous) { log_line("auth: WARNING no usable api keys; anonymous access enabled with USER role"); } else { log_line("auth: disabled (no configured api keys)"); log_line("auth: no usable api keys configured — all authenticated endpoints will return 401 " "(set API_KEYS or [[api_keys]], or AUTH_ALLOW_ANONYMOUS=true)"); } if (config.models.allowed.size() <= 1) { log_line("models: allowlist contains only the default model (set ALLOWED_MODELS to permit others)"); }
log_line("startup: loading default model");20 unmodified lines std::this_thread::sleep_for(std::chrono::milliseconds(100)); continue; } std::thread( &do_session, std::move(socket), std::ref(manager), std::cref(config), std::cref(auth), std::ref(rate_limiter), std::ref(registry), std::ref(metrics), std::ref(scheduler)).detach(); // Connection cap: each session pins a thread, so refuse fast once the // configured maximum is reached instead of letting a flood exhaust us. if (active_sessions.load() >= config.server.max_sessions) { static const std::string kBusy = "HTTP/1.1 503 Service Unavailable\r\nContent-Type: application/json\r\n" "Retry-After: 2\r\nConnection: close\r\nContent-Length: 29\r\n\r\n" "{\"error\":\"Too many sessions\"}"; boost::system::error_code ignored; asio::write(socket, asio::buffer(kBusy), ignored); socket.shutdown(asio::ip::tcp::socket::shutdown_both, ignored); socket.close(ignored); continue; } active_sessions.fetch_add(1); try { std::thread(&do_session, std::move(socket), std::ref(deps)).detach(); } catch (const std::exception &e) { // Thread creation failed (resource exhaustion): the socket was // moved into the thread argument and is gone; just release the slot. active_sessions.fetch_sub(1); log_line("thread_spawn_error=" + std::string(e.what())); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } }}2 unmodified lines34567898 unmodified lines18192021222324252627282924 unmodified lines54555657585960616263646566676869707172736 unmodified lines80818283848586878889909192939495969798991001016 unmodified lines1081091101111121131141151161171188 unmodified lines12712812913013113213313418 unmodified lines15315415515615715815916034 unmodified lines1951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242 unmodified lines#include <atomic>#include <chrono>#include <condition_variable>#include <functional>#include <memory>#include <mutex>#include <string>8 unmodified linesstruct ServerConfig { std::string host = "0.0.0.0"; int port = 7860; // Hard cap on concurrently open client connections (each one pins a // thread). Excess connections get a fast 503. int max_sessions = 256; // Per-recv timeout for client sockets: bounds idle keep-alive connections // and stalled senders. int read_timeout_sec = 30;};
struct WorkerConfig {24 unmodified linesstruct AuthConfig { std::string header = "Authorization"; std::string scheme = "Bearer"; // Fail closed by default: with no API keys configured every request is // rejected. Setting this lets unauthenticated callers in with USER role // (never ADMIN). bool allow_anonymous = false; // Secrets shorter than this are refused at load time. int min_secret_length = 32;};
struct LimitsConfig { int default_max_tokens = 256; int max_tokens_per_request = 2048; int request_timeout_sec = 30; // Upper bound on any request body; larger bodies get 413 before parsing. int max_request_body_bytes = 1 * 1024 * 1024;};
struct QueueConfig {6 unmodified linesstruct RateLimitConfig { int requests_per_minute = 60; int estimated_tokens_per_minute = 6000; // Pre-auth per-source limit applied to every request (0 = disabled). The // source is the first X-Forwarded-For hop when trust_proxy_headers is // set, otherwise the TCP peer address. int per_ip_requests_per_minute = 0; bool trust_proxy_headers = true;};
struct LoggingConfig { // Request bodies carry user prompts; keep them out of logs unless // explicitly enabled for debugging. bool log_request_bodies = false;};
struct ModelsConfig { // Models /switch-model may load. Empty means only the default model. std::vector<std::string> allowed;};
struct SchedulerConfig {6 unmodified lines
struct ApiKeyRecord { std::string key_id; // Plaintext secret as loaded from config (may be empty when only the // hash is configured). Never logged. std::string secret; // Lowercase hex SHA-256 of the secret; this is what auth compares. std::string secret_sha256; Role role = Role::USER; bool enabled = true;};8 unmodified lines RateLimitConfig rate_limit; SchedulerConfig scheduler; StreamingConfig streaming; LoggingConfig logging; ModelsConfig models; std::vector<ApiKeyRecord> api_keys;};
18 unmodified lines};
struct TokenEstimate { // All values are validated to be non-negative and <= max_tokens_per_request // before a request is admitted, so they always fit in int. int prompt_tokens = 0; int requested_max_tokens = 0; int estimated_total_tokens = 0;34 unmodified lines std::condition_variable cv; bool completed = false; RequestResult result;
// Soft cancellation: while the scheduler has an upstream connection open // for this request it registers a callback that shuts that socket down. // Cancelling then aborts only this request instead of restarting the // worker (llama-server drops the task when the client disconnects). std::mutex abort_mu; std::function<void()> abort_upstream;
// Returns false if the request was already cancelled, in which case the // caller must not proceed with the upstream call. bool arm_abort(std::function<void()> fn) { std::lock_guard<std::mutex> lock(abort_mu); if (cancelled.load()) return false; abort_upstream = std::move(fn); return true; } void disarm_abort() { std::lock_guard<std::mutex> lock(abort_mu); abort_upstream = nullptr; } void trigger_abort() { std::lock_guard<std::mutex> lock(abort_mu); if (abort_upstream) abort_upstream(); }};
struct ProxiedGetResult {171 unmodified lines17217317417517617717817917817918018118218318418318418576 unmodified lines262263264265266267268269270171 unmodified lines json out; out["status"] = (active_ && is_alive(active_->pid)) ? "ready" : "no_active_model"; out["switch_in_progress"] = switch_in_progress_; // Process id and port are internal details; keep them out of the // unauthenticated status view. if (active_ && is_alive(active_->pid)) { out["current_model"] = active_->model; out["last_loaded"] = active_->last_loaded; out["active_pid"] = active_->pid; out["active_port"] = active_->port; } else { out["current_model"] = nullptr; out["last_loaded"] = nullptr; out["active_pid"] = nullptr; out["active_port"] = nullptr; } return out;}76 unmodified lines beast::tcp_stream stream(ioc); auto const results = resolver.resolve(worker_host_, std::to_string(port)); stream.connect(results); // Readiness probe: a worker that accepts but never answers must not stall // the switch forever. set_socket_timeouts(stream.socket().native_handle(), 5, 5);
http::request<http::string_body> req{http::verb::get, target, 11}; req.set(http::field::host, worker_host_);1234566788910111223 unmodified lines363738394041424 unmodified lines474849484950515253545556575855596061626364656667685869706071727374757677787980816682838469858671878889909192937475949596979899100101102103104105106#include "request_parsing.h"
#include <algorithm>#include <cstdint>#include <sstream>
static int estimate_text_tokens_rough(const std::string &text) {static int64_t estimate_text_tokens_rough(const std::string &text) { if (text.empty()) return 0; return std::max(1, static_cast<int>((text.size() + 3) / 4)); return std::max<int64_t>(1, static_cast<int64_t>((text.size() + 3) / 4));}
static std::string flatten_json_content(const json &content) {23 unmodified linesstd::optional<TokenEstimate> estimate_chat_tokens( const json &payload, const LimitsConfig &limits, size_t body_bytes, std::string &error) { if (!payload.is_object()) { error = "Expected JSON object";4 unmodified lines return std::nullopt; }
TokenEstimate estimate; estimate.requested_max_tokens = limits.default_max_tokens; // All arithmetic in 64 bits: an int-sized max_tokens plus a prompt used // to wrap negative and sail past every budget check below. const int64_t max_per_request = limits.max_tokens_per_request; int64_t requested_max_tokens = limits.default_max_tokens; if (payload.contains("max_tokens")) { if (!payload["max_tokens"].is_number_integer()) { error = "Expected integer 'max_tokens'"; return std::nullopt; } estimate.requested_max_tokens = payload["max_tokens"].get<int>(); // Out-of-range integers (beyond int64) come back saturated by nlohmann // as unsigned; treat anything that does not fit as over the limit. if (payload["max_tokens"].is_number_unsigned() && payload["max_tokens"].get<uint64_t>() > static_cast<uint64_t>(INT64_MAX)) { error = "'max_tokens' exceeds configured limit"; return std::nullopt; } requested_max_tokens = payload["max_tokens"].get<int64_t>(); }
if (estimate.requested_max_tokens <= 0) { if (requested_max_tokens <= 0) { // -1 (and other non-positive values) is a sentinel meaning "unlimited" — use the default estimate.requested_max_tokens = limits.default_max_tokens; requested_max_tokens = limits.default_max_tokens; } if (requested_max_tokens > max_per_request) { error = "'max_tokens' exceeds configured limit"; return std::nullopt; }
int64_t prompt_tokens = 0; for (const auto &message : payload["messages"]) { if (!message.is_object()) continue; if (message.contains("role") && message["role"].is_string()) { estimate.prompt_tokens += estimate_text_tokens_rough(message["role"].get<std::string>()); prompt_tokens += estimate_text_tokens_rough(message["role"].get<std::string>()); } if (message.contains("content")) { estimate.prompt_tokens += estimate_text_tokens_rough(flatten_json_content(message["content"])); prompt_tokens += estimate_text_tokens_rough(flatten_json_content(message["content"])); } estimate.prompt_tokens += 4; prompt_tokens += 4; if (prompt_tokens > max_per_request) break; // already over; stop walking } // Floor the estimate on the raw body size so payload that the text walker // does not see (tools, image parts, unknown keys) is still budgeted. prompt_tokens = std::max(prompt_tokens, static_cast<int64_t>(body_bytes / 4));
estimate.estimated_total_tokens = estimate.prompt_tokens + estimate.requested_max_tokens; if (estimate.estimated_total_tokens > limits.max_tokens_per_request) { const int64_t total = prompt_tokens + requested_max_tokens; if (prompt_tokens > max_per_request || total > max_per_request) { error = "Estimated request tokens exceed configured limit"; return std::nullopt; }
TokenEstimate estimate; estimate.prompt_tokens = static_cast<int>(prompt_tokens); estimate.requested_max_tokens = static_cast<int>(requested_max_tokens); estimate.estimated_total_tokens = static_cast<int>(total); error.clear(); return estimate;}4 unmodified lines5678910111213141516174 unmodified lines
#include "llm_manager_types.h"
// `body_bytes` is the size of the raw request body: it is used as a floor for// the prompt estimate so fields the text walker does not see (tools, image// parts, unknown keys) still count against the budget.std::optional<TokenEstimate> estimate_chat_tokens( const json &payload, const LimitsConfig &limits, size_t body_bytes, std::string &error);
bool request_stream_enabled(const json &payload);2 unmodified lines3456789115 unmodified lines12512612712812913013113213313415 unmodified lines150151152153154155156207 unmodified lines3643653663613673683693703 unmodified lines3743753763773783793803813823833723843853863873883893903753913923933943953963813973983994003834014024034044054064074084093884104114124134144153944164174184194204213964224234244254264274284294304314024034324334344354364374384392 unmodified lines#include "config.h"#include "http_helpers.h"#include "model_manager.h"#include "sha256.h"
#include <algorithm>#include <cctype>115 unmodified lines if (previous_state) *previous_state = expected; if (expected == RequestState::RUNNING) { ctx->state.store(RequestState::CANCELLED); // Soft cancel: drop the upstream connection for this request only. // llama-server abandons the task when its client disconnects, so // no worker restart is needed and other users are unaffected. ctx->trigger_abort(); } } return ctx;15 unmodified lines ctx->cv.notify_all(); } else if (expected == RequestState::RUNNING) { ctx->state.store(RequestState::CANCELLED); ctx->trigger_abort(); } out.push_back(ctx); }207 unmodified lines }
try { auto [status, body] = forward_chat(*worker, ctx->request_body); auto [status, body] = forward_chat(*worker, ctx); if (ctx->cancelled.load()) { registry_.complete(ctx, RequestState::CANCELLED, {499, R"({"error":"Request cancelled"})"}); continue;3 unmodified lines } registry_.complete(ctx, RequestState::DONE, {status, body}); } catch (const std::exception &e) { if (ctx->cancelled.load()) { // Expected: the cancel path shut the upstream socket under us. registry_.complete(ctx, RequestState::CANCELLED, {499, R"({"error":"Request cancelled"})"}); continue; } // Upstream details stay in the log; clients get a generic error. log_line("request_id=" + ctx->request_id + " scheduler_exception=" + std::string(e.what())); registry_.complete(ctx, RequestState::FAILED, {500, json({{"error", e.what()}}).dump()}); registry_.complete(ctx, RequestState::FAILED, {502, R"({"error":"Upstream inference error"})"}); } catch (...) { if (ctx->cancelled.load()) { registry_.complete(ctx, RequestState::CANCELLED, {499, R"({"error":"Request cancelled"})"}); continue; } log_line("request_id=" + ctx->request_id + " scheduler_exception=unknown"); registry_.complete(ctx, RequestState::FAILED, {500, json({{"error", "Unknown exception"}}).dump()}); registry_.complete(ctx, RequestState::FAILED, {502, R"({"error":"Upstream inference error"})"}); } }}
ApiKeyAuth::ApiKeyAuth(const ManagerConfig &config) : header_name_(config.auth.header), scheme_(config.auth.scheme) { : header_name_(config.auth.header), scheme_(config.auth.scheme), allow_anonymous_(config.auth.allow_anonymous) { for (const auto &record : config.api_keys) { records_by_secret_.emplace(record.secret, record); // Disabled records are kept so a presented-but-disabled key reports // "disabled" instead of "invalid"; only enabled ones count as usable. if (record.secret_sha256.empty()) continue; records_by_hash_.emplace(record.secret_sha256, record); if (record.enabled) ++usable_keys_; }}
bool ApiKeyAuth::enabled() const { return !records_by_secret_.empty(); return usable_keys_ > 0;}
std::optional<ApiKeyRecord> ApiKeyAuth::authenticate( const http::request<http::string_body> &req, std::string &error) const { if (!enabled()) { const bool has_header = req.find(header_name_) != req.end();
// Fail closed: with no usable keys and no explicit anonymous opt-in, // nothing is let through. Anonymous access is never more than USER. if (!has_header && allow_anonymous_) { error.clear(); return ApiKeyRecord{"anonymous", "", Role::ADMIN, true}; return ApiKeyRecord{"anonymous", "", "", Role::USER, true}; } if (!enabled() && !has_header) { error = "Authentication not configured"; return std::nullopt; }
const auto token = extract_bearer_token(req, error); if (!token) return std::nullopt;
const auto it = records_by_secret_.find(*token); if (it == records_by_secret_.end()) { // Hash first so lookup time does not depend on the secret's bytes, then // confirm with a constant-time compare of the digests. const std::string digest = sha256_hex(*token); const auto it = records_by_hash_.find(digest); if (it == records_by_hash_.end() || !constant_time_equals(it->first, digest)) { error = "Invalid API key"; return std::nullopt; }156 unmodified lines157158159160161162160163164165166156 unmodified linesprivate: std::string header_name_; std::string scheme_; bool allow_anonymous_ = false; size_t usable_keys_ = 0; // Keyed by lowercase hex SHA-256 of the secret. std::unordered_map<std::string, ApiKeyRecord> records_by_secret_; std::unordered_map<std::string, ApiKeyRecord> records_by_hash_;
std::optional<std::string> extract_bearer_token( const http::request<http::string_body> &req,1 unmodified line23456781 unmodified line10111213141516171516171819202122212223205 unmodified lines2292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672352362372382392402412682692702712722732742752762772782792442452802812822482832842852862872883 unmodified lines29229329425825929529629729829930030130230330430541 unmodified lines3473483493073503513523533543555 unmodified lines36136236336436536636736836937037137237337437537637737837938038138238338430 unmodified lines41541641741841942042142242342442542642742842931 unmodified lines46146246339246446546646746839539639746947047147247347447547647747840440540640740840947948048148248341548448548619 unmodified lines50650750844150951051151255 unmodified lines56856957057157257357457550650750850951051157657757857951658058158238 unmodified lines62162262356156256356462462562662762862963063163263363463563663763863964064164264364457164564664764820 unmodified lines6696706716726736745996756766776026786796806816066076086096106116126136146826836846856866876886896906916926936946186196206216956966976986997007017026266277037047057067077087097107117127137147157167177187197207217227237246297257267277281 unmodified line
#include <boost/beast/core.hpp>
#include "config.h"#include "http_helpers.h"#include "model_manager.h"#include "request_parsing.h"1 unmodified line
#include <algorithm>#include <atomic>#include <regex>#include <sstream>#include <unordered_set>#include <utility>
#include <sys/socket.h>#include <sys/time.h>
namespace beast = boost::beast;namespace http = beast::http;
static std::atomic<uint64_t> g_req_id{1};
static std::string build_sse_event(const json &payload) { return "data: " + payload.dump() + "\n\n";}205 unmodified lines return oss.str();}
// Model identifiers go straight onto llama-server's command line as the -hf// value, so only accept the owner/repo[:quant] shape and nothing that looks// like a flag, a path, or contains control characters.static bool is_valid_model_identifier(const std::string &model) { if (model.empty() || model.size() > 256) return false; static const std::regex pattern( R"(^[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*(:[A-Za-z0-9][A-Za-z0-9_.-]*)?$)"); if (!std::regex_match(model, pattern)) return false; return model.find("..") == std::string::npos;}
static bool is_allowed_model(const ModelsConfig &models, const std::string &model) { return std::find(models.allowed.begin(), models.allowed.end(), model) != models.allowed.end();}
// Resolves the client address used for per-source rate limiting. The first// X-Forwarded-For hop is used only when the deployment says the proxy in// front of us is trusted (HF Spaces); otherwise the TCP peer.static std::string client_address( const http::request<http::string_body> &req, const std::string &peer_address, bool trust_proxy_headers) { if (trust_proxy_headers) { const auto it = req.find("X-Forwarded-For"); if (it != req.end()) { std::string value = it->value().to_string(); const auto comma = value.find(','); if (comma != std::string::npos) value = value.substr(0, comma); value = trim_copy(value); if (!value.empty() && value.size() <= 64) return value; } } return peer_address;}
http::response<http::string_body> handle_request( ModelManager &manager, const ManagerConfig &config, const ApiKeyAuth &auth, RateLimiterStore &rate_limiter, RequestRegistry ®istry, MetricsRegistry &metrics, Scheduler &scheduler, ServerDeps &deps, const std::string &peer_address, http::request<http::string_body> &&req) { ModelManager &manager = deps.manager; const ManagerConfig &config = deps.config; const ApiKeyAuth &auth = deps.auth; RateLimiterStore &rate_limiter = deps.rate_limiter; RequestRegistry ®istry = deps.registry; MetricsRegistry &metrics = deps.metrics; Scheduler &scheduler = deps.scheduler;
const auto start = std::chrono::steady_clock::now(); const auto req_id_num = g_req_id.fetch_add(1); const std::string request_id = std::to_string(req_id_num); const std::string request_id = generate_request_id(); const std::string target = req.target().to_string(); const std::string method = req.method_string().to_string(); const std::string path = target.substr(0, target.find('?')); const auto query_pos = target.find('?'); const std::string raw_path = target.substr(0, query_pos); const std::string query = query_pos == std::string::npos ? "" : target.substr(query_pos); auto authenticated = std::optional<ApiKeyRecord>{};
metrics.inc_requests_total();3 unmodified lines ~InflightGuard() { metrics.dec_requests_inflight(); } } inflight_guard{metrics};
log_line("request_id=" + request_id + " method=" + method + " path=" + target); if (!req.body().empty()) { // Canonical path for routing. Anything that does not normalise (escapes // the root, control chars, bad percent-encoding) is simply not found. const auto normalized = normalize_path(raw_path); const std::string path = normalized ? *normalized : std::string();
log_line("request_id=" + request_id + " method=" + method + " path=" + raw_path + " body_bytes=" + std::to_string(req.body().size())); if (config.logging.log_request_bodies && !req.body().empty()) { log_line("request_id=" + request_id + " body=" + truncate_body(req.body())); }
41 unmodified lines std::string auth_error; authenticated = auth.authenticate(req, auth_error); if (!authenticated) { return json_response(http::status::unauthorized, {{"error", auth_error}}); auto res = json_response(http::status::unauthorized, {{"error", auth_error}}); res.set(http::field::www_authenticate, config.auth.scheme); return res; } if (minimum_role == Role::ADMIN && authenticated->role != Role::ADMIN) { return json_response(http::status::forbidden, {{"error", "Admin role required"}});5 unmodified lines };
try { // Pre-auth per-source limit: protects the thread pool and the auth // path itself from a single abusive client. if (config.rate_limit.per_ip_requests_per_minute > 0) { const std::string source = client_address(req, peer_address, config.rate_limit.trust_proxy_headers); auto decision = deps.ip_rate_limiter.allow("ip:" + source, 0); if (!decision.allowed) { metrics.inc_rate_limited_total(); return json_response_with_retry_after( http::status::too_many_requests, {{"error", "Rate limit exceeded: requests from this address"}}, decision.retry_after_sec); } }
if (!normalized) { return json_response(http::status::not_found, {{"error", "Not found"}}); }
if (path == "/health" && req.method() == http::verb::get) { return json_response(http::status::ok, manager.models_view()); }30 unmodified lines if (model.empty()) { return json_response(http::status::bad_request, {{"error", "Expected string 'model' or 'model_name'"}}); } if (!is_valid_model_identifier(model)) { return json_response(http::status::bad_request, {{"error", "Invalid model identifier; expected owner/repo[:quant]"}}); } if (!is_allowed_model(config.models, model)) { return json_response(http::status::bad_request, {{"error", "Model is not in the configured allowlist"}, {"allowed_models", config.models.allowed}}); }
std::string err; bool ok = manager.switch_model(model, err);31 unmodified lines if (auto cancel_id = extract_cancel_request_id(path)) { if (auto auth_res = ensure_authenticated(Role::USER)) return *auth_res; auto ctx = registry.find(*cancel_id); if (!ctx) { // Same answer for "unknown" and "not yours" so request ids of // other keys cannot be probed. if (!ctx || (authenticated->role != Role::ADMIN && authenticated->key_id != ctx->api_key_id)) { return json_response(http::status::not_found, {{"error", "Unknown request id"}}); } if (authenticated->role != Role::ADMIN && authenticated->key_id != ctx->api_key_id) { return json_response(http::status::forbidden, {{"error", "Cannot cancel another API key request"}}); }
// Soft cancel only: a queued request is dropped, a running one // has its upstream connection closed. The worker is never // restarted from here (that is the admin-only /stop), so one // key cannot take the service down for everyone else. RequestState previous_state = RequestState::QUEUED; registry.cancel_request(*cancel_id, &previous_state); const bool did_cancel = previous_state == RequestState::QUEUED || previous_state == RequestState::RUNNING; if (did_cancel) metrics.add_cancellations_total(); std::string restart_error; bool restarted = true; if (previous_state == RequestState::RUNNING) { restarted = manager.restart_active(restart_error); if (restarted) metrics.inc_worker_restarts_total(); }
json payload = { {"cancelled_request_id", *cancel_id}, {"state", state_to_string(ctx->state.load())} }; if (!restarted) payload["restart_error"] = restart_error; return json_response(http::status::ok, payload); } }19 unmodified lines }
std::string token_error; auto estimate = estimate_chat_tokens(payload, config.limits, token_error); auto estimate = estimate_chat_tokens(payload, config.limits, req.body().size(), token_error); if (!estimate) { return json_response(http::status::bad_request, {{"error", token_error}}); }55 unmodified lines } if (!finished) { lock.unlock(); // Soft cancel: closes this request's upstream connection; the // worker keeps serving everyone else. RequestState timed_out_state = RequestState::QUEUED; registry.cancel_request(request_id, &timed_out_state); metrics.add_cancellations_total(); std::string restart_error; bool restarted = true; if (timed_out_state == RequestState::RUNNING) { restarted = manager.restart_active(restart_error); if (restarted) metrics.inc_worker_restarts_total(); } json timeout_payload = { {"error", "Request timed out"}, {"state", state_to_string(ctx->state.load())} }; if (!restarted) timeout_payload["restart_error"] = restart_error; return json_response(http::status::gateway_timeout, timeout_payload); }
38 unmodified lines }
if (req.method() == http::verb::get) { // /slots can expose other users' prompt content and /metrics exposes // server internals; don't proxy them anonymously. Static UI assets // and /props stay open so the browser UI can load. if (path == "/slots" || path == "/metrics") { // Allowlist, not blocklist: only the paths the bundled web UI needs // are proxied, matched on the canonical (decoded) path so encoded // variants cannot slip past. /props exposes model and template // settings, /slots other users' prompts, /metrics server internals // — those need a key. static const std::unordered_set<std::string> kPublicPaths = { "/", "/index.html", "/index.html.gz", "/favicon.ico"}; static const std::unordered_set<std::string> kAuthenticatedPaths = { "/props", "/v1/models", "/slots", "/metrics"}; const bool is_public = kPublicPaths.count(path) > 0; const bool needs_auth = kAuthenticatedPaths.count(path) > 0; if (!is_public && !needs_auth) { return json_response(http::status::not_found, {{"error", "Not found"}}); } if (needs_auth) { if (auto auth_res = ensure_authenticated(Role::USER)) return *auth_res; } auto worker = manager.active_worker(); if (!worker) { return json_response(http::status::service_unavailable, {{"error", "No active model"}}); } auto upstream = forward_get_to_worker(*worker, target); auto upstream = forward_get_to_worker(*worker, path + query); http::response<http::string_body> res{ static_cast<http::status>(upstream.status), req.version()}; res.set(http::field::content_type, upstream.content_type);20 unmodified lines
return json_response(http::status::not_found, {{"error", "Not found"}}); } catch (const std::exception &e) { // Exception text can reveal internals (paths, library messages); log // it, return a generic message. log_line("request_id=" + request_id + " exception=" + std::string(e.what())); return json_response(http::status::internal_server_error, {{"error", e.what()}}); return json_response(http::status::internal_server_error, {{"error", "Internal server error"}}); } catch (...) { log_line("request_id=" + request_id + " exception=unknown"); return json_response(http::status::internal_server_error, {{"error", "Unknown exception"}}); return json_response(http::status::internal_server_error, {{"error", "Internal server error"}}); }}
void do_session( boost::asio::ip::tcp::socket socket, ModelManager &manager, const ManagerConfig &config, const ApiKeyAuth &auth, RateLimiterStore &rate_limiter, RequestRegistry ®istry, MetricsRegistry &metrics, Scheduler &scheduler) {void do_session(boost::asio::ip::tcp::socket socket, ServerDeps &deps) { struct SessionGuard { std::atomic<int> &counter; ~SessionGuard() { counter.fetch_sub(1); } } session_guard{deps.active_sessions};
const ManagerConfig &config = deps.config; // Receive timeout: each connection pins a detached thread, so idle // keep-alive connections and stalled senders must eventually release it. set_socket_timeouts(socket.native_handle(), config.server.read_timeout_sec, 60);
std::string peer_address; { timeval tv{}; tv.tv_sec = 60; setsockopt(socket.native_handle(), SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char *>(&tv), sizeof(tv)); boost::system::error_code ec; const auto endpoint = socket.remote_endpoint(ec); if (!ec) peer_address = endpoint.address().to_string(); }
try { beast::flat_buffer buffer; for (;;) { http::request<http::string_body> req; http::read(socket, buffer, req); // Explicit limits instead of Beast defaults: oversized headers or // bodies are rejected before they are buffered in full. http::request_parser<http::string_body> parser; parser.header_limit(16 * 1024); parser.body_limit(static_cast<uint64_t>(config.limits.max_request_body_bytes)); beast::error_code read_ec; http::read(socket, buffer, parser, read_ec); if (read_ec == http::error::body_limit || read_ec == http::error::header_limit) { http::response<http::string_body> res{http::status::payload_too_large, 11}; res.set(http::field::content_type, "application/json"); res.set(http::field::server, "llm-manager"); res.keep_alive(false); res.body() = R"({"error":"Request too large"})"; res.prepare_payload(); beast::error_code write_ec; http::write(socket, res, write_ec); break; } if (read_ec) throw beast::system_error{read_ec};
http::request<http::string_body> req = parser.release(); const bool keep_alive = req.keep_alive(); auto res = handle_request(manager, config, auth, rate_limiter, registry, metrics, scheduler, std::move(req)); auto res = handle_request(deps, peer_address, std::move(req)); http::write(socket, res); if (!keep_alive || res.need_eof()) break; }2 unmodified lines3456789105 unmodified lines1617181920212223242526272829303132333418192021222324353637382728293031323334353940412 unmodified lines#include <boost/asio.hpp>#include <boost/beast/http.hpp>
#include <atomic>
#include "llm_manager_types.h"
class ModelManager;5 unmodified lines
namespace http = boost::beast::http;
// Everything a session needs; owned by main() for the process lifetime.struct ServerDeps { ModelManager &manager; const ManagerConfig &config; const ApiKeyAuth &auth; RateLimiterStore &rate_limiter; // Pre-auth per-source limiter (keyed by client address). RateLimiterStore &ip_rate_limiter; RequestRegistry ®istry; MetricsRegistry &metrics; Scheduler &scheduler; // Open sessions, for the connection cap. std::atomic<int> &active_sessions;};
http::response<http::string_body> handle_request( ModelManager &manager, const ManagerConfig &config, const ApiKeyAuth &auth, RateLimiterStore &rate_limiter, RequestRegistry ®istry, MetricsRegistry &metrics, Scheduler &scheduler, ServerDeps &deps, const std::string &peer_address, http::request<http::string_body> &&req);
void do_session( boost::asio::ip::tcp::socket socket, ModelManager &manager, const ManagerConfig &config, const ApiKeyAuth &auth, RateLimiterStore &rate_limiter, RequestRegistry ®istry, MetricsRegistry &metrics, Scheduler &scheduler);// Takes ownership of one accepted connection; decrements// deps.active_sessions on exit.void do_session(boost::asio::ip::tcp::socket socket, ServerDeps &deps);12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788#pragma once
// Minimal, dependency-free SHA-256 used to store and compare API key secrets// as digests. Not performance critical: one hash per authenticated request.
#include <array>#include <cstdint>#include <cstring>#include <string>
namespace sha256_detail {
inline uint32_t rotr(uint32_t x, uint32_t n) { return (x >> n) | (x << (32 - n)); }
constexpr uint32_t K[64] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
inline void compress(std::array<uint32_t, 8> &h, const uint8_t block[64]) { uint32_t w[64]; for (int i = 0; i < 16; ++i) { w[i] = (uint32_t(block[i * 4]) << 24) | (uint32_t(block[i * 4 + 1]) << 16) | (uint32_t(block[i * 4 + 2]) << 8) | uint32_t(block[i * 4 + 3]); } for (int i = 16; i < 64; ++i) { const uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); const uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); w[i] = w[i - 16] + s0 + w[i - 7] + s1; } uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]; for (int i = 0; i < 64; ++i) { const uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25); const uint32_t ch = (e & f) ^ (~e & g); const uint32_t t1 = hh + S1 + ch + K[i] + w[i]; const uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22); const uint32_t maj = (a & b) ^ (a & c) ^ (b & c); const uint32_t t2 = S0 + maj; hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; } h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh;}
} // namespace sha256_detail
// Lowercase hex digest of `input`.inline std::string sha256_hex(const std::string &input) { std::array<uint32_t, 8> h = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; const uint8_t *data = reinterpret_cast<const uint8_t *>(input.data()); size_t len = input.size(); while (len >= 64) { sha256_detail::compress(h, data); data += 64; len -= 64; } uint8_t block[128] = {0}; std::memcpy(block, data, len); block[len] = 0x80; const size_t total = (len + 1 + 8 <= 64) ? 64 : 128; const uint64_t bit_len = uint64_t(input.size()) * 8; for (int i = 0; i < 8; ++i) block[total - 1 - i] = uint8_t(bit_len >> (8 * i)); sha256_detail::compress(h, block); if (total == 128) sha256_detail::compress(h, block + 64);
static const char *digits = "0123456789abcdef"; std::string out; out.reserve(64); for (uint32_t v : h) { for (int shift = 28; shift >= 0; shift -= 4) out.push_back(digits[(v >> shift) & 0xF]); } return out;}
// Compares two strings without early exit on the first differing byte.inline bool constant_time_equals(const std::string &a, const std::string &b) { if (a.size() != b.size()) return false; unsigned char diff = 0; for (size_t i = 0; i < a.size(); ++i) { diff |= static_cast<unsigned char>(a[i]) ^ static_cast<unsigned char>(b[i]); } return diff == 0;}.gitignore+3
Dockerfile+21-15
README.md+32
config.toml.example+34-2
cpp/config.cpp+144-2
cpp/http_helpers.cpp+113-3
cpp/http_helpers.h+13-1
cpp/llm_manager.cpp+41-12
cpp/llm_manager_types.h+63
cpp/model_manager.cpp+5-4
cpp/request_parsing.cpp+36-12
cpp/request_parsing.h+4
cpp/runtime_components.cpp+43-10
cpp/runtime_components.h+4-1
cpp/server.cpp+156-60
cpp/server.h+22-16
cpp/sha256.hAdded+88