Skip to content

Distribute and run LLMs with a single file.

Add HTTPS support via cpp-httplib's mbedtls backend (#1011)

Davide Eynarda03a7c832733
diff --git a/llama.cpp.patches/README.md b/llama.cpp.patches/README.md
index 17cdc695..1f96e6e5 100644
--- a/llama.cpp.patches/README.md
+++ b/llama.cpp.patches/README.md
@@ -86,7 +86,29 @@ Cosmopolitan libc has specific behaviors with condition variables and signals th
| `common_log.cpp.patch` | Adds `#include <csignal>`; blocks `SIGINT`/`SIGTERM` on logger thread via `pthread_sigmask` to prevent `EINTR` exceptions; replaces `cv.wait()` with `wait_for(30s)` loop to work around XNU futex timeout bug (~72 minute expiry) |
| `tools_server_server-models.cpp.patch` | Adds `#include <csignal>`; blocks signals on the stopping thread via `pthread_sigmask`; replaces untimed `cv.wait()` with `wait_for(30s)` loops on every model-lifecycle wait (`unload_lru`, the reload-drain wait, `stopping_thread`, the `is_reloading` guard in `load`, and the generic `wait()` predicate helper) to work around the XNU futex timeout bug |
| `tools_server_server-queue.cpp.patch` | Adds missing includes (`<cerrno>`, `<system_error>`, `<csignal>`); blocks `SIGINT`/`SIGTERM` on queue thread; replaces `wait()` with `wait_for()` loops in three locations (`wait_until_no_sleep`, main loop, `recv`) |
-| `vendor_cpp-httplib_httplib.cpp.patch` | Fixes httplib thread pool with `wait_for()` instead of `wait()` for XNU futex compatibility |
+| `vendor_cpp-httplib_httplib.cpp.patch` | Fixes httplib thread pool with `wait_for()` instead of `wait()` for XNU futex compatibility; also see HTTPS / TLS Support below |
+
+### HTTPS / TLS Support
+
+Upstream llama.cpp gets TLS from cpp-httplib's OpenSSL backend
+(`CPPHTTPLIB_OPENSSL_SUPPORT`, satisfied by system OpenSSL or vendored
+BoringSSL/LibreSSL at cmake time). None of those is available in the
+cosmocc make build, so llamafile instead enables cpp-httplib's **Mbed TLS
+backend** (`CPPHTTPLIB_MBEDTLS_SUPPORT`) against the mbedtls fork already
+vendored in `third_party/mbedtls` — the same TLS stack llamafile <= 0.9.3
+used. `third_party/mbedtls/include/` maps the canonical `<mbedtls/*.h>`
+include paths onto the fork's headers, and `BUILD.mk` sets the macro on
+every object that can reach `httplib.h` (the macro changes httplib class
+layouts, so all TUs must agree) and links `mbedtls.a` into `llama-server`.
+This enables HTTPS model downloads (`-hf`, `--model-url`), https clients
+in server-models, and TLS serving via `--ssl-cert-file`/`--ssl-key-file`.
+
+| Patch | Description |
+|-------|-------------|
+| `common_http.h.patch` | `#ifndef CPPHTTPLIB_OPENSSL_SUPPORT` -> `#ifndef CPPHTTPLIB_SSL_ENABLED` for the "HTTPS is not supported" guard, so any cpp-httplib TLS backend counts (candidate for upstreaming) |
+| `tools_server_server-http.cpp.patch` | Same macro fix for the `httplib::SSLServer` (`--ssl-cert-file`/`--ssl-key-file`) guard (candidate for upstreaming) |
+| `tools_server_server-models.cpp.patch` | Same macro fix for the direct `httplib::SSLClient` construction in `server_http_proxy` (candidate for upstreaming) |
+| `vendor_cpp-httplib_httplib.cpp.patch` | Under `__COSMOPOLITAN__`: appends `/zip/third_party/mbedtls/sslroot` to `system_ca_dirs()` as the trust-store fallback (essential on Windows hosts, where the `_WIN32` cert-store branches are not compiled into an APE), and `__static_yoink("ssl_root_support")` so the Mozilla root PEMs bundled by `third_party/mbedtls/BUILD.mk` are pulled into the executable's zip |
### TinyBLAS Integration
diff --git a/llama.cpp.patches/llamafile-files/BUILD.mk b/llama.cpp.patches/llamafile-files/BUILD.mk
index 32ab1470..0a23aca5 100644
--- a/llama.cpp.patches/llamafile-files/BUILD.mk
+++ b/llama.cpp.patches/llamafile-files/BUILD.mk
@@ -460,6 +460,19 @@ $(TOOL_PERPLEXITY_OBJS) $(TOOL_BENCH_OBJS) $(TOOL_SERVER_OBJS) $(MTMD_OBJS): \
-iquote $(UI_GEN_DIR) \
-isystem llama.cpp/vendor
+# HTTPS support: build cpp-httplib with its Mbed TLS backend against the
+# mbedtls vendored in third_party/mbedtls (the same TLS stack llamafile
+# <= 0.9.3 used); third_party/mbedtls/include maps the canonical
+# <mbedtls/*.h> include paths onto it. The macro changes httplib class
+# layouts, so every object that includes httplib.h (directly or via
+# common/http.h, server-http.h, server-cors-proxy.h) must see it.
+$(LLAMA_CPP_OBJS) $(TOOL_QUANTIZE_OBJS) $(TOOL_IMATRIX_OBJS) \
+$(TOOL_PERPLEXITY_OBJS) $(TOOL_BENCH_OBJS) $(TOOL_SERVER_OBJS) $(MTMD_OBJS) \
+$(HTTPLIB_OBJS): \
+ private CPPFLAGS += \
+ -DCPPHTTPLIB_MBEDTLS_SUPPORT \
+ -isystem third_party/mbedtls/include
+
# Server needs llamafile headers for Metal support.
# The generated ui.h sits in $(UI_GEN_DIR); the -iquote above lets every
# server source resolve `#include "ui.h"`.
@@ -576,9 +589,10 @@ o/$(MODE)/llama.cpp/server/llama-server: \
$(HTTPLIB_OBJS) \
$(TOOL_LLAMAFILE_OBJS) \
$$(TINYBLAS_CPU_OBJS) \
- o/$(MODE)/llama.cpp/llama.cpp.a
+ o/$(MODE)/llama.cpp/llama.cpp.a \
+ o/$(MODE)/third_party/mbedtls/mbedtls.a
@mkdir -p $(dir $@)
- $(LINK.o) $(TOOL_SERVER_OBJS) $(UI_GEN_OBJ) $(MTMD_OBJS) $(HTTPLIB_OBJS) $(TOOL_LLAMAFILE_OBJS) $(TINYBLAS_CPU_OBJS) o/$(MODE)/llama.cpp/llama.cpp.a $(LOADLIBES) $(LDLIBS) -o $@
+ $(LINK.o) $(TOOL_SERVER_OBJS) $(UI_GEN_OBJ) $(MTMD_OBJS) $(HTTPLIB_OBJS) $(TOOL_LLAMAFILE_OBJS) $(TINYBLAS_CPU_OBJS) o/$(MODE)/llama.cpp/llama.cpp.a o/$(MODE)/third_party/mbedtls/mbedtls.a $(LOADLIBES) $(LDLIBS) -o $@
# ==============================================================================
# Dependencies
diff --git a/llama.cpp.patches/patches/common_http.h.patch b/llama.cpp.patches/patches/common_http.h.patch
new file mode 100644
index 00000000..5aa4236a
--- /dev/null
+++ b/llama.cpp.patches/patches/common_http.h.patch
@@ -0,0 +1,12 @@
+diff --git a/common/http.h b/common/http.h
+--- a/llama.cpp/common/http.h
++++ b/llama.cpp/common/http.h
+@@ -72,7 +72,7 @@ static std::pair<httplib::Client, common_http_url> common_http_client(const std:
+ throw std::runtime_error("error: invalid URL format");
+ }
+
+-#ifndef CPPHTTPLIB_OPENSSL_SUPPORT
++#ifndef CPPHTTPLIB_SSL_ENABLED
+ if (parts.scheme == "https") {
+ throw std::runtime_error(
+ "HTTPS is not supported. Please rebuild with one of:\n"
diff --git a/llama.cpp.patches/patches/tools_server_server-http.cpp.patch b/llama.cpp.patches/patches/tools_server_server-http.cpp.patch
new file mode 100644
index 00000000..3db61c8c
--- /dev/null
+++ b/llama.cpp.patches/patches/tools_server_server-http.cpp.patch
@@ -0,0 +1,12 @@
+diff --git a/tools/server/server-http.cpp b/tools/server/server-http.cpp
+--- a/llama.cpp/tools/server/server-http.cpp
++++ b/llama.cpp/tools/server/server-http.cpp
+@@ -93,7 +93,7 @@ bool server_http_context::init(const common_params & params) {
+
+ auto & srv = pimpl->srv;
+
+-#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
++#ifdef CPPHTTPLIB_SSL_ENABLED
+ if (!params.ssl_file_key.empty() && !params.ssl_file_cert.empty()) {
+ SRV_INF("running with SSL: key = %s, cert = %s\n", params.ssl_file_key.c_str(), params.ssl_file_cert.c_str());
+ srv = std::make_unique<httplib::SSLServer>(
diff --git a/llama.cpp.patches/patches/tools_server_server-models.cpp.patch b/llama.cpp.patches/patches/tools_server_server-models.cpp.patch
index 98f7b7e7..8943db45 100644
--- a/llama.cpp.patches/patches/tools_server_server-models.cpp.patch
+++ b/llama.cpp.patches/patches/tools_server_server-models.cpp.patch
@@ -120,3 +120,16 @@ diff --git a/tools/server/server-models.cpp b/tools/server/server-models.cpp
}
bool server_models::ensure_model_ready(const std::string & name) {
+@@ -1894,10 +1928,10 @@ server_http_proxy::server_http_proxy(
+ auto pipe = std::make_shared<pipe_t<msg_t>>();
+
+ if (scheme == "https") {
+-#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
++#ifdef CPPHTTPLIB_SSL_ENABLED
+ cli.reset(new httplib::SSLClient(host, port));
+ #else
+- throw std::runtime_error("HTTPS requested but CPPHTTPLIB_OPENSSL_SUPPORT is not defined");
++ throw std::runtime_error("HTTPS requested but the server is built without SSL support");
+ #endif
+ }
+
diff --git a/llama.cpp.patches/patches/vendor_cpp-httplib_httplib.cpp.patch b/llama.cpp.patches/patches/vendor_cpp-httplib_httplib.cpp.patch
index d5b4dcf1..88a2de27 100644
--- a/llama.cpp.patches/patches/vendor_cpp-httplib_httplib.cpp.patch
+++ b/llama.cpp.patches/patches/vendor_cpp-httplib_httplib.cpp.patch
@@ -39,3 +39,28 @@ diff --git a/vendor/cpp-httplib/httplib.cpp b/vendor/cpp-httplib/httplib.cpp
}
idle_thread_count_--;
+@@ -12625,6 +12647,13 @@ bool enumerate_macos_keychain_certs(Callback cb) {
+
+ #if !defined(_WIN32) && !(defined(__APPLE__) && \
+ defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
++#ifdef __COSMOPOLITAN__
++// Reference the Mozilla CA roots zipped into the APE (see llamafile's
++// third_party/mbedtls/sslroot) so the linker keeps them; they serve as
++// the trust-store fallback below on hosts without a system CA store
++// (notably Windows, where the _WIN32 branches above are not compiled).
++__static_yoink("ssl_root_support");
++#endif
+ // Common CA certificate file paths on Linux/Unix
+ const char **system_ca_paths() {
+ static const char *paths[] = {
+@@ -12642,6 +12671,10 @@ const char **system_ca_dirs() {
+ static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
+ "/etc/pki/tls/certs", // RHEL/CentOS
+ "/usr/share/ca-certificates", // Other
++#ifdef __COSMOPOLITAN__
++ // CA bundle zipped into the APE (llamafile)
++ "/zip/third_party/mbedtls/sslroot",
++#endif
+ nullptr};
+ return dirs;
+ }
diff --git a/llamafile/BUILD.mk b/llamafile/BUILD.mk
index 464aa27d..bafde492 100644
--- a/llamafile/BUILD.mk
+++ b/llamafile/BUILD.mk
@@ -62,6 +62,20 @@ LLAMAFILE_CPPFLAGS := \
-DLLAMAFILE_TUI \
-DCOSMOCC=1
+# Flags for every TU that includes httplib.h: cpp-httplib is built with its
+# Mbed TLS backend (see llama.cpp/BUILD.mk), and CPPHTTPLIB_MBEDTLS_SUPPORT
+# changes httplib class layouts (e.g. httplib::Result, httplib::Client), so
+# an includer compiled without it corrupts memory when it exchanges those
+# types with httplib.cpp. If you add an httplib include to a llamafile
+# source, add its object below next to the chatbot ones.
+# -iquote . and -mcosmo are for the vendored mbedtls headers themselves
+# (repo-rooted internal includes, cosmo-extension macros).
+LLAMAFILE_HTTPLIB_TLS_FLAGS := \
+ -DCPPHTTPLIB_MBEDTLS_SUPPORT \
+ -isystem third_party/mbedtls/include \
+ -iquote . \
+ -mcosmo
+
# ==============================================================================
# Source files - Highlight library
# ==============================================================================
@@ -285,17 +299,21 @@ LLAMAFILE_DEPS = \
$(LLAMAFILE_HIGHLIGHT_KEYWORDS) \
$(LLAMAFILE_METAL_SOURCES) \
$(TINYBLAS_CPU_OBJS) \
- o/$(MODE)/third_party/stb/stb_image_resize2.o
+ o/$(MODE)/third_party/stb/stb_image_resize2.o \
+ o/$(MODE)/third_party/mbedtls/mbedtls.a
# ==============================================================================
# Server integration
# ==============================================================================
-# Include paths needed for server compilation
+# Include paths needed for server compilation. server.cpp reaches
+# httplib.h via server-cors-proxy.h, so it needs the httplib TLS flags
+# (see LLAMAFILE_HTTPLIB_TLS_FLAGS above).
LLAMAFILE_SERVER_INCS := \
$(LLAMAFILE_INCLUDES) \
-iquote llama.cpp/tools/server \
- -iquote o/$(MODE)/llama.cpp/tools/server
+ -iquote o/$(MODE)/llama.cpp/tools/server \
+ $(LLAMAFILE_HTTPLIB_TLS_FLAGS)
# Compile server.cpp
o/$(MODE)/llamafile/server.cpp.o: llama.cpp/tools/server/server.cpp
@@ -317,7 +335,7 @@ o/$(MODE)/llamafile/llamafile: \
$(LLAMAFILE_OBJS) \
$(LLAMAFILE_DEPS)
@mkdir -p $(@D)
- $(CXX) $(LDFLAGS) -o $@ $(filter %.o,$^) $(LDLIBS)
+ $(CXX) $(LDFLAGS) -o $@ $(filter %.o %.a,$^) $(LDLIBS)
# ==============================================================================
# Pattern rules for llamafile sources
@@ -354,6 +372,13 @@ LLAMAFILE_GPU_OBJS := \
o/$(MODE)/llamafile/gpu.a: $(LLAMAFILE_GPU_OBJS)
+# The TUI chatbot talks to the server through httplib as an HTTP client,
+# so its objects must agree with httplib.cpp on the httplib class layouts
+# (see LLAMAFILE_HTTPLIB_TLS_FLAGS).
+o/$(MODE)/llamafile/chatbot_api.o \
+o/$(MODE)/llamafile/chatbot_main.o: private \
+ LLAMAFILE_CPPFLAGS += $(LLAMAFILE_HTTPLIB_TLS_FLAGS)
+
o/$(MODE)/llamafile/%.o: llamafile/%.cpp
@mkdir -p $(@D)
$(CXX) $(CXXFLAGS) $(LLAMAFILE_CPPFLAGS) -c -o $@ $<
diff --git a/llamafile/args.cpp b/llamafile/args.cpp
index 2ec119eb..8f78367a 100644
--- a/llamafile/args.cpp
+++ b/llamafile/args.cpp
@@ -57,6 +57,11 @@ LlamafileArgs parse_llamafile_args(int argc, char** argv) {
if ((strcmp(argv[i], "-m") == 0 || strcmp(argv[i], "--model") == 0) && i + 1 < argc) {
args.model_path = argv[i + 1];
}
+ if ((strcmp(argv[i], "-hf") == 0 || strcmp(argv[i], "-hfr") == 0 ||
+ strcmp(argv[i], "--hf-repo") == 0 || strcmp(argv[i], "-mu") == 0 ||
+ strcmp(argv[i], "--model-url") == 0) && i + 1 < argc) {
+ args.remote_model = argv[i + 1];
+ }
}
// Determine execution mode from flags
diff --git a/llamafile/args.h b/llamafile/args.h
index 86a63e22..584ba4d1 100644
--- a/llamafile/args.h
+++ b/llamafile/args.h
@@ -45,6 +45,11 @@ struct LlamafileArgs {
// Model path captured from -m (for display in combined mode TUI)
std::string model_path;
+ // Remote model reference captured from -hf/--hf-repo/-mu/--model-url.
+ // llama.cpp downloads it over HTTPS at load time, so -m is not required
+ // when one of these is present; also used as the TUI display fallback.
+ std::string remote_model;
+
// Note: Llamafile-specific flags are stored in FLAG_* globals (llamafile.h):
// --verbose -> FLAG_verbose
// --nothink -> FLAG_nothink
diff --git a/llamafile/main.cpp b/llamafile/main.cpp
index c5fb79b5..898ef179 100644
--- a/llamafile/main.cpp
+++ b/llamafile/main.cpp
@@ -240,7 +240,8 @@ static int combined_main(const LlamafileArgs &args) {
// stack is too small for the httplib + SSE + JSON parsing call chain)
auto *ctx = new TuiThreadCtx{
&shutdown_fn, &mu, &cv, &shutdown_ready,
- listen_addr, args.system_prompt, args.model_path
+ listen_addr, args.system_prompt,
+ args.model_path.empty() ? args.remote_model : args.model_path
};
pthread_attr_t attr;
@@ -314,8 +315,10 @@ int main(int argc, char **argv) {
}
}
- // All modes require a model file (but let --server --help pass through).
- if (args.model_path.empty() &&
+ // All modes require a model: either a local file (-m) or a remote
+ // reference (-hf/--model-url) that llama.cpp downloads over HTTPS.
+ // --server --help still passes through.
+ if (args.model_path.empty() && args.remote_model.empty() &&
!llamafile_has(argv, "--help") && !llamafile_has(argv, "-h")) {
fprintf(stderr, "error: missing required -m MODEL.gguf\n\n");
switch (args.mode) {
diff --git a/tests/integration/README.md b/tests/integration/README.md
index 4fc66f09..0f7f9489 100644
--- a/tests/integration/README.md
+++ b/tests/integration/README.md
@@ -31,12 +31,14 @@ Use `-m` to select test categories:
| `cli` | CLI mode tests |
| `tui` | TUI/chat mode tests |
| `server` | Server mode tests |
-| `server` | Combined (TUI/chat + server) mode tests |
+| `combined` | Combined (TUI/chat + server) mode tests |
| `multimodal` | Vision/image tests (requires multimodal model) |
| `tool_calling` | Tool use tests (requires tool-capable model) |
| `thinking` | Thinking model tests (QwQ, DeepSeek-R1, etc.) |
| `gpu` | GPU acceleration tests |
| `cpu` | CPU-only tests |
+| `ssl` | HTTPS/TLS tests: serving with `--ssl-cert-file`, model download over HTTPS, untrusted-cert rejection. Needs `openssl` in PATH to generate a test certificate |
+| `online` | Tests that need network access (currently the HTTPS model download). Skip with `-m "not online"` |
Examples:
@@ -49,6 +51,12 @@ Examples:
# Skip multimodal and tool_calling tests
./run_tests.sh --executable ~/model.llamafile -m "not multimodal and not tool_calling"
+
+# Run only the HTTPS/TLS tests (or skip them with -m "not ssl")
+./run_tests.sh --executable ./o/llamafile/llamafile --model model.gguf -m ssl
+
+# Run the HTTPS/TLS tests without the network-dependent ones
+./run_tests.sh --executable ./o/llamafile/llamafile --model model.gguf -m "ssl and not online"
```
## Options
diff --git a/tests/integration/pyproject.toml b/tests/integration/pyproject.toml
index 3f38f5ea..909ff087 100644
--- a/tests/integration/pyproject.toml
+++ b/tests/integration/pyproject.toml
@@ -26,4 +26,6 @@ markers = [
"tui: tests TUI mode",
"cli: tests CLI mode",
"combined: tests combined (TUI+server) mode",
+ "ssl: tests HTTPS/TLS support (serving and model download)",
+ "online: tests that need network access (deselect with '-m \"not online\"')",
]
diff --git a/tests/integration/tests/test_ssl.py b/tests/integration/tests/test_ssl.py
new file mode 100644
index 00000000..ddc9a5c8
--- /dev/null
+++ b/tests/integration/tests/test_ssl.py
@@ -0,0 +1,237 @@
+"""HTTPS/TLS integration tests.
+
+Covers the TLS support added via cpp-httplib's Mbed TLS backend:
+serving over HTTPS (--ssl-cert-file/--ssl-key-file), downloading models
+over HTTPS (-hf/--model-url), and rejection of untrusted certificates.
+
+Toggle with the ``ssl`` marker: ``-m ssl`` / ``-m "not ssl"``.
+``test_download_model_over_https`` needs network access (huggingface.co)
+and is additionally marked ``online`` (skip with ``-m "not online"``);
+the other tests run fully offline.
+"""
+
+import os
+import platform
+import shutil
+import subprocess
+
+import pytest
+import requests
+
+from utils.llamafile import LlamafileRunner
+
+# Tiny model used for the network download test (~1 MiB)
+HF_TEST_REPO = "ggml-org/models"
+HF_TEST_FILE = "tinyllamas/stories260K.gguf"
+
+OPENSSL_CNF = """\
+[req]
+distinguished_name = dn
+x509_extensions = v3_req
+prompt = no
+[dn]
+CN = localhost
+[v3_req]
+subjectAltName = DNS:localhost, IP:127.0.0.1
+"""
+
+
[email protected](scope="module")
+def ssl_cert(tmp_path_factory):
+ """Generate a self-signed cert/key pair for localhost.
+
+ Returns (cert_path, key_path). Skips if no openssl binary is available.
+ The SAN config file keeps this portable across OpenSSL and LibreSSL
+ (macOS ships LibreSSL, where -addext support varies).
+ """
+ if not shutil.which("openssl"):
+ pytest.skip("openssl binary not available to generate a test certificate")
+
+ tmp = tmp_path_factory.mktemp("ssl")
+ cnf = tmp / "openssl.cnf"
+ cnf.write_text(OPENSSL_CNF)
+ cert, key = tmp / "cert.pem", tmp / "key.pem"
+
+ subprocess.run(
+ [
+ "openssl", "req", "-x509", "-newkey", "rsa:2048", "-sha256",
+ "-days", "2", "-nodes",
+ "-keyout", str(key), "-out", str(cert),
+ "-config", str(cnf),
+ ],
+ check=True,
+ capture_output=True,
+ )
+ return cert, key
+
+
+def wait_for_https_server(port, cert, timeout, poll_interval=1.0):
+ """Poll https://127.0.0.1:port/health until 200, verifying against cert."""
+ import time
+
+ url = f"https://127.0.0.1:{port}/health"
+ start = time.time()
+ while time.time() - start < timeout:
+ try:
+ if requests.get(url, timeout=2, verify=str(cert)).status_code == 200:
+ return True
+ except requests.RequestException:
+ pass
+ time.sleep(poll_interval)
+ return False
+
+
+def base_exe_args(executable):
+ """Mimic LlamafileRunner's sh-prefixed invocation for manual Popen."""
+ if platform.system() != "Windows":
+ return ["sh", os.path.abspath(executable)]
+ return [os.path.abspath(executable)]
+
+
+def fresh_cache_env(cache_dir):
+ """Environment pointing the model download cache at a fresh directory."""
+ env = os.environ.copy()
+ env["XDG_CACHE_HOME"] = str(cache_dir)
+ return env
+
+
+class TestHttpsServing:
+ """Serving over TLS with --ssl-cert-file/--ssl-key-file."""
+
+ def test_server_serves_https(self, llamafile, server_port, timeouts, ssl_cert):
+ """Server comes up over HTTPS and a verifying client can connect."""
+ cert, key = ssl_cert
+ proc = llamafile.start_server(
+ port=server_port,
+ extra_args=["--ssl-cert-file", str(cert), "--ssl-key-file", str(key)],
+ )
+ try:
+ assert wait_for_https_server(
+ server_port, cert, timeout=timeouts.server_ready
+ ), "Server did not become ready over HTTPS"
+
+ # Chain + hostname verification against our cert succeeds
+ r = requests.get(
+ f"https://127.0.0.1:{server_port}/props",
+ timeout=timeouts.http_request,
+ verify=str(cert),
+ )
+ assert r.status_code == 200
+ assert "default_generation_settings" in r.text
+ finally:
+ proc.terminate()
+ proc.wait()
+
+ def test_https_server_rejects_plaintext(
+ self, llamafile, server_port, timeouts, ssl_cert
+ ):
+ """A plain-HTTP request to the TLS port must not get an HTTP 200."""
+ cert, key = ssl_cert
+ proc = llamafile.start_server(
+ port=server_port,
+ extra_args=["--ssl-cert-file", str(cert), "--ssl-key-file", str(key)],
+ )
+ try:
+ assert wait_for_https_server(
+ server_port, cert, timeout=timeouts.server_ready
+ ), "Server did not become ready over HTTPS"
+
+ with pytest.raises(requests.RequestException):
+ requests.get(f"http://127.0.0.1:{server_port}/health", timeout=5)
+ finally:
+ proc.terminate()
+ proc.wait()
+
+
+class TestHttpsDownload:
+ """Model downloads over HTTPS (the client side of TLS support)."""
+
+ @pytest.mark.online
+ def test_download_model_over_https(
+ self, executable, server_port, timeouts, tmp_path
+ ):
+ """Download a tiny model from Hugging Face over HTTPS and serve it.
+
+ Requires network access. Exercises the full client path including
+ the hf.co -> CDN cross-host redirect. A fresh cache directory
+ guarantees the download actually happens.
+ """
+ cache = tmp_path / "cache"
+ cache.mkdir()
+ args = base_exe_args(executable) + [
+ "--server",
+ "--port", str(server_port),
+ "--hf-repo", HF_TEST_REPO,
+ "--hf-file", HF_TEST_FILE,
+ ]
+ proc = subprocess.Popen(
+ args,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ env=fresh_cache_env(cache),
+ )
+ try:
+ assert LlamafileRunner.wait_for_server(
+ server_port, timeout=timeouts.server_ready
+ ), "Server did not become ready (HTTPS download failed?)"
+
+ if platform.system() != "Windows":
+ # The downloaded weights landed in our fresh cache
+ ggufs = [
+ p
+ for p in cache.rglob("*")
+ if p.is_file() and p.stat().st_size > 100_000
+ ]
+ assert ggufs, "No downloaded model found in fresh cache"
+ finally:
+ proc.terminate()
+ proc.wait()
+
+ def test_download_rejects_untrusted_cert(
+ self, llamafile, executable, server_port, timeouts, ssl_cert, tmp_path
+ ):
+ """Downloading from a server with an untrusted (self-signed) cert fails.
+
+ Runs fully offline: our own HTTPS server plays the untrusted host.
+ Its /health endpoint would happily serve a body, so if the client's
+ certificate verification were broken the download would 'succeed'
+ and leave a file in the cache; instead the TLS handshake must fail
+ and the cache must stay empty.
+ """
+ cert, key = ssl_cert
+ rogue_port = server_port + 1
+ server = llamafile.start_server(
+ port=rogue_port,
+ extra_args=["--ssl-cert-file", str(cert), "--ssl-key-file", str(key)],
+ )
+ try:
+ assert wait_for_https_server(
+ rogue_port, cert, timeout=timeouts.server_ready
+ ), "TLS server did not become ready"
+
+ cache = tmp_path / "cache"
+ cache.mkdir()
+ args = base_exe_args(executable) + [
+ "--server",
+ "--port", str(server_port),
+ "--model-url", f"https://127.0.0.1:{rogue_port}/health",
+ ]
+ client = subprocess.run(
+ args,
+ capture_output=True,
+ text=True,
+ env=fresh_cache_env(cache),
+ timeout=timeouts.server_ready,
+ )
+ assert client.returncode != 0, "Download from untrusted cert host succeeded"
+ leftovers = [p for p in cache.rglob("*") if p.is_file()]
+ assert not leftovers, (
+ "Client fetched data from a server with an untrusted certificate: "
+ f"{leftovers}"
+ )
+ finally:
+ server.terminate()
+ server.wait()
diff --git a/third_party/mbedtls/include/mbedtls/ctr_drbg.h b/third_party/mbedtls/include/mbedtls/ctr_drbg.h
new file mode 100644
index 00000000..90226e7e
--- /dev/null
+++ b/third_party/mbedtls/include/mbedtls/ctr_drbg.h
@@ -0,0 +1,4 @@
+// Maps the canonical <mbedtls/ctr_drbg.h> include path onto llamafile's
+// vendored copy, for third-party code (e.g. cpp-httplib's Mbed TLS
+// backend) that expects standard Mbed TLS include paths.
+#include "third_party/mbedtls/ctr_drbg.h"
diff --git a/third_party/mbedtls/include/mbedtls/entropy.h b/third_party/mbedtls/include/mbedtls/entropy.h
new file mode 100644
index 00000000..da605ccb
--- /dev/null
+++ b/third_party/mbedtls/include/mbedtls/entropy.h
@@ -0,0 +1,4 @@
+// Maps the canonical <mbedtls/entropy.h> include path onto llamafile's
+// vendored copy, for third-party code (e.g. cpp-httplib's Mbed TLS
+// backend) that expects standard Mbed TLS include paths.
+#include "third_party/mbedtls/entropy.h"
diff --git a/third_party/mbedtls/include/mbedtls/error.h b/third_party/mbedtls/include/mbedtls/error.h
new file mode 100644
index 00000000..021d3bec
--- /dev/null
+++ b/third_party/mbedtls/include/mbedtls/error.h
@@ -0,0 +1,4 @@
+// Maps the canonical <mbedtls/error.h> include path onto llamafile's
+// vendored copy, for third-party code (e.g. cpp-httplib's Mbed TLS
+// backend) that expects standard Mbed TLS include paths.
+#include "third_party/mbedtls/error.h"
diff --git a/third_party/mbedtls/include/mbedtls/md5.h b/third_party/mbedtls/include/mbedtls/md5.h
new file mode 100644
index 00000000..e464ba88
--- /dev/null
+++ b/third_party/mbedtls/include/mbedtls/md5.h
@@ -0,0 +1,4 @@
+// Maps the canonical <mbedtls/md5.h> include path onto llamafile's
+// vendored copy, for third-party code (e.g. cpp-httplib's Mbed TLS
+// backend) that expects standard Mbed TLS include paths.
+#include "third_party/mbedtls/md5.h"
diff --git a/third_party/mbedtls/include/mbedtls/net_sockets.h b/third_party/mbedtls/include/mbedtls/net_sockets.h
new file mode 100644
index 00000000..a38f4d0d
--- /dev/null
+++ b/third_party/mbedtls/include/mbedtls/net_sockets.h
@@ -0,0 +1,4 @@
+// Maps the canonical <mbedtls/net_sockets.h> include path onto llamafile's
+// vendored copy, for third-party code (e.g. cpp-httplib's Mbed TLS
+// backend) that expects standard Mbed TLS include paths.
+#include "third_party/mbedtls/net_sockets.h"
diff --git a/third_party/mbedtls/include/mbedtls/oid.h b/third_party/mbedtls/include/mbedtls/oid.h
new file mode 100644
index 00000000..9a1f7ae1
--- /dev/null
+++ b/third_party/mbedtls/include/mbedtls/oid.h
@@ -0,0 +1,4 @@
+// Maps the canonical <mbedtls/oid.h> include path onto llamafile's
+// vendored copy, for third-party code (e.g. cpp-httplib's Mbed TLS
+// backend) that expects standard Mbed TLS include paths.
+#include "third_party/mbedtls/oid.h"
diff --git a/third_party/mbedtls/include/mbedtls/pk.h b/third_party/mbedtls/include/mbedtls/pk.h
new file mode 100644
index 00000000..3b03db4d
--- /dev/null
+++ b/third_party/mbedtls/include/mbedtls/pk.h
@@ -0,0 +1,4 @@
+// Maps the canonical <mbedtls/pk.h> include path onto llamafile's
+// vendored copy, for third-party code (e.g. cpp-httplib's Mbed TLS
+// backend) that expects standard Mbed TLS include paths.
+#include "third_party/mbedtls/pk.h"
diff --git a/third_party/mbedtls/include/mbedtls/sha1.h b/third_party/mbedtls/include/mbedtls/sha1.h
new file mode 100644
index 00000000..1c2adf0d
--- /dev/null
+++ b/third_party/mbedtls/include/mbedtls/sha1.h
@@ -0,0 +1,4 @@
+// Maps the canonical <mbedtls/sha1.h> include path onto llamafile's
+// vendored copy, for third-party code (e.g. cpp-httplib's Mbed TLS
+// backend) that expects standard Mbed TLS include paths.
+#include "third_party/mbedtls/sha1.h"
diff --git a/third_party/mbedtls/include/mbedtls/sha256.h b/third_party/mbedtls/include/mbedtls/sha256.h
new file mode 100644
index 00000000..964a79b5
--- /dev/null
+++ b/third_party/mbedtls/include/mbedtls/sha256.h
@@ -0,0 +1,4 @@
+// Maps the canonical <mbedtls/sha256.h> include path onto llamafile's
+// vendored copy, for third-party code (e.g. cpp-httplib's Mbed TLS
+// backend) that expects standard Mbed TLS include paths.
+#include "third_party/mbedtls/sha256.h"
diff --git a/third_party/mbedtls/include/mbedtls/sha512.h b/third_party/mbedtls/include/mbedtls/sha512.h
new file mode 100644
index 00000000..c03a94fd
--- /dev/null
+++ b/third_party/mbedtls/include/mbedtls/sha512.h
@@ -0,0 +1,4 @@
+// Maps the canonical <mbedtls/sha512.h> include path onto llamafile's
+// vendored copy, for third-party code (e.g. cpp-httplib's Mbed TLS
+// backend) that expects standard Mbed TLS include paths.
+#include "third_party/mbedtls/sha512.h"
diff --git a/third_party/mbedtls/include/mbedtls/ssl.h b/third_party/mbedtls/include/mbedtls/ssl.h
new file mode 100644
index 00000000..00fdb07e
--- /dev/null
+++ b/third_party/mbedtls/include/mbedtls/ssl.h
@@ -0,0 +1,4 @@
+// Maps the canonical <mbedtls/ssl.h> include path onto llamafile's
+// vendored copy, for third-party code (e.g. cpp-httplib's Mbed TLS
+// backend) that expects standard Mbed TLS include paths.
+#include "third_party/mbedtls/ssl.h"
diff --git a/third_party/mbedtls/include/mbedtls/x509_crt.h b/third_party/mbedtls/include/mbedtls/x509_crt.h
new file mode 100644
index 00000000..985a55c8
--- /dev/null
+++ b/third_party/mbedtls/include/mbedtls/x509_crt.h
@@ -0,0 +1,4 @@
+// Maps the canonical <mbedtls/x509_crt.h> include path onto llamafile's
+// vendored copy, for third-party code (e.g. cpp-httplib's Mbed TLS
+// backend) that expects standard Mbed TLS include paths.
+#include "third_party/mbedtls/x509_crt.h"