Spaces:
Sleeping
Sleeping
Dmitry Beresnev commited on
Commit ·
70dee29
1
Parent(s): 6dc320d
fix security volnurabilities
Browse filesFiles changed (11)
18 unmodified lines192021222324252627282930313280 unmodified lines1131141151161171181 unmodified line12012112212312412524 unmodified lines1501511521531541551562 unmodified lines15916016116216316416518 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=b12367#ARG BUILD_PROFILE=fast_buildARG BUILD_PROFILE=fast_runtimeARG BUILD_JOBS=1RUN git clone --depth 1 --branch ${LLAMA_CPP_REF} https://github.com/ggerganov/llama.cpp.git && \cd llama.cpp && \if [ "${BUILD_PROFILE}" = "fast_runtime" ]; then \C_FLAGS="-O3 -DNDEBUG"; \CXX_FLAGS="-O3 -DNDEBUG"; \80 unmodified linesEXPOSE 7860# Start FastAPI app (which manages llama-server internally)#CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]1 unmodified line# Keep the FastAPI CMD above as the default. Uncomment ONE of the following# to run the C++ server directly instead of the Python app.## Example DeepSeek (4k context):# CMD ["llama-server", "-hf", "TheBloke/deepseek-llm-7B-chat-GGUF:deepseek-llm-7b-chat.Q4_K_M.gguf",# "--host", "0.0.0.0", "--port", "7860", "-c", "4096", "-t", "4", "-ngl", "0", "--cont-batching", "-b", "512"]24 unmodified lines# - PER_IP_REQUESTS_PER_MINUTE is a pre-auth limit per client address# (X-Forwarded-For from the HF proxy).# - MIN_FREE_DISK_MB refuses a model switch when the cache volume is nearly full.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 \2 unmodified linesMANAGER_HOST=0.0.0.0 \MANAGER_PORT=7860 \WORKER_BASE_PORT=8080 \SWITCH_TIMEOUT_SEC=300 \REQUEST_TIMEOUT_SEC=300 \DEFAULT_MAX_TOKENS=2048 \MAX_TOKENS_PER_REQUEST=4096 \18 unmodified lines192021222324252627282930313233343580 unmodified lines1161171181191201211221231241251261271 unmodified line12913013113213313413524 unmodified lines1601611621631641651661671681691702 unmodified lines17317417517617717817918 unmodified lines# Clone and build llama.cpp with SSL support for HuggingFace HubWORKDIR /buildARG CACHEBUST=6# Pinned to an immutable commit (release tag b12367). Tags can be moved;# commits cannot. Bump deliberately and re-run the endpoint tests.ARG LLAMA_CPP_REF=fe14cad51bbfb3f1cc8d9cfd9d70e98a123743d3#ARG BUILD_PROFILE=fast_buildARG BUILD_PROFILE=fast_runtimeARG BUILD_JOBS=1RUN mkdir llama.cpp && cd llama.cpp && git init -q && \git remote add origin https://github.com/ggerganov/llama.cpp.git && \git fetch --depth 1 origin ${LLAMA_CPP_REF} && \git checkout -q FETCH_HEAD && \echo "llama.cpp commit: $(git rev-parse HEAD)" && \if [ "${BUILD_PROFILE}" = "fast_runtime" ]; then \C_FLAGS="-O3 -DNDEBUG"; \CXX_FLAGS="-O3 -DNDEBUG"; \80 unmodified linesEXPOSE 7860# The only supported entrypoint is the C++ manager (CMD at the bottom). The# legacy FastAPI app is unauthenticated and is not in this image.## Historical examples of running llama-server directly (unauthenticated —# do not use in production):# Start FastAPI app (which manages llama-server internally)#CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]1 unmodified line# Keep the FastAPI CMD above as the default. Uncomment ONE of the following# to run the C++ server directly instead of the Python app.## Example DeepSeek (4k context):# CMD ["llama-server", "-hf", "TheBloke/deepseek-llm-7B-chat-GGUF:deepseek-llm-7b-chat.Q4_K_M.gguf",# "--host", "0.0.0.0", "--port", "7860", "-c", "4096", "-t", "4", "-ngl", "0", "--cont-batching", "-b", "512"]24 unmodified lines# - PER_IP_REQUESTS_PER_MINUTE is a pre-auth limit per client address# (X-Forwarded-For from the HF proxy).# - MIN_FREE_DISK_MB refuses a model switch when the cache volume is nearly full.# - The allowlist below is the curated set from docs/MODEL_CANDIDATES_FREE_SPACE.md:# dense upgrades (Qwen3.5), MoE fast lanes (LFM2.5-8B-A1B, Granite 4.0 H-Tiny,# 1-1.5B active), Gemma 4, and one large MoE (Qwen3.6-35B-A3B at IQ3, 12.3 GiB)# that needs SWITCH_TIMEOUT_SEC >= 600 on a cold start.ENV ALLOWED_MODELS=QuantFactory/Qwen2.5-7B-Instruct-GGUF:q4_k_m,unsloth/Qwen3.5-9B-GGUF:Q4_K_M,unsloth/Qwen3.5-4B-GGUF:Q4_K_M,LiquidAI/LFM2.5-8B-A1B-GGUF:Q4_K_M,unsloth/granite-4.0-h-tiny-GGUF:Q4_K_M,unsloth/gemma-4-E4B-it-GGUF:Q4_K_M,unsloth/gemma-4-E2B-it-GGUF:Q4_K_M,unsloth/Qwen3.6-35B-A3B-GGUF:UD-IQ3_XXS \PER_IP_REQUESTS_PER_MINUTE=120 \MANAGER_MAX_SESSIONS=256 \MAX_REQUEST_BODY_BYTES=1048576 \2 unmodified linesMANAGER_HOST=0.0.0.0 \MANAGER_PORT=7860 \WORKER_BASE_PORT=8080 \SWITCH_TIMEOUT_SEC=600 \REQUEST_TIMEOUT_SEC=300 \DEFAULT_MAX_TOKENS=2048 \MAX_TOKENS_PER_REQUEST=4096 \
27 unmodified lines28293031323334177 unmodified lines21221321421521621721827 unmodified lines## 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:```bash177 unmodified lines- `admin`: can call privileged control endpoints- `user`: can submit chat requests and cancel owned requestsIf no API keys are configured, the manager currently stays in a compatibility mode and does not enforce auth.## Configuration27 unmodified lines2829303132333435177 unmodified lines21321421521621721821927 unmodified lines## 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, `/models`, `/queue/metrics`, `/props`, `/slots`,`/metrics`) returns 401. Only `/health` (liveness: status and switch flag) and the static web UI are public.Keys are never baked into the image. Configure them as an environment variable / HF Space secret:```bash177 unmodified lines- `admin`: can call privileged control endpoints- `user`: can submit chat requests and cancel owned requestsIf no usable API keys are configured the manager **fails closed**: every protected endpoint returns 401 (only `/health` and the static web UI stay public). Set `AUTH_ALLOW_ANONYMOUS=true` explicitly to allow unauthenticated callers with the user role.## Configuration
254 unmodified lines25525625725825926028 unmodified lines28929029129229329413 unmodified lines308309310311312313254 unmodified linesstatic 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");28 unmodified linesrecord.enabled = false;}}}}13 unmodified linescfg.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));254 unmodified lines25525625725825926026128 unmodified lines29029129229329429529629729829930030113 unmodified lines315316317318319320321322254 unmodified linesstatic 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;std::unordered_set<std::string> seen_digests;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");28 unmodified linesrecord.enabled = false;}}// The same secret under two ids (possibly two roles) is ambiguous:// whichever loaded first would silently win. Fail closed on the rest.if (record.enabled && !record.secret_sha256.empty() && !seen_digests.insert(record.secret_sha256).second) {log_line("config: api key '" + record.key_id + "' reuses another key's secret — disabled");record.enabled = false;}}}13 unmodified linescfg.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.server.header_timeout_sec = std::max(1, get_env_int_or("MANAGER_HEADER_TIMEOUT_SEC", get_toml_int_or(toml, "server", "header_timeout_sec", cfg.server.header_timeout_sec)));cfg.server.body_timeout_sec = std::max(cfg.server.header_timeout_sec, get_env_int_or("MANAGER_BODY_TIMEOUT_SEC", get_toml_int_or(toml, "server", "body_timeout_sec", cfg.server.body_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));
8 unmodified lines91011121314151617181920212233 unmodified lines56575859606162636465666768697071727374757677788 unmodified lines#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;33 unmodified linessetsockopt(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) {8 unmodified lines91011121314151617181920212223242533 unmodified lines59606162636465666768697071727374757677787980818283848586878889909192939495968 unmodified lines#include <ctime>#include <iomanip>#include <iostream>#include <cerrno>#include <fstream>#include <sstream>#include <stdexcept>#include <vector>#include <sys/socket.h>#include <sys/time.h>#if defined(__linux__)#include <sys/random.h>#endifnamespace asio = boost::asio;namespace beast = boost::beast;33 unmodified linessetsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char *>(&snd), sizeof(snd));}// Fills `out` from the operating system CSPRNG. Throws rather than falling// back to anything predictable.static void fill_os_random(unsigned char *out, size_t len) {#if defined(__linux__)size_t got = 0;while (got < len) {const ssize_t r = getrandom(out + got, len - got, 0);if (r < 0) {if (errno == EINTR) continue;break; // fall through to /dev/urandom}got += static_cast<size_t>(r);}if (got == len) return;#endifstd::ifstream urandom("/dev/urandom", std::ios::binary);if (!urandom.read(reinterpret_cast<char *>(out), static_cast<std::streamsize>(len))) {throw std::runtime_error("no OS random source available");}}std::string generate_request_id() {unsigned char bytes[16];fill_os_random(bytes, sizeof(bytes));static const char *digits = "0123456789abcdef";std::string out;out.reserve(32);for (unsigned char b : bytes) {out.push_back(digits[b >> 4]);out.push_back(digits[b & 0xF]);}return out;}std::optional<std::string> normalize_path(const std::string &raw_path) {
20 unmodified lines21222324252627282920 unmodified lines// 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 {20 unmodified lines212223242526272829303132333420 unmodified lines// Hard cap on concurrently open client connections (each one pins a// thread). Excess connections get a fast 503.int max_sessions = 256;// Idle timeout while waiting for the first byte of a request (keep-alive).int read_timeout_sec = 30;// Absolute deadlines, measured from the first byte of a request: the full// header must arrive within header_timeout_sec and the full body within// body_timeout_sec, however slowly bytes trickle in. Exceeding them gets// a 408 and the connection is closed.int header_timeout_sec = 10;int body_timeout_sec = 30;};struct WorkerConfig {
7 unmodified lines8910111213211 unmodified lines2252262272282292302312322332342352362372382392407 unmodified lines#include <cerrno>#include <csignal>#include <thread>#include <unistd.h>#include <sys/wait.h>211 unmodified linesfor (auto &s : args) argv.push_back(const_cast<char *>(s.c_str()));argv.push_back(nullptr);pid_t pid = fork();if (pid < 0) return -1;if (pid == 0) {setsid();execvp(argv[0], argv.data());_exit(127);}return pid;}bool ModelManager::wait_until_ready(pid_t pid, int port, int timeout_sec) {const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);// Exponential backoff: fast detection when the worker comes up (or dies)7 unmodified lines891011121314211 unmodified lines2262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982997 unmodified lines#include <cerrno>#include <csignal>#include <cstdlib>#include <thread>#include <unistd.h>#include <sys/wait.h>211 unmodified linesfor (auto &s : args) argv.push_back(const_cast<char *>(s.c_str()));argv.push_back(nullptr);// The worker parses untrusted model files and serves user prompts; it must// not inherit API_KEYS or any other manager secret. Hand it an explicit// allowlisted environment instead of ours.std::vector<std::string> env = worker_environment();std::vector<char *> envp;envp.reserve(env.size() + 1);for (auto &s : env) envp.push_back(const_cast<char *>(s.c_str()));envp.push_back(nullptr);// execve does not search PATH; resolve a bare binary name up front.const std::string resolved = resolve_executable(llama_server_bin_);if (resolved.empty()) return -1;pid_t pid = fork();if (pid < 0) return -1;if (pid == 0) {setsid();execve(resolved.c_str(), argv.data(), envp.data());_exit(127);}return pid;}extern "C" char **environ;// Variables the worker legitimately needs: locale, cache/home, the model// download path (HF token for private repos, proxies, CA bundle) and// llama.cpp/BLAS tuning knobs. Everything else, in particular API_KEYS and// MANAGER_*, is dropped.std::vector<std::string> ModelManager::worker_environment() {static const char *kExact[] = {"HOME", "PATH", "LANG", "TMPDIR", "TERM", "LD_LIBRARY_PATH", "LLAMA_CACHE","HF_TOKEN", "HF_HOME", "HF_HUB_CACHE", "HF_HUB_OFFLINE","CURL_CA_BUNDLE", "SSL_CERT_FILE", "SSL_CERT_DIR","HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy"};static const char *kPrefixes[] = {"LC_", "LLAMA_", "GGML_", "OMP_", "OPENBLAS_", "HF_HUB_"};std::vector<std::string> out;for (char **e = environ; e && *e; ++e) {const std::string entry(*e);const auto eq = entry.find('=');if (eq == std::string::npos) continue;const std::string name = entry.substr(0, eq);bool keep = false;for (const char *n : kExact) if (name == n) { keep = true; break; }for (const char *pfx : kPrefixes) if (!keep && name.rfind(pfx, 0) == 0) { keep = true; break; }if (keep) out.push_back(entry);}return out;}std::string ModelManager::resolve_executable(const std::string &bin) {if (bin.find('/') != std::string::npos) return bin;const char *path = std::getenv("PATH");std::string search = path ? path : "/usr/local/bin:/usr/bin:/bin";size_t start = 0;while (start <= search.size()) {const auto end = search.find(':', start);const std::string dir = search.substr(start, end == std::string::npos ? std::string::npos : end - start);if (!dir.empty()) {const std::string candidate = dir + "/" + bin;if (access(candidate.c_str(), X_OK) == 0) return candidate;}if (end == std::string::npos) break;start = end + 1;}return "";}bool ModelManager::wait_until_ready(pid_t pid, int port, int timeout_sec) {const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);// Exponential backoff: fast detection when the worker comes up (or dies)
3 unmodified lines45678930 unmodified lines4041424344453 unmodified lines#include <optional>#include <string>#include <utility>#include "llm_manager_types.h"30 unmodified linesint allocate_port();void finish_switch(bool ok);pid_t spawn_worker(const std::string &model, int port);bool wait_until_ready(pid_t pid, int port, int timeout_sec);std::pair<int, std::string> http_get(int port, const std::string &target);};3 unmodified lines4567891030 unmodified lines4142434445464748493 unmodified lines#include <optional>#include <string>#include <utility>#include <vector>#include "llm_manager_types.h"30 unmodified linesint allocate_port();void finish_switch(bool ok);pid_t spawn_worker(const std::string &model, int port);// Allowlisted copy of our environment for the worker (no manager secrets).static std::vector<std::string> worker_environment();static std::string resolve_executable(const std::string &bin);bool wait_until_ready(pid_t pid, int port, int timeout_sec);std::pair<int, std::string> http_get(int port, const std::string &target);};
18 unmodified lines192021222324252620 unmodified lines47484950515218 unmodified linesif (requests_per_minute_ <= 0 && estimated_tokens_per_minute_ <= 0) return {};std::lock_guard<std::mutex> lock(mu_);auto &bucket = buckets_[api_key_id];const auto now = std::chrono::steady_clock::now();refill(bucket.request_tokens, bucket.last_request_refill, requests_per_minute_, now);refill(bucket.estimated_tokens, bucket.last_estimated_refill, estimated_tokens_per_minute_, now);20 unmodified linesreturn {};}void RateLimiterStore::refill(double &tokens,std::chrono::steady_clock::time_point &last_refill,18 unmodified lines19202122232425262728293020 unmodified lines515253545556575859606162636465666768697071727318 unmodified linesif (requests_per_minute_ <= 0 && estimated_tokens_per_minute_ <= 0) return {};std::lock_guard<std::mutex> lock(mu_);const auto now = std::chrono::steady_clock::now();if (buckets_.size() >= kMaxBuckets && buckets_.find(api_key_id) == buckets_.end()) {prune_idle(now);}auto &bucket = buckets_[api_key_id];bucket.last_seen = now;refill(bucket.request_tokens, bucket.last_request_refill, requests_per_minute_, now);refill(bucket.estimated_tokens, bucket.last_estimated_refill, estimated_tokens_per_minute_, now);20 unmodified linesreturn {};}void RateLimiterStore::prune_idle(std::chrono::steady_clock::time_point now) {for (auto it = buckets_.begin(); it != buckets_.end();) {if (now - it->second.last_seen > kIdleEvict) it = buckets_.erase(it);else ++it;}// Still full of active keys: drop the oldest ones so the map stays bounded// even under a flood of fresh sources. Those sources merely get a fresh// (full) bucket, which is no worse than before they were seen.while (buckets_.size() >= kMaxBuckets) {auto oldest = buckets_.begin();for (auto it = buckets_.begin(); it != buckets_.end(); ++it) {if (it->second.last_seen < oldest->second.last_seen) oldest = it;}buckets_.erase(oldest);}}void RateLimiterStore::refill(double &tokens,std::chrono::steady_clock::time_point &last_refill,
24 unmodified lines2526272829303132333435363724 unmodified linesdouble estimated_tokens = 0.0;std::chrono::steady_clock::time_point last_request_refill{};std::chrono::steady_clock::time_point last_estimated_refill{};};std::mutex mu_;std::unordered_map<std::string, Bucket> buckets_;int requests_per_minute_;int estimated_tokens_per_minute_;static void refill(double &tokens,std::chrono::steady_clock::time_point &last_refill,24 unmodified lines2526272829303132333435363738394041424344454624 unmodified linesdouble estimated_tokens = 0.0;std::chrono::steady_clock::time_point last_request_refill{};std::chrono::steady_clock::time_point last_estimated_refill{};std::chrono::steady_clock::time_point last_seen{};};// Bound on distinct keys kept (per-IP limiting sees arbitrary many// sources). Above this, buckets idle longer than kIdleEvict are dropped;// an idle bucket is full anyway, so evicting it changes nothing.static constexpr size_t kMaxBuckets = 10000;static constexpr std::chrono::seconds kIdleEvict{120};std::mutex mu_;std::unordered_map<std::string, Bucket> buckets_;int requests_per_minute_;int estimated_tokens_per_minute_;void prune_idle(std::chrono::steady_clock::time_point now);static void refill(double &tokens,std::chrono::steady_clock::time_point &last_refill,
283 unmodified lines2842852862872882892902912922 unmodified lines295296297298299300301302303304127 unmodified lines432433434435436437438439440441442443444445230 unmodified lines67667767867968068168268368440 unmodified lines72572672772872973073117 unmodified lines7497507517527537547557567572 unmodified lines7607617627637647652 unmodified lines76876977077177277377477577677777877978078178278378412 unmodified lines797798799800801802283 unmodified linesreturn 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,2 unmodified linesconst 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;127 unmodified lines}if (path == "/health" && req.method() == http::verb::get) {return json_response(http::status::ok, manager.models_view());}if (path == "/models" && req.method() == http::verb::get) {return json_response(http::status::ok, manager.models_view());}if (path == "/queue/metrics" && req.method() == http::verb::get) {http::response<http::string_body> res{http::status::ok, req.version()};res.set(http::field::content_type, "text/plain; version=0.0.4; charset=utf-8");res.set(http::field::server, "llm-manager");230 unmodified lines" final_state=" + state_to_string(final_state) +" upstream_status=" + std::to_string(result.status) +" elapsed_ms=" + std::to_string(elapsed_ms));if (result.status >= 400) {log_line("request_id=" + request_id +" upstream_error_body=" + truncate_body(result.body));}return res;}40 unmodified lines" elapsed_ms=" + std::to_string(elapsed_ms));if (upstream.status >= 400) {log_line("request_id=" + request_id +" proxied_get_error_body=" + truncate_body(upstream.body));}return res;}17 unmodified lines} 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;{2 unmodified linesif (!ec) peer_address = endpoint.address().to_string();}try {beast::flat_buffer buffer;for (;;) {2 unmodified lineshttp::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};12 unmodified lines// would_block/try_again family, which is the SO_RCVTIMEO receive timeout// firing on an idle keep-alive connection. Neither is a real error.if (e.code() != http::error::end_of_stream &&e.code() != boost::asio::error::would_block &&e.code() != boost::asio::error::try_again &&e.code() != boost::asio::error::timed_out)283 unmodified lines2842852862872882892902912922932 unmodified lines296297298299300301302303304305306307308309310311312127 unmodified lines440441442443444445446447448449450451452453454455456457458459460461230 unmodified lines69269369469569669769869970070170270340 unmodified lines74474574674774874975075117 unmodified lines7697707717727737747752 unmodified lines7787797807817827837847857867877887897907917927937942 unmodified lines79779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385412 unmodified lines867868869870871872873283 unmodified linesreturn std::find(models.allowed.begin(), models.allowed.end(), model) != models.allowed.end();}// Resolves the client address used for per-source rate limiting. Behind a// trusted reverse proxy (HF Spaces) the proxy appends the real client to// X-Forwarded-For, so the LAST hop is the one it vouches for; anything// before it was supplied by the client and must not be trusted.static std::string client_address(const http::request<http::string_body> &req,const std::string &peer_address,2 unmodified linesconst auto it = req.find("X-Forwarded-For");if (it != req.end()) {std::string value = it->value().to_string();const auto comma = value.rfind(',');if (comma != std::string::npos) value = value.substr(comma + 1);value = trim_copy(value);// Only accept something that looks like an address: digits, hex,// dots and colons. Anything else falls back to the TCP peer so a// client cannot pick an arbitrary bucket key.const bool address_like = !value.empty() && value.size() <= 45 &&std::all_of(value.begin(), value.end(), [](unsigned char c) {return std::isxdigit(c) || c == '.' || c == ':';});if (address_like) return value;}}return peer_address;127 unmodified lines}if (path == "/health" && req.method() == http::verb::get) {// Public liveness only: which model is loaded, counters and// internals are behind a key (/models, /queue/metrics).const auto view = manager.models_view();return json_response(http::status::ok, {{"status", view.value("status", "unknown")},{"switch_in_progress", view.value("switch_in_progress", false)}});}if (path == "/models" && req.method() == http::verb::get) {if (auto auth_res = ensure_authenticated(Role::USER)) return *auth_res;return json_response(http::status::ok, manager.models_view());}if (path == "/queue/metrics" && req.method() == http::verb::get) {if (auto auth_res = ensure_authenticated(Role::USER)) return *auth_res;http::response<http::string_body> res{http::status::ok, req.version()};res.set(http::field::content_type, "text/plain; version=0.0.4; charset=utf-8");res.set(http::field::server, "llm-manager");230 unmodified lines" final_state=" + state_to_string(final_state) +" upstream_status=" + std::to_string(result.status) +" elapsed_ms=" + std::to_string(elapsed_ms));// Upstream error bodies can echo user content; status and size// are enough unless body logging is explicitly on.if (result.status >= 400) {log_line("request_id=" + request_id +" upstream_error_bytes=" + std::to_string(result.body.size()) +(config.logging.log_request_bodies ? " upstream_error_body=" + truncate_body(result.body) : ""));}return res;}40 unmodified lines" elapsed_ms=" + std::to_string(elapsed_ms));if (upstream.status >= 400) {log_line("request_id=" + request_id +" proxied_get_error_bytes=" + std::to_string(upstream.body.size()) +(config.logging.log_request_bodies ? " proxied_get_error_body=" + truncate_body(upstream.body) : ""));}return res;}17 unmodified lines} session_guard{deps.active_sessions};const ManagerConfig &config = deps.config;using clock = std::chrono::steady_clock;std::string peer_address;{2 unmodified linesif (!ec) peer_address = endpoint.address().to_string();}auto write_and_close = [&](http::status status, const char *body) {http::response<http::string_body> res{status, 11};res.set(http::field::content_type, "application/json");res.set(http::field::server, "llm-manager");res.keep_alive(false);res.body() = body;res.prepare_payload();beast::error_code write_ec;http::write(socket, res, write_ec);};try {beast::flat_buffer buffer;for (;;) {2 unmodified lineshttp::request_parser<http::string_body> parser;parser.header_limit(16 * 1024);parser.body_limit(static_cast<uint64_t>(config.limits.max_request_body_bytes));// Read in pieces so an absolute deadline can be enforced. Before// the first byte only the idle timeout applies (keep-alive); from// the first byte on, the header and then the whole message must// complete within fixed budgets regardless of how slowly bytes// arrive. SO_RCVTIMEO is re-armed each iteration to the smaller of// the idle timeout and the time left on the deadline.beast::error_code read_ec;clock::time_point first_byte{};bool deadline_exceeded = false;bool idle_closed = false;while (!parser.is_done()) {const auto now = clock::now();long wait_sec = config.server.read_timeout_sec;if (first_byte == clock::time_point{} && (parser.got_some() || buffer.size() > 0)) {first_byte = now;}if (first_byte != clock::time_point{}) {const int budget = parser.is_header_done() ? config.server.body_timeout_sec: config.server.header_timeout_sec;const auto limit = first_byte + std::chrono::seconds(budget);if (now >= limit) {deadline_exceeded = true;break;}const long remaining = std::chrono::duration_cast<std::chrono::seconds>(limit - now).count() + 1;wait_sec = std::min(wait_sec, remaining);}set_socket_timeouts(socket.native_handle(), static_cast<int>(std::max(1L, wait_sec)), 60);read_ec = {};http::read_some(socket, buffer, parser, read_ec);if (read_ec == boost::asio::error::would_block ||read_ec == boost::asio::error::try_again ||read_ec == boost::asio::error::timed_out) {if (first_byte == clock::time_point{}) {idle_closed = true; // nothing started; plain keep-alive expirybreak;}continue; // deadline is re-checked at the top of the loop}if (read_ec) break;}if (idle_closed) break;if (deadline_exceeded) {log_line("session: request read deadline exceeded peer=" + peer_address);write_and_close(http::status::request_timeout, R"({"error":"Request read timed out"})");break;}if (read_ec == http::error::body_limit || read_ec == http::error::header_limit) {write_and_close(http::status::payload_too_large, R"({"error":"Request too large"})");break;}if (read_ec) throw beast::system_error{read_ec};12 unmodified lines// would_block/try_again family, which is the SO_RCVTIMEO receive timeout// firing on an idle keep-alive connection. Neither is a real error.if (e.code() != http::error::end_of_stream &&e.code() != http::error::partial_message &&e.code() != boost::asio::error::would_block &&e.code() != boost::asio::error::try_again &&e.code() != boost::asio::error::timed_out)
21 unmodified lines22232425262782 unmodified lines11011111211311411511621 unmodified lineslogger = get_logger(__name__)app = FastAPI(title="AGI Multi-Model API",description="""82 unmodified linesPRELOAD_MODELS = os.getenv("PRELOAD_MODELS", "").split(",") if os.getenv("PRELOAD_MODELS") else []WEB_SEARCH_CACHE_TTL = int(os.getenv("WEB_SEARCH_CACHE_TTL", "3600")) # 1 hourREQUEST_TIMEOUT = int(os.getenv("REQUEST_TIMEOUT", "300")) # 5 minutesLOG_REQUEST_BODY = os.getenv("LOG_REQUEST_BODY", "1") == "1"LOG_REQUEST_BODY_MAX_CHARS = int(os.getenv("LOG_REQUEST_BODY_MAX_CHARS", "2000"))CONTEXT_SIZE = int(os.getenv("CONTEXT_SIZE", "2048"))21 unmodified lines2223242526272829303132333435363782 unmodified lines12012112212312412512621 unmodified lineslogger = get_logger(__name__)# This legacy app has NO authentication: /switch-model, /cache/clear and the# chat routes are public, and web-chat forwards queries to an external search# provider. It is kept for reference only and is not part of the Docker image.# Refuse to start unless the operator explicitly acknowledges that.if os.getenv("LEGACY_UNAUTHENTICATED_APP_ACK") != "1":raise RuntimeError("python/app.py is the unauthenticated legacy service. Use the C++ llm-manager, ""or set LEGACY_UNAUTHENTICATED_APP_ACK=1 to run this on a trusted network only.")app = FastAPI(title="AGI Multi-Model API",description="""82 unmodified linesPRELOAD_MODELS = os.getenv("PRELOAD_MODELS", "").split(",") if os.getenv("PRELOAD_MODELS") else []WEB_SEARCH_CACHE_TTL = int(os.getenv("WEB_SEARCH_CACHE_TTL", "3600")) # 1 hourREQUEST_TIMEOUT = int(os.getenv("REQUEST_TIMEOUT", "300")) # 5 minutesLOG_REQUEST_BODY = os.getenv("LOG_REQUEST_BODY", "0") == "1" # prompts are user data; opt-in onlyLOG_REQUEST_BODY_MAX_CHARS = int(os.getenv("LOG_REQUEST_BODY_MAX_CHARS", "2000"))CONTEXT_SIZE = int(os.getenv("CONTEXT_SIZE", "2048"))
Dockerfile+21-7
README.md+3-2
cpp/config.cpp+9
cpp/http_helpers.cpp+35-17
cpp/llm_manager_types.h+7-2
cpp/model_manager.cpp+60-1
cpp/model_manager.h+4
cpp/runtime_components.cpp+22-1
cpp/runtime_components.h+9
cpp/server.cpp+92-21
python/app.py+11-1