Spaces:
Sleeping
Sleeping
Dmitry Beresnev commited on
Commit ·
6dc320d
1
Parent(s): 6471a06
fix other security volnurabilities
Browse filesFiles changed (8)
123468 unmodified lines7374757677787968 unmodified lines148149150151152153FROM debian:bookworm-slim AS builder# Install build dependenciesRUN apt-get update && apt-get install -y --no-install-recommends \68 unmodified lines-o /build/llm-manager# Runtime stageFROM debian:bookworm-slim# Install runtime dependencies including SSL/HTTPS supportRUN apt-get update && apt-get install -y --no-install-recommends \68 unmodified lines# - 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 \1234568 unmodified lines7475767778798068 unmodified lines149150151152153154155# debian:bookworm-slim pinned by digest (resolved 2026-11-13). Bump deliberately.FROM debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc AS builder# Install build dependenciesRUN apt-get update && apt-get install -y --no-install-recommends \68 unmodified lines-o /build/llm-manager# Runtime stageFROM debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc# Install runtime dependencies including SSL/HTTPS supportRUN apt-get update && apt-get install -y --no-install-recommends \68 unmodified lines# - 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).# - 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 \
53 unmodified lines5455565758596053 unmodified lines| `[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`.## Features53 unmodified lines54555657585960616253 unmodified lines| `[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. To be able to cancel, send your own`X-Request-Id` header (8–64 chars of `[A-Za-z0-9_-]`) with the chat request and call`POST /requests/<that id>/cancel` with the same key; an id already in flight is refused with 409. The full audit and rationale is in`docs/SECURITY_AUDIT_AND_FIX_PLAN.md`.## Features
14 unmodified lines15161718192014 unmodified linesbind_host = "127.0.0.1"base_port = 8080switch_timeout_sec = 300[llama]n_ctx = 819214 unmodified lines151617181920212214 unmodified linesbind_host = "127.0.0.1"base_port = 8080switch_timeout_sec = 300# Refuse /switch-model when the model cache volume has less free space (MiB).min_free_disk_mb = 512[llama]n_ctx = 8192
314 unmodified lines315316317318319320314 unmodified linescfg.worker.bind_host = get_env_or("WORKER_BIND_HOST", get_toml_string_or(toml, "worker", "bind_host", cfg.worker.bind_host));cfg.worker.base_port = get_env_int_or("WORKER_BASE_PORT", get_toml_int_or(toml, "worker", "base_port", cfg.worker.base_port));cfg.worker.switch_timeout_sec = get_env_int_or("SWITCH_TIMEOUT_SEC", get_toml_int_or(toml, "worker", "switch_timeout_sec", cfg.worker.switch_timeout_sec));cfg.llama.n_ctx = get_env_int_or("MODEL_N_CTX", get_toml_int_or(toml, "llama", "n_ctx", cfg.llama.n_ctx));cfg.llama.threads = get_env_int_or("MODEL_THREADS", get_toml_int_or(toml, "llama", "threads", cfg.llama.threads));314 unmodified lines315316317318319320321314 unmodified linescfg.worker.bind_host = get_env_or("WORKER_BIND_HOST", get_toml_string_or(toml, "worker", "bind_host", cfg.worker.bind_host));cfg.worker.base_port = get_env_int_or("WORKER_BASE_PORT", get_toml_int_or(toml, "worker", "base_port", cfg.worker.base_port));cfg.worker.switch_timeout_sec = get_env_int_or("SWITCH_TIMEOUT_SEC", get_toml_int_or(toml, "worker", "switch_timeout_sec", cfg.worker.switch_timeout_sec));cfg.worker.min_free_disk_mb = std::max(0, get_env_int_or("MIN_FREE_DISK_MB", get_toml_int_or(toml, "worker", "min_free_disk_mb", cfg.worker.min_free_disk_mb)));cfg.llama.n_ctx = get_env_int_or("MODEL_N_CTX", get_toml_int_or(toml, "llama", "n_ctx", cfg.llama.n_ctx));cfg.llama.threads = get_env_int_or("MODEL_THREADS", get_toml_int_or(toml, "llama", "threads", cfg.llama.threads));
35 unmodified lines36373839404135 unmodified linesstd::string bind_host = "127.0.0.1";int base_port = 8080;int switch_timeout_sec = 300;};struct LlamaConfig {35 unmodified lines36373839404142434435 unmodified linesstd::string bind_host = "127.0.0.1";int base_port = 8080;int switch_timeout_sec = 300;// /switch-model is refused when the model cache volume has less than// this much free space (0 = no check).int min_free_disk_mb = 512;};struct LlamaConfig {
80 unmodified lines8182838485868780 unmodified linesctx->enqueue_time = ctx->created_at;std::lock_guard<std::mutex> lock(mu_);requests_[request_id] = ctx;return ctx;}80 unmodified lines81828384858687888980 unmodified linesctx->enqueue_time = ctx->created_at;std::lock_guard<std::mutex> lock(mu_);// Never overwrite an in-flight entry: a colliding (client-supplied) id// would otherwise let one caller detach another's request.if (!requests_.emplace(request_id, ctx).second) return nullptr;return ctx;}
40 unmodified lines41424344454640 unmodified linesclass RequestRegistry {public:std::shared_ptr<RequestContext> create(const std::string &request_id,const ApiKeyRecord &principal,40 unmodified lines4142434445464740 unmodified linesclass RequestRegistry {public:// Returns nullptr if `request_id` is already registered.std::shared_ptr<RequestContext> create(const std::string &request_id,const ApiKeyRecord &principal,
9 unmodified lines10111213141551 unmodified lines6768697071727374757677162 unmodified lines24024124224324424531 unmodified lines27727827928028128228314 unmodified lines298299300301302303304120 unmodified lines42542642742842943099 unmodified lines5305315325335345359 unmodified lines#include <algorithm>#include <atomic>#include <regex>#include <sstream>#include <unordered_set>51 unmodified lines}}int normalized_max_tokens = limits.default_max_tokens;if (payload.contains("n_predict") && payload["n_predict"].is_number_integer()) {normalized_max_tokens = payload["n_predict"].get<int>();} else if (payload.contains("max_tokens") && payload["max_tokens"].is_number_integer()) {normalized_max_tokens = payload["max_tokens"].get<int>();}if (normalized_max_tokens <= 0) {normalized_max_tokens = limits.default_max_tokens;162 unmodified linesreturn 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();}31 unmodified linesScheduler &scheduler = deps.scheduler;const auto start = std::chrono::steady_clock::now();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 auto query_pos = target.find('?');14 unmodified linesconst 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()));}120 unmodified lines{"allowed_models", config.models.allowed}});}std::string err;bool ok = manager.switch_model(model, err);if (!ok) {99 unmodified linesconst std::string upstream_request_body = payload.dump();auto ctx = registry.create(request_id, *authenticated, *estimate, upstream_request_body);// Once this handler returns, nobody can act on the request id anymore// (cancellation targets in-flight requests only), so drop the registry// entry on every exit path to keep the map bounded. The scheduler keeps9 unmodified lines1011121314151617181951 unmodified lines7172737475767778798081828384858687162 unmodified lines25025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428531 unmodified lines31731831932032132232332432532632732832933033133233333414 unmodified lines349350351352353354355356120 unmodified lines47747847948048148248348448548648748899 unmodified lines5885895905915925935945955965975989 unmodified lines#include <algorithm>#include <atomic>#include <cctype>#include <cstdint>#include <cstdlib>#include <filesystem>#include <regex>#include <sstream>#include <unordered_set>51 unmodified lines}}// Read in 64 bits so an oversized value is preserved (and then rejected// by estimate_chat_tokens) instead of being truncated into range.int64_t normalized_max_tokens = limits.default_max_tokens;auto read_int64 = [](const json &v) -> int64_t {if (v.is_number_unsigned() && v.get<uint64_t>() > static_cast<uint64_t>(INT64_MAX)) return INT64_MAX;return v.get<int64_t>();};if (payload.contains("n_predict") && payload["n_predict"].is_number_integer()) {normalized_max_tokens = read_int64(payload["n_predict"]);} else if (payload.contains("max_tokens") && payload["max_tokens"].is_number_integer()) {normalized_max_tokens = read_int64(payload["max_tokens"]);}if (normalized_max_tokens <= 0) {normalized_max_tokens = limits.default_max_tokens;162 unmodified linesreturn model.find("..") == std::string::npos;}// Client-chosen request ids: opaque tokens only, so they are safe in logs,// headers and the cancel URL.static bool is_valid_client_request_id(const std::string &id) {if (id.size() < 8 || id.size() > 64) return false;return std::all_of(id.begin(), id.end(), [](unsigned char c) {return std::isalnum(c) || c == '-' || c == '_';});}// Refuses a switch when the model cache volume is nearly full: -hf downloads// into LLAMA_CACHE and a failed download leaves partial files behind.static bool cache_has_free_space(int64_t min_free_bytes, std::string &detail) {if (min_free_bytes <= 0) return true;const char *cache = std::getenv("LLAMA_CACHE");std::string dir = cache && *cache ? cache : std::string();if (dir.empty()) {const char *home = std::getenv("HOME");dir = std::string(home && *home ? home : "/") + "/.cache/llama.cpp";}std::error_code ec;auto info = std::filesystem::space(dir, ec);if (ec) {// Unknown filesystem state: do not block the switch, but say so.detail = "unknown";return true;}detail = std::to_string(info.available / (1024 * 1024)) + " MiB free";return static_cast<int64_t>(info.available) >= min_free_bytes;}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();}31 unmodified linesScheduler &scheduler = deps.scheduler;const auto start = std::chrono::steady_clock::now();// Clients may pick their own id (X-Request-Id) so they can cancel an// in-flight request; otherwise one is generated. Duplicates are rejected// at registration so one key cannot hijack another's id.std::string request_id = generate_request_id();bool client_supplied_id = false;if (const auto it = req.find("X-Request-Id"); it != req.end()) {const std::string candidate = trim_copy(it->value().to_string());if (is_valid_client_request_id(candidate)) {request_id = candidate;client_supplied_id = true;}}const std::string target = req.target().to_string();const std::string method = req.method_string().to_string();const auto query_pos = target.find('?');14 unmodified linesconst 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()) +(client_supplied_id ? " client_request_id=true" : ""));if (config.logging.log_request_bodies && !req.body().empty()) {log_line("request_id=" + request_id + " body=" + truncate_body(req.body()));}120 unmodified lines{"allowed_models", config.models.allowed}});}std::string space_detail;if (!cache_has_free_space(static_cast<int64_t>(config.worker.min_free_disk_mb) * 1024 * 1024, space_detail)) {return json_response(http::status::insufficient_storage,{{"error", "Not enough free disk in model cache (" + space_detail + ")"}});}std::string err;bool ok = manager.switch_model(model, err);if (!ok) {99 unmodified linesconst std::string upstream_request_body = payload.dump();auto ctx = registry.create(request_id, *authenticated, *estimate, upstream_request_body);if (!ctx) {// Only reachable with a client-supplied id that is already in// flight (ours or another key's).return json_response(http::status::conflict, {{"error", "Request id already in flight"}});}// Once this handler returns, nobody can act on the request id anymore// (cancellation targets in-flight requests only), so drop the registry// entry on every exit path to keep the map bounded. The scheduler keeps
Dockerfile+4-2
README.md+3-1
config.toml.example+2
cpp/config.cpp+1
cpp/llm_manager_types.h+3
cpp/runtime_components.cpp+3-1
cpp/runtime_components.h+1
cpp/server.cpp+68-5