diff --git a/.dockerignore b/.dockerignore index 1df85ca..a69e68f 100644 --- a/.dockerignore +++ b/.dockerignore @@ -9,3 +9,8 @@ !plugins/ !plugins/**/package.json !plugins/**/*.ts +!llm-proxy/ +!llm-proxy/Cargo.toml +!llm-proxy/Cargo.lock +!llm-proxy/src/ +!llm-proxy/src/main.rs diff --git a/.gitignore b/.gitignore index 498ae89..4c7aa33 100644 --- a/.gitignore +++ b/.gitignore @@ -5,5 +5,7 @@ **/*.log **/node_modules **/dist +llm-proxy/target/ **/coverage *.tsbuildinfo +graphify* diff --git a/Dockerfile b/Dockerfile index c18b736..f0acf7c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,18 @@ # hadolint ignore=DL3007 ARG BUN_VERSION="latest" + +# llm-proxy: localhost reverse proxy with classical-only TLS (rustls/ring) +# so Azure never sees a multi-segment PQC ClientHello. +FROM rust:1-trixie AS proxy-builder +WORKDIR /src/llm-proxy +COPY llm-proxy/Cargo.toml llm-proxy/Cargo.lock ./ +COPY llm-proxy/src/ ./src/ +RUN <<'FOE' +set -e +cargo build --release --locked +cp target/release/llm-proxy /llm-proxy +FOE + FROM oven/bun:${BUN_VERSION} SHELL ["/bin/bash", "-o", "pipefail", "-c"] @@ -396,6 +409,23 @@ EOF FOE +COPY --chmod=0555 --from=proxy-builder /llm-proxy /usr/local/bin/llm-proxy + +# MITM CA for llm-proxy, created once per image (not on every start). +# Private key stays in the image, 0600 bun-owned; rotation = rebuild. +RUN mkdir -p /usr/local/share/llm-proxy \ + && openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 \ + -keyout /usr/local/share/llm-proxy/mitm-ca-key.pem \ + -out /usr/local/share/ca-certificates/llm-proxy-mitm.crt \ + -days 3650 -nodes -subj "/CN=llm-proxy MITM CA" \ + -addext "basicConstraints=critical,CA:TRUE" \ + -addext "keyUsage=critical,digitalSignature,cRLSign,keyCertSign" \ + -addext "subjectKeyIdentifier=hash" \ + -addext "authorityKeyIdentifier=keyid:always" \ + && chmod 600 /usr/local/share/llm-proxy/mitm-ca-key.pem \ + && chown bun:bun /usr/local/share/llm-proxy/mitm-ca-key.pem \ + && update-ca-certificates + COPY --chmod=0555 scripts/entrypoint.sh /entrypoint.sh COPY --chmod=0555 scripts/convert-gemini.auth.ts /usr/local/bin/convert-gemini.auth.ts @@ -404,9 +434,23 @@ USER bun:bun RUN mise use -g --silent go@1.26 ripgrep +### +# Image clean up (always keep last just before ENTRYPOINT or ENV settings) +# hadolint ignore=DL3066 +USER root:root + +RUN rm -rf /tmp/* /var/tmp/* \ + && rm -rf "${BUN_HOME}/.cache/go-build" "${BUN_HOME}/.cache/uv" "${BUN_HOME}/.cache/pip" \ + && rm -rf "${BUN_HOME}/.local/share/mise/downloads" "${BUN_HOME}/.cache/mise" \ + && find "${BUN_HOME}" \! -path '*/llm-proxy/*' -name '__pycache__' -type d -prune -exec rm -rf {} + + +# hadolint ignore=DL3066 +USER bun:bun + # Set BASH_ENV so non-interactive bash shells (spawned by OpenCode CLI) source /etc/bash.bashrc # This ensures mise activation and PATH are available in shell commands ENV BASH_ENV=/etc/bash.bashrc ENV SHELL=/bin/bash +ENV LLM_PROXY_LOGFILE=/tmp/llm_proxy.log ENTRYPOINT [ "/entrypoint.sh" ] diff --git a/LLMPROXY.md b/LLMPROXY.md new file mode 100644 index 0000000..e7fdda2 --- /dev/null +++ b/LLMPROXY.md @@ -0,0 +1,39 @@ +# LLM Proxy + +This document describes use of the `llm-proxy` HTTP proxy that ships inside the OpenCode CLI image. + +## Purpose + +OpenCode runs inside a container where all outgoing HTTP(S) traffic goes through a localhost proxy at `http://127.0.0.1:8899`. The proxy starts itself, without user action, on container launch. + +The proxy ensures TLS connections to upstream services — in particular Azure Foundry — are established using classical curves, so the upstream front-end never receives post-quantum client hellos it would reject. It also terminates intercepted TLS connections locally, endpoints that are reached via plain HTTP are forwarded, and everything else is relayed. In short, HTTPS traffic visible to the proxy never inherits the client’s TLS capabilities. + +For the user, this behavior is transparent and no manual proxy configuration is required. + +## Configuration + +All configuration is done with environment variables. Below, in alphabetical order. + +> [!WARNING] +> `HTTP_PROXY` / `HTTPS_PROXY` (and lowercase) are enforced by the entrypoint; any other value is overridden with a warning. +> `NO_PROXY` / `no_proxy` are equally enforced to `localhost,127.0.0.1`. Existing value is overridden with a warning. + +| Variable | Default | Meaning | +| --- | --- | --- | +| `LLM_PROXY_ENABLED` | enabled | `off`, `0`, `false` or `no` disables the proxy entirely: it is not started and no proxy environment is enforced. | +| `LLM_PROXY_LISTEN_ADDR` | `127.0.0.1:8899` | Address the proxy listens on; also the value `HTTP_PROXY` is forced to. | +| `LLM_PROXY_INTERCEPT_SUFFIXES` | everything | Comma-separated domain suffixes (e.g. `cognitiveservices.azure.com`) whose TLS is terminated locally. Empty means all hosts. | +| `LLM_PROXY_MITM` | enabled | `off` disables TLS termination; all `CONNECT` tunnels are then relayed opaquely. | +| `LLM_PROXY_MITM_CA_CERT` / `LLM_PROXY_MITM_CA_KEY` | baked-in image paths | Optional alternate CA certificate/key files for terminated TLS. | +| `LLM_PROXY_UPSTREAM_PROXY` | direct | Optional corporate proxy for the proxy's own upstream connections: an `http://` or `https://` URL, or `direct`/`none`/`off` to force direct connections. Unset means direct (container-wide `HTTP_PROXY` is never followed by the proxy itself). | +| `LLM_PROXY_UPSTREAM_URL` | none | Upstream origin for reverse-proxying (e.g. `https://example.com`). When set, relative (origin-form) requests are forwarded there. When unset, each request must name its target host or it is rejected. | +| `LLM_PROXY_TLS_MIN_VERSION` / `LLM_PROXY_TLS_MAX_VERSION` | none | Bound TLS versions accepted by the proxy. Values `1.2` or `1.3` only; any other value, or minimum above maximum, prevents startup with an error. | +| `LLM_PROXY_LOGFILE` | syslog | Path of the proxy's own log file. Parent directories are created automatically. Unset means syslog (requires something listening on `/dev/log`, otherwise stderr fallback). | +| `LLM_PROXY_LOGLEVEL` | `INFO` | Maximum log verbosity: `ERROR`, `WARN`, `INFO` (default), or `DEBUG`. Any other value prevents startup with an error. Relay ends and byte counts appear only at `DEBUG`. | +| `LLM_PROXY_LLM_LOGFILE` | none | Optional JSONL log of every forwarded LLM request (status, latency, token counts). Unset disables it. | +| `LLM_PROXY_LLM_LOG_BODIES` | off | `1` also stores complete request bodies in the JSONL log. | + +Two operational aspects worth knowing: + +- Every `CONNECT` accepted by the proxy produces exactly one `INFO` line in the proxy log (`CONNECT (MITM|tunnel) `). Relay end details are `DEBUG` only. +- If no log file is configured, the proxy logs via syslog (facility `daemon`, tag `llm-proxy`). With no syslog listener the messages fall back to stderr; the container's entrypoint severs the proxy's stdio so they cannot corrupt the OpenCode TUI. diff --git a/llm-proxy/Cargo.lock b/llm-proxy/Cargo.lock new file mode 100644 index 0000000..896d5fa --- /dev/null +++ b/llm-proxy/Cargo.lock @@ -0,0 +1,2025 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "aws-lc-rs" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "hostname" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd" +dependencies = [ + "cfg-if", + "libc", + "windows-link", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "llm-proxy" +version = "0.1.0" +dependencies = [ + "axum", + "base64 0.22.1", + "bytes", + "hyper", + "hyper-util", + "rcgen", + "reqwest", + "rustls", + "serde", + "serde_json", + "syslog", + "time", + "tokio", + "tokio-rustls", + "tokio-stream", + "webpki-roots 0.26.11", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_threads" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cabcc654086861f9e1bc5115258de62ef92c79b20f4615a1b0cc57c4e82027d4" +dependencies = [ + "libc", +] + +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64 0.23.1", + "serde_core", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "pem", + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "encoding_rs", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "mime", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "aws-lc-rs", + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "syslog" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "019f1500a13379b7d051455df397c75770de6311a7a188a699499502704d9f10" +dependencies = [ + "hostname", + "libc", + "log", + "time", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "libc", + "num-conv", + "num_threads", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.12", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec", + "time", +] + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure 0.14.0", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure 0.14.0", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/llm-proxy/Cargo.toml b/llm-proxy/Cargo.toml new file mode 100644 index 0000000..63361f5 --- /dev/null +++ b/llm-proxy/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "llm-proxy" +version = "0.1.0" +edition = "2024" + +[dependencies] +axum = "0.8" +bytes = "1" +# `rustls-no-provider` avoids pulling aws-lc-rs (which enables X25519MLKEM768). +# The process-default provider is installed explicitly in main.rs (ring only). +reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "stream", "http2", "charset", "system-proxy", "socks"] } +hyper = "1" +hyper-util = { version = "0.1", features = ["tokio"] } +tokio-rustls = "0.26" +webpki-roots = "0.26" +rcgen = { version = "0.14", default-features = false, features = ["ring", "pem", "x509-parser"] } +time = "0.3" +base64 = "0.22" +rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "sync", "io-util", "time"] } +syslog = "7" +tokio-stream = "0.1" + +# Size-first release profile: the proxy is a loopback shim (latency is +# dominated by LLM inference), so byte-per-size tradeoffs favor shrinking. +[profile.release] +opt-level = "z" +lto = true +codegen-units = 1 +panic = "abort" +strip = "symbols" diff --git a/llm-proxy/src/main.rs b/llm-proxy/src/main.rs new file mode 100644 index 0000000..69b2833 --- /dev/null +++ b/llm-proxy/src/main.rs @@ -0,0 +1,1559 @@ +// llm-proxy: localhost reverse/forward/MITM proxy. Plain HTTP is forwarded +// (absolute URI) or reverse-proxied (LLM_PROXY_UPSTREAM_URL) with a classical +// single-packet TLS 1.3 ClientHello upstream; CONNECT tunnels listed +// LLM_PROXY_INTERCEPT_SUFFIXES hosts with full TLS termination so the proxy — not the +// client — controls the upstream ciphers. +// HTTPS clients are served via CONNECT tunnels (opaque TCP relay). +// +// Why: Azure's front-end resets multi-segment ClientHello messages carrying +// the X25519MLKEM768 key share (sent by default by OpenSSL 3.5, Go 1.24+, +// Bun >= 1.4.1/BoringSSL, and rustls + aws-lc-rs). This proxy uses rustls +// with the *ring* provider (which has zero post-quantum groups) and puts +// SECP384R1 first, so the ClientHello stays small and even skips Azure's +// HelloRetryRequest. It optionally logs every LLM call + token usage as JSONL +// when LLM_PROXY_LLM_LOGFILE is set (no log file by default). + +use axum::{ + body::{to_bytes, Body, Bytes}, + extract::State, + http::{HeaderMap, HeaderName, Method, Request, StatusCode, Uri}, + response::{IntoResponse, Response}, + Router, +}; +use base64::Engine as _; +use rcgen::{ + CertificateParams, DnType, ExtendedKeyUsagePurpose, Issuer, KeyPair, SanType, +}; +use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName}; +use rustls::version::{TLS12, TLS13}; +use rustls::{ClientConfig, RootCertStore, ServerConfig, SupportedProtocolVersion}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::HashMap, + env, + fs::{File, OpenOptions}, + io::Write, + net::IpAddr, + path::{Path, PathBuf}, + sync::{Arc, Mutex, OnceLock}, + time::{Duration, Instant, SystemTime, UNIX_EPOCH}, +}; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; +use tokio::sync::mpsc; +use tokio_stream::{wrappers::ReceiverStream, StreamExt}; + +/// Where the proxy's own logs go: LLM_PROXY_LOGFILE file, syslog, or stderr. +enum LogSink { + File(Mutex), + Syslog(Mutex>), + Stderr, +} + +static LOGGER: OnceLock = OnceLock::new(); + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] +enum Level { + Error, + Warn, + Info, + Debug, +} + +fn parse_log_level(raw: &str) -> Result { + match raw.trim().to_ascii_lowercase().as_str() { + "" => Ok(Level::Info), + "error" => Ok(Level::Error), + "warn" | "warning" => Ok(Level::Warn), + "info" => Ok(Level::Info), + "debug" => Ok(Level::Debug), + _ => Err(format!( + "llm-proxy: LLM_PROXY_LOGLEVEL must be one of ERROR, WARN, INFO, DEBUG; got {raw:?}" + )), + } +} + +fn max_level() -> Level { + *MAX_LEVEL.get().unwrap_or(&Level::Info) +} + +static MAX_LEVEL: OnceLock = OnceLock::new(); + +fn level_name(level: Level) -> &'static str { + match level { + Level::Error => "ERROR", + Level::Warn => "WARN", + Level::Info => "INFO", + Level::Debug => "DEBUG", + } +} + +fn log_msg(level: Level, msg: &str) { + if level > max_level() { + return; + } + match LOGGER.get().unwrap_or(&LogSink::Stderr) { + LogSink::File(f) => { + if let Ok(mut f) = f.lock() { + let _ = writeln!(f, "[{}] {msg}", level_name(level)); + } + } + LogSink::Syslog(l) => { + if let Ok(mut l) = l.lock() { + match level { + Level::Error => { + let _ = l.err(msg); + } + Level::Warn => { + let _ = l.warning(msg); + } + Level::Info => { + let _ = l.info(msg); + } + Level::Debug => { + let _ = l.debug(msg); + } + } + } + } + LogSink::Stderr => eprintln!("[{}] {msg}", level_name(level)), + } +} + +macro_rules! log_line { + ($lvl:expr, $($arg:tt)*) => { + $crate::log_msg($lvl, &format!($($arg)*)) + }; +} + +/// Own the proxy's log routing: LLM_PROXY_LOGFILE file if set (creating parent +/// dirs), else syslog, else stderr if syslog is unreachable. +/// LLM_PROXY_LOGLEVEL caps verbosity (ERROR/WARN/INFO/DEBUG, default INFO). +fn init_logging() { + let max = match parse_log_level(&env::var("LLM_PROXY_LOGLEVEL").unwrap_or_default()) { + Ok(v) => v, + Err(e) => { + eprintln!("{e}"); + std::process::exit(1); + } + }; + let _ = MAX_LEVEL.set(max); + if let Some(path) = env::var("LLM_PROXY_LOGFILE").ok().filter(|s| !s.trim().is_empty()) { + if let Some(parent) = Path::new(&path).parent() { + let _ = std::fs::create_dir_all(parent); + } + match OpenOptions::new().create(true).append(true).open(&path) { + Ok(f) => { + let _ = LOGGER.set(LogSink::File(Mutex::new(f))); + return; + } + Err(e) => eprintln!("llm-proxy: cannot open LLM_PROXY_LOGFILE {path}: {e}; trying syslog"), + } + } + let formatter = syslog::Formatter3164 { + facility: syslog::Facility::LOG_DAEMON, + hostname: None, + process: "llm-proxy".to_string(), + pid: std::process::id(), + }; + match syslog::unix(formatter) { + Ok(logger) => { + let _ = LOGGER.set(LogSink::Syslog(Mutex::new(logger))); + } + Err(e) => { + let _ = LOGGER.set(LogSink::Stderr); + eprintln!("llm-proxy: syslog unavailable ({e}); logging to stderr"); + } + } +} + +#[derive(Clone)] +enum TunnelVia { + Direct, + HttpProxy { addr: String, auth: Option }, + Unsupported, +} + +#[derive(Clone)] +struct AppState { + client: reqwest::Client, + upstream: Option, + tunnel_via: TunnelVia, + mitm: Option>, + log_file: Option>>, + log_bodies: bool, +} + +#[derive(Deserialize, Default)] +struct ReqMeta { + #[serde(default)] + model: String, + #[serde(default)] + stream: bool, +} + +#[derive(Deserialize, Default)] +struct UsageDetails { + #[serde(default)] + cached_tokens: u64, +} + +#[derive(Deserialize, Default)] +struct UsageStats { + #[serde(default)] + prompt_tokens: u64, + #[serde(default)] + completion_tokens: u64, + #[serde(default)] + input_tokens: u64, + #[serde(default)] + output_tokens: u64, + #[serde(default)] + total_tokens: u64, + prompt_tokens_details: Option, + input_tokens_details: Option, +} + +#[derive(Deserialize)] +struct ResponseInner { + #[serde(default)] + model: String, + usage: Option, +} + +#[derive(Deserialize)] +struct UsageEnvelope { + #[serde(default)] + model: String, + usage: Option, + response: Option, +} + +#[derive(Serialize)] +struct CallRecord { + ts_ms: u128, + method: String, + path: String, + #[serde(skip_serializing_if = "String::is_empty")] + model: String, + stream: bool, + status: u16, + ttfb_ms: u64, + duration_ms: u64, + input_tokens: u64, + output_tokens: u64, + cached_tokens: u64, + total_tokens: u64, + req_bytes: usize, + resp_bytes: usize, + #[serde(skip_serializing_if = "Option::is_none")] + request_body: Option, +} + +fn is_hop_header(name: &HeaderName) -> bool { + matches!( + name.as_str(), + "host" + | "connection" + | "keep-alive" + | "proxy-connection" + | "te" + | "trailer" + | "transfer-encoding" + | "upgrade" + ) +} + +fn apply_usage(rec: &mut CallRecord, model: &str, usage: Option<&UsageStats>) { + if !model.is_empty() && rec.model.is_empty() { + rec.model = model.to_string(); + } + if let Some(u) = usage { + if u.input_tokens > 0 { + rec.input_tokens = u.input_tokens; + } else if u.prompt_tokens > 0 { + rec.input_tokens = u.prompt_tokens; + } + if u.output_tokens > 0 { + rec.output_tokens = u.output_tokens; + } else if u.completion_tokens > 0 { + rec.output_tokens = u.completion_tokens; + } + if u.total_tokens > 0 { + rec.total_tokens = u.total_tokens; + } + if let Some(d) = &u.input_tokens_details { + if d.cached_tokens > 0 { + rec.cached_tokens = d.cached_tokens; + } + } else if let Some(d) = &u.prompt_tokens_details { + if d.cached_tokens > 0 { + rec.cached_tokens = d.cached_tokens; + } + } + } +} + +fn extract_usage(raw: &[u8], is_sse: bool, rec: &mut CallRecord) { + let parse_json = |slice: &[u8], rec: &mut CallRecord| { + if !slice.windows(7).any(|w| w == br#""usage""#.as_slice()) { + return; + } + if let Ok(env) = serde_json::from_slice::(slice) { + apply_usage(rec, &env.model, env.usage.as_ref()); + if let Some(resp) = &env.response { + apply_usage(rec, &resp.model, resp.usage.as_ref()); + } + } + }; + + if !is_sse { + parse_json(raw, rec); + return; + } + + let text = String::from_utf8_lossy(raw); + for line in text.lines() { + let line = line.trim(); + if let Some(payload) = line.strip_prefix("data:") { + let payload = payload.trim(); + if !payload.is_empty() && payload != "[DONE]" { + parse_json(payload.as_bytes(), rec); + } + } + } +} + +fn write_log(file: Option<&Mutex>, rec: &CallRecord) { + let Some(file) = file else { return }; + if let Ok(mut line) = serde_json::to_vec(rec) { + line.push(b'\n'); + if let Ok(mut f) = file.lock() { + let _ = f.write_all(&line); + } + } +} + +fn redact_proxy_url(raw: &str) -> String { + match reqwest::Url::parse(raw) { + Ok(mut u) => { + if u.password().is_some() { + let _ = u.set_password(Some("xxxxx")); + } + u.to_string() + } + Err(_) => raw.to_string(), + } +} + +fn resolve_target(upstream: Option<&str>, uri: &Uri) -> Option { + let pq = uri.path_and_query().map(|x| x.as_str()).unwrap_or("/"); + // Forward-proxy style (absolute URI) reaches any host directly; + // origin-form requests fall back to the configured upstream. + // Either way the proxy originates upstream TLS with classical curves. + match (uri.scheme_str(), uri.authority()) { + (Some(scheme), Some(authority)) if scheme == "http" || scheme == "https" => { + Some(format!("{scheme}://{authority}{pq}")) + } + _ => upstream.map(|base| format!("{base}{pq}")), + } +} + +/// Baked-in image paths (created once per image build, see Dockerfile). +/// Override with LLM_PROXY_MITM_CA_CERT / LLM_PROXY_MITM_CA_KEY to mount a pre-provisioned CA. +const DEFAULT_LLM_PROXY_MITM_CA_CERT: &str = "/usr/local/share/ca-certificates/llm-proxy-mitm.crt"; +const DEFAULT_LLM_PROXY_MITM_CA_KEY: &str = "/usr/local/share/llm-proxy/mitm-ca-key.pem"; + +fn ca_paths() -> (PathBuf, PathBuf) { + let cert = env::var("LLM_PROXY_MITM_CA_CERT") + .ok() + .filter(|s| !s.trim().is_empty()) + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(DEFAULT_LLM_PROXY_MITM_CA_CERT)); + let key = env::var("LLM_PROXY_MITM_CA_KEY") + .ok() + .filter(|s| !s.trim().is_empty()) + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(DEFAULT_LLM_PROXY_MITM_CA_KEY)); + (cert, key) +} + +struct CaAuthority { + issuer: Arc>, +} + +/// Load a separately-provisioned CA (see entrypoint: `openssl req -x509`). +/// The PEM is intentionally leaked: the issuer borrows it for the proxy's +/// whole lifetime, so a one-time leak is the simplest sound ownership. +fn load_ca_authority(cert_path: &Path, key_path: &Path) -> Result { + let key_pem = std::fs::read_to_string(key_path).map_err(|e| { + format!( + "MITM CA key not found at {}: {e} (baked into the image; override with LLM_PROXY_MITM_CA_KEY)", + key_path.display() + ) + })?; + let cert_pem = std::fs::read_to_string(cert_path).map_err(|e| { + format!( + "MITM CA cert not found at {}: {e} (baked into the image; override with LLM_PROXY_MITM_CA_CERT)", + cert_path.display() + ) + })?; + let key = KeyPair::from_pem(&key_pem).map_err(|e| e.to_string())?; + let leaked: &'static str = Box::leak(cert_pem.into_boxed_str()); + let issuer = Issuer::from_ca_cert_pem(leaked, key).map_err(|e| e.to_string())?; + Ok(CaAuthority { + issuer: Arc::new(issuer), + }) +} + +fn issue_leaf(issuer: &Issuer<'static, KeyPair>, host: &str) -> Result<(Vec, Vec), String> { + let mut params = if let Ok(ip) = host.parse::() { + let mut p = CertificateParams::new(Vec::::new()).map_err(|e| e.to_string())?; + p.subject_alt_names = vec![SanType::IpAddress(ip)]; + p.distinguished_name.push(DnType::CommonName, host); + p + } else { + CertificateParams::new(vec![host.to_string()]).map_err(|e| e.to_string())? + }; + params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth]; + params.not_before = + time::OffsetDateTime::now_utc() - time::Duration::days(1); + params.not_after = + time::OffsetDateTime::now_utc() + time::Duration::days(365); + let key = KeyPair::generate().map_err(|e| e.to_string())?; + let cert = params.signed_by(&key, issuer).map_err(|e| e.to_string())?; + Ok((cert.der().to_vec(), key.serialize_der())) +} + +fn parse_suffixes(raw: &str) -> Vec { + raw.split(',') + .map(|s| s.trim().trim_start_matches('.').to_lowercase()) + .filter(|s| !s.is_empty()) + .collect() +} + +fn intercept_host(host: &str, suffixes: &[String]) -> bool { + let host = host.trim().trim_end_matches('.').to_lowercase(); + if host.is_empty() { + return false; + } + // No configured suffixes: intercept everything. + if suffixes.is_empty() { + return true; + } + suffixes.iter().any(|s| s == "*" || host == *s || host.ends_with(&format!(".{s}"))) +} + +/// Host part of a CONNECT authority (`example.com:443` -> `example.com`). +fn authority_host(authority: &str) -> &str { + if let Some(rest) = authority.strip_prefix('[') { + return rest.split("]:").next().unwrap_or(rest.trim_end_matches(']')); + } + match authority.rsplit_once(':') { + Some((host, port)) if !port.is_empty() && port.chars().all(|c| c.is_ascii_digit()) => host, + _ => authority, + } +} + +fn config_for_host(mitm: &MitmState, host: &str) -> Result, String> { + if let Some(cfg) = mitm.cache.lock().map_err(|e| e.to_string())?.get(host) { + return Ok(cfg.clone()); + } + let (cert_der, key_der) = issue_leaf(&mitm.issuer, host)?; + let cfg = ServerConfig::builder_with_protocol_versions(&mitm.versions) + .with_no_client_auth() + .with_single_cert( + vec![CertificateDer::from(cert_der)], + PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key_der)), + ) + .map_err(|e| e.to_string())?; + let cfg = Arc::new(cfg); + mitm.cache + .lock() + .map_err(|e| e.to_string())? + .insert(host.to_string(), cfg.clone()); + Ok(cfg) +} + +struct MitmState { + issuer: Arc>, + suffixes: Vec, + versions: Vec<&'static SupportedProtocolVersion>, + cache: Mutex>>, +} + +fn init_mitm(versions: Vec<&'static SupportedProtocolVersion>) -> Option> { + if env::var("LLM_PROXY_MITM").is_ok_and(|v| v.eq_ignore_ascii_case("off")) { + return None; + } + // No LLM_PROXY_INTERCEPT_SUFFIXES: intercept everything. + let suffixes = match env::var("LLM_PROXY_INTERCEPT_SUFFIXES") { + Ok(raw) => parse_suffixes(&raw), + Err(_) => Vec::new(), + }; + let (cert_path, key_path) = ca_paths(); + match load_ca_authority(&cert_path, &key_path) { + Ok(ca) => { + log_line!( + Level::Info, + "llm-proxy: MITM enabled for [{}] (CA: {})", + suffixes.join(", "), + cert_path.display() + ); + Some(Arc::new(MitmState { + issuer: ca.issuer, + suffixes, + versions, + cache: Mutex::new(HashMap::new()), + })) + } + Err(e) => { + log_line!(Level::Warn, "llm-proxy: MITM disabled, {e}"); + None + } + } +} + +fn parse_tls_version(raw: &str, var: &str) -> Result, String> { + let v = raw.trim(); + if v.is_empty() { + return Ok(None); + } + match v { + "1.2" => Ok(Some(2)), + "1.3" => Ok(Some(3)), + _ => Err(format!( + "llm-proxy: {var} must be \"1.2\" or \"1.3\", got {raw:?}" + )), + } +} + +/// Effective TLS versions from LLM_PROXY_MIN/MAX_TLS_VERSION. +/// Unset bounds mean "no restriction"; min > max is a startup error. +fn tls_versions(min: Option, max: Option) -> Result, String> { + if let (Some(lo), Some(hi)) = (min, max) { + if lo > hi { + return Err(format!( + "llm-proxy: LLM_PROXY_TLS_MIN_VERSION (1.{lo}) is higher than LLM_PROXY_TLS_MAX_VERSION (1.{hi})" + )); + } + } + let mut out = Vec::with_capacity(2); + if max.unwrap_or(3) >= 3 && min.unwrap_or(2) <= 3 { + out.push(&TLS13); + } + if max.unwrap_or(3) >= 2 && min.unwrap_or(2) <= 2 { + out.push(&TLS12); + } + Ok(out) +} + +fn tls_bounds_or_exit() -> ( + Option, + Option, + Vec<&'static SupportedProtocolVersion>, +) { + let min = match parse_tls_version( + &env::var("LLM_PROXY_TLS_MIN_VERSION").unwrap_or_default(), + "LLM_PROXY_TLS_MIN_VERSION", + ) { + Ok(v) => v, + Err(e) => { + log_line!(Level::Error, "{e}"); + std::process::exit(1); + } + }; + let max = match parse_tls_version( + &env::var("LLM_PROXY_TLS_MAX_VERSION").unwrap_or_default(), + "LLM_PROXY_TLS_MAX_VERSION", + ) { + Ok(v) => v, + Err(e) => { + log_line!(Level::Error, "{e}"); + std::process::exit(1); + } + }; + match tls_versions(min, max) { + Ok(versions) => (min, max, versions), + Err(e) => { + log_line!(Level::Error, "{e}"); + std::process::exit(1); + } + } +} + +fn reqwest_tls_version(v: u8) -> reqwest::tls::Version { + if v >= 3 { + reqwest::tls::Version::TLS_1_3 + } else { + reqwest::tls::Version::TLS_1_2 + } +} + +fn parse_tunnel_via(raw: &str) -> TunnelVia { + let v = raw.trim(); + if v.is_empty() + || v.eq_ignore_ascii_case("none") + || v.eq_ignore_ascii_case("direct") + || v.eq_ignore_ascii_case("off") + { + return TunnelVia::Direct; + } + let normalized = if v.contains("://") { + v.to_string() + } else { + format!("http://{v}") + }; + match reqwest::Url::parse(&normalized) { + Ok(u) if u.scheme() == "http" || u.scheme() == "https" => { + let host = u.host_str().unwrap_or("").to_string(); + let port = u + .port_or_known_default() + .unwrap_or(if u.scheme() == "https" { 443 } else { 80 }); + let auth = match (u.username(), u.password()) { + ("", _) => None, + (user, pass) => Some(base64::engine::general_purpose::STANDARD.encode(format!( + "{}:{}", + user, + pass.unwrap_or("") + ))), + }; + TunnelVia::HttpProxy { + addr: format!("{host}:{port}"), + auth, + } + } + _ => TunnelVia::Unsupported, + } +} + +async fn open_upstream(authority: &str, via: &TunnelVia) -> Result { + let connect = async { + match via { + TunnelVia::Direct => TcpStream::connect(authority) + .await + .map_err(|e| e.to_string()), + TunnelVia::HttpProxy { addr, auth } => { + let stream = TcpStream::connect(addr).await.map_err(|e| e.to_string())?; + let mut req = format!("CONNECT {authority} HTTP/1.1\r\nHost: {authority}\r\n"); + if let Some(a) = auth { + req.push_str(&format!("Proxy-Authorization: Basic {a}\r\n")); + } + req.push_str("\r\n"); + let mut reader = tokio::io::BufReader::new(stream); + reader + .get_mut() + .write_all(req.as_bytes()) + .await + .map_err(|e| e.to_string())?; + let mut head = Vec::new(); + loop { + let mut line = Vec::new(); + let n = reader.read_until(b'\n', &mut line).await.map_err(|e| e.to_string())?; + if n == 0 { + return Err("corporate proxy closed the connection".to_string()); + } + head.extend_from_slice(&line); + if head.len() > 32768 { + return Err("corporate proxy header too large".to_string()); + } + if head.ends_with(b"\r\n\r\n") { + break; + } + } + let ok = String::from_utf8_lossy(&head) + .lines() + .next() + .is_some_and(|l| l.contains(" 200")); + if !ok { + return Err(format!( + "corporate proxy refused: {}", + String::from_utf8_lossy(&head).lines().next().unwrap_or("") + )); + } + Ok(reader.into_inner()) + } + TunnelVia::Unsupported => { + Err("SOCKS upstream chaining is not supported for CONNECT tunnels".to_string()) + } + } + }; + tokio::time::timeout(Duration::from_secs(15), connect) + .await + .map_err(|_| "upstream connect timed out".to_string())? +} + +/// Explicit port of a CONNECT authority, if any. +fn connect_port(authority: &str) -> Option { if let Some(rest) = authority.strip_prefix('[') { + return rest.rsplit_once("]:").and_then(|(_, p)| p.parse().ok()); + } + match authority.rsplit_once(':') { + Some((_, p)) if !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()) => p.parse().ok(), + _ => None, + } +} + +/// Bounded `tls.handshake.failed.` key for a peer rustls error +/// (taxonomy stolen from sozu-proxy, ideas only). Unknown variants collapse +/// to `.other` so grep/metric cardinality stays predictable. +fn handshake_failure_reason(err: &rustls::Error) -> &'static str { + match err { + rustls::Error::AlertReceived(_) => "tls.handshake.failed.alert_received", + rustls::Error::PeerIncompatible(_) => "tls.handshake.failed.peer_incompatible", + rustls::Error::PeerMisbehaved(_) => "tls.handshake.failed.peer_misbehaved", + rustls::Error::InvalidMessage(_) => "tls.handshake.failed.invalid_message", + rustls::Error::InappropriateMessage { .. } => "tls.handshake.failed.inappropriate_message", + rustls::Error::InappropriateHandshakeMessage { .. } => { + "tls.handshake.failed.inappropriate_handshake_message" + } + rustls::Error::PeerSentOversizedRecord => "tls.handshake.failed.oversized_record", + rustls::Error::NoApplicationProtocol => "tls.handshake.failed.no_alpn", + rustls::Error::InvalidCertificate(_) => "tls.handshake.failed.invalid_certificate", + rustls::Error::DecryptError => "tls.handshake.failed.decrypt_error", + rustls::Error::NoCertificatesPresented => "tls.handshake.failed.no_certificates_present", + _ => "tls.handshake.failed.other", + } +} + +/// Tier for a TLS handshake failure (sozu taxonomy, SMITH-free): +/// - `alert_received`: peer rejected our cert/config — routine, `Debug`. +/// - protocol violations incl. ALPN mismatch: buggy/stale peers — `Warn`. +/// - everything else (local/config): genuine — `Error`. +/// - peer disconnect mid-handshake (reset/abort/pipe/eof): routine — `Debug`. +fn handshake_error_tier(err: &std::io::Error) -> (Level, &'static str) { + if let Some(rustls_err) = err.get_ref().and_then(|s| s.downcast_ref::()) { + return match rustls_err { + rustls::Error::AlertReceived(_) => (Level::Debug, handshake_failure_reason(rustls_err)), + rustls::Error::PeerIncompatible(_) + | rustls::Error::PeerMisbehaved(_) + | rustls::Error::InvalidMessage(_) + | rustls::Error::InappropriateMessage { .. } + | rustls::Error::InappropriateHandshakeMessage { .. } + | rustls::Error::PeerSentOversizedRecord + | rustls::Error::NoApplicationProtocol + | rustls::Error::InvalidCertificate(_) + | rustls::Error::DecryptError + | rustls::Error::NoCertificatesPresented => (Level::Warn, handshake_failure_reason(rustls_err)), + _ => (Level::Error, handshake_failure_reason(rustls_err)), + }; + } + use std::io::ErrorKind; + if matches!( + err.kind(), + ErrorKind::ConnectionReset + | ErrorKind::ConnectionAborted + | ErrorKind::BrokenPipe + | ErrorKind::UnexpectedEof + ) { + return (Level::Debug, "tls.handshake.failed.peer_closed"); + } + (Level::Error, "tls.handshake.failed.other") +} + +fn log_handshake_error(stage: &str, host: &str, err: &std::io::Error) -> &'static str { + let (level, reason) = handshake_error_tier(err); + log_line!( + level, + "llm-proxy: {stage} for {host} failed ({reason}): {err}" + ); + reason +} + +async fn mitm_handshake( + client_io: IO, + upstream_tcp: TcpStream, + server_cfg: Arc, + mut cc: ClientConfig, + server_name: ServerName<'static>, + host: &str, +) -> Result< + ( + tokio_rustls::server::TlsStream, + tokio_rustls::client::TlsStream, + ), + String, +> +where + IO: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, +{ + let hello = match tokio_rustls::LazyConfigAcceptor::new( + rustls::server::Acceptor::default(), + client_io, + ) + .await + { + Ok(hello) => hello, + Err(e) => { + let reason = log_handshake_error("client TLS ClientHello", host, &e); + return Err(format!("client TLS ClientHello failed ({reason}): {e}")); + } + }; + cc.alpn_protocols = hello + .client_hello() + .alpn() + .map(|protocols| protocols.map(|p| p.to_vec()).collect()) + .unwrap_or_default(); + let upstream_tls = match tokio_rustls::TlsConnector::from(Arc::new(cc)) + .connect(server_name, upstream_tcp) + .await + { + Ok(tls) => tls, + Err(e) => { + let reason = log_handshake_error("upstream TLS handshake", host, &e); + return Err(format!("upstream TLS handshake failed ({reason}): {e}")); + } + }; + // Byte relaying requires both TLS peers to select the same application protocol. + let mut cfg = (*server_cfg).clone(); + cfg.alpn_protocols = upstream_tls + .get_ref() + .1 + .alpn_protocol() + .map(|p| vec![p.to_vec()]) + .unwrap_or_default(); + let client_tls = match hello.into_stream(Arc::new(cfg)).await { + Ok(tls) => tls, + Err(e) => { + let reason = log_handshake_error("client TLS handshake", host, &e); + return Err(format!("client TLS handshake failed ({reason}): {e}")); + } + }; + if client_tls.get_ref().1.alpn_protocol() != upstream_tls.get_ref().1.alpn_protocol() { + log_line!( + Level::Warn, + "llm-proxy: MITM setup for {host} failed (tls.handshake.failed.no_alpn): client and upstream ALPN protocols differ" + ); + return Err("client and upstream ALPN protocols differ".to_string()); + } + Ok((client_tls, upstream_tls)) +} + +async fn mitm_relay( + host: String, + upstream_addr: String, + on_upgrade: hyper::upgrade::OnUpgrade, + state: &AppState, +) -> Response { + let mitm = match state.mitm.as_ref() { + Some(m) => m.clone(), + None => { + return (StatusCode::BAD_GATEWAY, "llm-proxy: MITM is disabled") + .into_response() + } + }; + let server_cfg = match config_for_host(&mitm, &host) { + Ok(c) => c, + Err(e) => { + return ( + StatusCode::BAD_GATEWAY, + format!("llm-proxy: cannot issue certificate for {host}: {e}"), + ) + .into_response() + } + }; + // Fail fast: dial upstream TCP before answering 200 to the client. + let upstream_tcp = match open_upstream(&upstream_addr, &state.tunnel_via).await { + Ok(s) => s, + Err(e) => { + return ( + StatusCode::BAD_GATEWAY, + format!("llm-proxy: CONNECT {upstream_addr} failed: {e}"), + ) + .into_response() + } + }; + tokio::spawn(async move { + let setup = async { + let mut roots = RootCertStore::empty(); + roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); + let cc = ClientConfig::builder_with_protocol_versions(&mitm.versions) + .with_root_certificates(roots) + .with_no_client_auth(); + let server_name: ServerName<'static> = match ServerName::try_from(host.clone()) { + Ok(n) => n, + Err(_) => match host.parse::() { + Ok(ip) => ServerName::IpAddress(ip.into()), + Err(_) => return Err(format!("invalid upstream name: {host}")), + }, + }; + let client_io = hyper_util::rt::TokioIo::new( + on_upgrade.await.map_err(|e| format!("client upgrade failed: {e}"))?, + ); + mitm_handshake(client_io, upstream_tcp, server_cfg, cc, server_name, &host).await + }; + match tokio::time::timeout(Duration::from_secs(20), setup).await { + Ok(Ok((mut a, mut b))) => { + // Relay end, routine or not, is DEBUG-only in the global log. + match tokio::io::copy_bidirectional(&mut a, &mut b).await { + Ok((up, down)) => log_line!( + Level::Debug, + "llm-proxy: MITM relay for {host} ended: {up} bytes up, {down} bytes down" + ), + Err(e) => log_line!(Level::Debug, "llm-proxy: MITM relay for {host} ended: {e}"), + } + } + // Handshake failures were already logged inside `mitm_handshake` + // with their tier + bounded reason; don't double-log. + Ok(Err(_)) => {} + Err(_) => log_line!(Level::Warn, "llm-proxy: MITM setup for {host} timed out"), + } + }); + Response::builder() + .status(StatusCode::OK) + .body(Body::empty()) + .unwrap_or_else(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()) +} + +async fn connect_tunnel(req: Request, state: AppState) -> Response { + let authority = match req.uri().authority().map(|a| a.to_string()) { + Some(a) => a, + None => return (StatusCode::BAD_REQUEST, "CONNECT requires an authority").into_response(), + }; + let on_upgrade = hyper::upgrade::on(req); + let host = authority_host(&authority).to_lowercase(); + // MITM: terminate TLS here so the proxy — not the client — controls the + // upstream ClientHello (classical curves only). Only for TLS ports and + // configured suffixes; everything else stays a transparent tunnel. + if let Some(mitm) = state.mitm.clone() { + let tls_port = connect_port(&authority).is_none_or(|p| p == 443); + if tls_port && intercept_host(&host, &mitm.suffixes) { + let upstream_addr = if authority.contains(':') { + authority.clone() + } else { + format!("{authority}:443") + }; + log_line!(Level::Info, "llm-proxy: CONNECT {authority} (MITM {host})"); + return mitm_relay(host, upstream_addr, on_upgrade, &state).await; + } + } + let via = state.tunnel_via.clone(); + let upstream = match open_upstream(&authority, &via).await { + Ok(s) => s, + Err(e) => { + log_line!(Level::Warn, "llm-proxy: CONNECT {authority} failed: {e}"); + return ( + StatusCode::BAD_GATEWAY, + format!("CONNECT {authority} failed: {e}"), + ) + .into_response() + } + }; + log_line!(Level::Info, "llm-proxy: CONNECT {authority} (tunnel {host})"); + tokio::spawn(async move { + match on_upgrade.await { + Ok(upgraded) => { + let mut client = hyper_util::rt::TokioIo::new(upgraded); + let mut server = upstream; + // Relay end, routine or not, is DEBUG-only in the global log. + match tokio::io::copy_bidirectional(&mut client, &mut server).await { + Ok((up, down)) => log_line!( + Level::Debug, + "llm-proxy: CONNECT relay for {host} ended: {up} bytes up, {down} bytes down" + ), + Err(e) => log_line!(Level::Debug, "llm-proxy: CONNECT relay for {host} ended: {e}"), + } + } + Err(e) => log_line!( + Level::Warn, + "llm-proxy: CONNECT {authority} upgrade failed: {e}" + ), + } + }); + Response::builder() + .status(StatusCode::OK) + .body(Body::empty()) + .unwrap_or_else(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()) +} + +async fn proxy_handler( + State(state): State, + method: Method, + uri: Uri, + headers: HeaderMap, + req: Request, +) -> Response { + // HTTPS clients reach a forward proxy via CONNECT (opaque tunnel). + // PQC-sensitive hosts (Azure) must use the plain-HTTP paths above so the + // proxy originates TLS with classical curves instead. + if method == Method::CONNECT { + return connect_tunnel(req, state).await; + } + + let start = Instant::now(); + let ts_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis()) + .unwrap_or(0); + + let req_bytes = match to_bytes(req.into_body(), 32 * 1024 * 1024).await { + Ok(b) => b, + Err(e) => return (StatusCode::BAD_REQUEST, e.to_string()).into_response(), + }; + + let meta: ReqMeta = serde_json::from_slice(&req_bytes).unwrap_or_default(); + let mut rec = CallRecord { + ts_ms, + method: method.to_string(), + path: uri.path().to_string(), + model: meta.model, + stream: meta.stream, + status: 0, + ttfb_ms: 0, + duration_ms: 0, + input_tokens: 0, + output_tokens: 0, + cached_tokens: 0, + total_tokens: 0, + req_bytes: req_bytes.len(), + resp_bytes: 0, + request_body: if state.log_bodies && !req_bytes.is_empty() { + Some(String::from_utf8_lossy(&req_bytes).into_owned()) + } else { + None + }, + }; + + let mut fwd_headers = HeaderMap::new(); + for (k, v) in &headers { + // Strip hop-by-hop + accept-encoding so Azure returns plain JSON/SSE for token parsing + if !is_hop_header(k) && k.as_str() != "accept-encoding" { + fwd_headers.append(k.clone(), v.clone()); + } + } + + let target = match resolve_target(state.upstream.as_deref(), &uri) { + Some(t) => t, + None => { + return ( + StatusCode::BAD_REQUEST, + "llm-proxy: origin-form request without LLM_PROXY_UPSTREAM_URL; send an absolute URI or set LLM_PROXY_UPSTREAM_URL", + ) + .into_response(); + } + }; + + let upstream_resp = match state + .client + .request(method, target.as_str()) + .headers(fwd_headers) + .body(req_bytes) + .send() + .await + { + Ok(r) => r, + Err(e) => { + rec.status = StatusCode::BAD_GATEWAY.as_u16(); + rec.duration_ms = start.elapsed().as_millis() as u64; + write_log(state.log_file.as_deref(), &rec); + return (StatusCode::BAD_GATEWAY, e.to_string()).into_response(); + } + }; + + rec.status = upstream_resp.status().as_u16(); + rec.ttfb_ms = start.elapsed().as_millis() as u64; + + let is_sse = upstream_resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .is_some_and(|ct| ct.contains("text/event-stream")); + + let mut resp_builder = Response::builder().status(upstream_resp.status()); + if let Some(h) = resp_builder.headers_mut() { + for (k, v) in upstream_resp.headers() { + if !is_hop_header(k) { + h.append(k.clone(), v.clone()); + } + } + } + + let (tx, rx) = mpsc::channel::>(32); + let log_file = state.log_file.clone(); + + tokio::spawn(async move { + let mut stream = upstream_resp.bytes_stream(); + let mut captured = Vec::new(); + while let Some(chunk) = stream.next().await { + if let Ok(ref b) = chunk { + captured.extend_from_slice(b); + } + if tx.send(chunk).await.is_err() { + break; + } + } + rec.duration_ms = start.elapsed().as_millis() as u64; + rec.resp_bytes = captured.len(); + extract_usage(&captured, is_sse, &mut rec); + write_log(log_file.as_deref(), &rec); + }); + + resp_builder + .body(Body::from_stream(ReceiverStream::new(rx))) + .unwrap_or_else(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()) +} + +#[tokio::main] +async fn main() { + init_logging(); + // Use rustls + ring (no X25519MLKEM768) and put P-384 first to skip Azure's HRR + let mut provider = rustls::crypto::ring::default_provider(); + provider.kx_groups = vec![ + rustls::crypto::ring::kx_group::SECP384R1, + rustls::crypto::ring::kx_group::X25519, + rustls::crypto::ring::kx_group::SECP256R1, + ]; + provider + .install_default() + .expect("install rustls ring provider"); + + // No LLM_PROXY_UPSTREAM_URL: connect directly to whatever host each request names + // (absolute-form URIs). Origin-form requests then need LLM_PROXY_UPSTREAM_URL. + let upstream: Option = env::var("LLM_PROXY_UPSTREAM_URL") + .ok() + .filter(|s| !s.trim().is_empty()) + .map(|s| s.trim_end_matches('/').to_string()); + let listen_addr = env::var("LLM_PROXY_LISTEN_ADDR") + .ok() + .filter(|s| !s.trim().is_empty()) + .unwrap_or_else(|| "127.0.0.1:8899".into()); + let log_path = env::var("LLM_PROXY_LLM_LOGFILE") + .ok() + .filter(|s| !s.trim().is_empty()); + + let log_file = match &log_path { + Some(path) => { + if let Some(parent) = Path::new(path).parent() { + if let Err(e) = std::fs::create_dir_all(parent) { + log_line!(Level::Warn, "llm-proxy: cannot create LLM_PROXY_LLM_LOGFILE dir {}: {e}", parent.display()); + } + } + Some(Arc::new(Mutex::new( + OpenOptions::new() + .create(true) + .append(true) + .open(path) + .expect("open LLM_PROXY_LLM_LOGFILE"), + ))) + } + None => None, + }; + let log_bodies = env::var("LLM_PROXY_LLM_LOG_BODIES").is_ok_and(|v| v == "1"); + + let (tls_min, tls_max, tls_versions) = tls_bounds_or_exit(); + + let mut client_builder = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none()); + if let Some(v) = tls_min { + client_builder = client_builder.min_tls_version(reqwest_tls_version(v)); + } + if let Some(v) = tls_max { + client_builder = client_builder.max_tls_version(reqwest_tls_version(v)); + } + + let upstream_proxy = env::var("LLM_PROXY_UPSTREAM_PROXY").unwrap_or_default(); + // Note: an unset LLM_PROXY_UPSTREAM_PROXY means direct, NOT env fallback. The + // container-wide HTTP(S)_PROXY points at this proxy itself, so falling + // back to env proxies here would relay upstream traffic into ourselves. + let proxy_desc = match upstream_proxy.trim().to_ascii_lowercase().as_str() { + "" => { + client_builder = client_builder.no_proxy(); + "direct".to_string() + } + "none" | "direct" | "off" => { + client_builder = client_builder.no_proxy(); + "direct (disabled)".to_string() + } + _ => { + let trimmed = upstream_proxy.trim(); + let normalized = if trimmed.contains("://") { + trimmed.to_string() + } else { + format!("http://{trimmed}") + }; + let proxy = reqwest::Proxy::all(normalized.as_str()).expect("invalid LLM_PROXY_UPSTREAM_PROXY"); + client_builder = client_builder.proxy(proxy); + redact_proxy_url(&normalized) + } + }; + + let client = client_builder.build().expect("build reqwest client"); + + let tls_desc = match (tls_min, tls_max) { + (None, None) => "1.3+1.2", + (Some(2), Some(2)) | (None, Some(2)) => "1.2", + (Some(3), Some(3)) | (Some(3), None) => "1.3", + _ => "1.2+1.3", + } + .to_string(); + let level_desc = level_name(max_level()).to_string(); + + let mitm = init_mitm(tls_versions); + let mitm_desc = match mitm.as_ref() { + Some(m) if m.suffixes.is_empty() => "all".to_string(), + Some(m) => m.suffixes.join(","), + None => "off".to_string(), + }; + + let state = AppState { + client, + upstream: upstream.clone(), + tunnel_via: parse_tunnel_via(&env::var("LLM_PROXY_UPSTREAM_PROXY").unwrap_or_default()), + mitm, + log_file, + log_bodies, + }; + + let app = Router::new().fallback(proxy_handler).with_state(state); + let listener = tokio::net::TcpListener::bind(&listen_addr) + .await + .expect("bind listen address"); + + log_line!( + Level::Info, + "llm-proxy (rust) listening on http://{listen_addr} -> {route} (upstream proxy: {proxy_desc}, mitm: {mitm_desc}, tls: {tls_desc}, level: {level_desc}, llm-logs: {log_display})", + route = upstream.as_deref().unwrap_or("direct"), + log_display = log_path.as_deref().unwrap_or("disabled") + ); + axum::serve(listener, app).await.expect("serve"); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn forwards_absolute_uris_to_their_own_host() { + let uri: Uri = "https://other.example.com/openai/v1/models".parse().unwrap(); + assert_eq!( + resolve_target(Some("https://default.example.com"), &uri), + Some("https://other.example.com/openai/v1/models".to_string()) + ); + // ... even with no LLM_PROXY_UPSTREAM_URL configured (direct mode). + assert_eq!( + resolve_target(None, &uri), + Some("https://other.example.com/openai/v1/models".to_string()) + ); + } + + #[test] + fn falls_back_to_upstream_for_origin_form() { + let uri: Uri = "/openai/v1/chat/completions?api-version=xyz".parse().unwrap(); + assert_eq!( + resolve_target(Some("https://default.example.com"), &uri), + Some("https://default.example.com/openai/v1/chat/completions?api-version=xyz".to_string()) + ); + } + + #[test] + fn rejects_origin_form_without_upstream() { + let uri: Uri = "/openai/v1/chat/completions".parse().unwrap(); + assert_eq!(resolve_target(None, &uri), None); + } + + #[test] + fn matches_intercept_suffixes() { + let suffixes = parse_suffixes("cognitiveservices.azure.com, services.ai.azure.com"); + assert!(intercept_host( + "ais123.cognitiveservices.azure.com", + &suffixes + )); + assert!(intercept_host("COGNITIVESERVICES.AZURE.COM", &suffixes)); + assert!(!intercept_host("opencode.ai", &suffixes)); + assert!(!intercept_host("notazure.com", &suffixes)); + assert!(!intercept_host("", &suffixes)); + assert!(intercept_host("anything.example.com", &parse_suffixes("*"))); + // No configured suffixes: intercept everything. + assert!(intercept_host("anything.example.com", &[])); + assert!(intercept_host("opencode.ai", &[])); + assert!(!intercept_host("", &[])); + } + + #[test] + fn splits_connect_authority() { + assert_eq!(authority_host("example.com:443"), "example.com"); + assert_eq!(authority_host("example.com"), "example.com"); + assert_eq!(authority_host("[::1]:443"), "::1"); + assert_eq!(connect_port("example.com:443"), Some(443)); + assert_eq!(connect_port("example.com"), None); + assert_eq!(connect_port("example.com:80"), Some(80)); + } + + /// Throwaway in-memory CA for tests (production CAs are provisioned + /// separately via openssl and loaded with `load_ca_authority`). + #[cfg(test)] + fn test_issuer() -> rcgen::CertifiedIssuer<'static, KeyPair> { + use rcgen::{IsCa, BasicConstraints, KeyUsagePurpose}; + let mut params = + CertificateParams::new(vec!["llm-proxy test CA".to_string()]).unwrap(); + params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + params.key_usages = vec![ + KeyUsagePurpose::DigitalSignature, + KeyUsagePurpose::KeyCertSign, + KeyUsagePurpose::CrlSign, + ]; + let key = KeyPair::generate().unwrap(); + rcgen::CertifiedIssuer::self_signed(params, key).unwrap() + } + + #[tokio::test] + async fn mitm_negotiates_the_same_alpn_on_both_sides() { + let _ = rustls::crypto::ring::default_provider().install_default(); + let issuer = test_issuer(); + let mut roots = RootCertStore::empty(); + roots.add(issuer.der().clone()).unwrap(); + let (cert_der, key_der) = issue_leaf(&issuer, "upstream.example.com").unwrap(); + let mut cfg = ServerConfig::builder() + .with_no_client_auth() + .with_single_cert( + vec![CertificateDer::from(cert_der)], + PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key_der)), + ) + .unwrap(); + let h2 = b"h2".to_vec(); + let http1 = b"http/1.1".to_vec(); + cfg.alpn_protocols = vec![h2.clone(), http1.clone()]; + let cached_cfg = Arc::new(cfg); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + for (client_alpn, upstream_alpn, expected) in [ + ( + vec![h2.clone(), http1.clone()], + vec![http1.clone()], + Some(http1.clone()), + ), + ( + vec![h2.clone(), http1.clone()], + vec![h2.clone()], + Some(h2.clone()), + ), + ( + vec![http1.clone()], + vec![h2.clone(), http1.clone()], + Some(http1.clone()), + ), + (vec![], vec![h2.clone(), http1.clone()], None), + (vec![h2.clone(), http1.clone()], vec![], None), + ] { + let cc = ClientConfig::builder() + .with_root_certificates(roots.clone()) + .with_no_client_auth(); + let mut client_cfg = cc.clone(); + client_cfg.alpn_protocols = client_alpn; + let mut upstream_cfg = (*cached_cfg).clone(); + upstream_cfg.alpn_protocols = upstream_alpn; + let upstream_tcp = TcpStream::connect(listener.local_addr().unwrap()) + .await + .unwrap(); + let (upstream_io, _) = listener.accept().await.unwrap(); + let (client_io, proxy_io) = tokio::io::duplex(16384); + let name = ServerName::try_from("upstream.example.com").unwrap(); + let (client, proxy, upstream) = tokio::time::timeout(Duration::from_secs(5), async { + tokio::join!( + tokio_rustls::TlsConnector::from(Arc::new(client_cfg)) + .connect(name.clone(), client_io), + mitm_handshake(proxy_io, upstream_tcp, cached_cfg.clone(), cc, name, "upstream.example.com"), + tokio_rustls::TlsAcceptor::from(Arc::new(upstream_cfg)).accept(upstream_io), + ) + }) + .await + .expect("MITM handshake timed out"); + let client = client.expect("client handshake"); + let (proxy_client, proxy_upstream) = proxy.expect("proxy handshake"); + let upstream = upstream.expect("upstream handshake"); + for selected in [ + client.get_ref().1.alpn_protocol(), + proxy_client.get_ref().1.alpn_protocol(), + proxy_upstream.get_ref().1.alpn_protocol(), + upstream.get_ref().1.alpn_protocol(), + ] { + assert_eq!(selected, expected.as_deref()); + } + assert_eq!(cached_cfg.alpn_protocols, vec![h2.clone(), http1.clone()]); + } + } + + #[test] + fn handshake_failure_reason_maps_every_variant() { + use rustls::{ + AlertDescription, CertificateError, ContentType, HandshakeType, InvalidMessage, + PeerIncompatible, PeerMisbehaved, + }; + use std::collections::HashSet; + let cases: &[(&rustls::Error, &str)] = &[ + ( + &rustls::Error::AlertReceived(AlertDescription::HandshakeFailure), + "tls.handshake.failed.alert_received", + ), + ( + &rustls::Error::PeerIncompatible(PeerIncompatible::NoCipherSuitesInCommon), + "tls.handshake.failed.peer_incompatible", + ), + ( + &rustls::Error::PeerMisbehaved(PeerMisbehaved::IllegalMiddleboxChangeCipherSpec), + "tls.handshake.failed.peer_misbehaved", + ), + ( + &rustls::Error::InvalidMessage(InvalidMessage::InvalidContentType), + "tls.handshake.failed.invalid_message", + ), + ( + &rustls::Error::InappropriateMessage { + expect_types: vec![ContentType::Handshake], + got_type: ContentType::ApplicationData, + }, + "tls.handshake.failed.inappropriate_message", + ), + ( + &rustls::Error::InappropriateHandshakeMessage { + expect_types: vec![HandshakeType::ClientHello], + got_type: HandshakeType::Finished, + }, + "tls.handshake.failed.inappropriate_handshake_message", + ), + ( + &rustls::Error::PeerSentOversizedRecord, + "tls.handshake.failed.oversized_record", + ), + ( + &rustls::Error::NoApplicationProtocol, + "tls.handshake.failed.no_alpn", + ), + ( + &rustls::Error::InvalidCertificate(CertificateError::Expired), + "tls.handshake.failed.invalid_certificate", + ), + ( + &rustls::Error::DecryptError, + "tls.handshake.failed.decrypt_error", + ), + ( + &rustls::Error::NoCertificatesPresented, + "tls.handshake.failed.no_certificates_present", + ), + ( + &rustls::Error::General("test".to_owned()), + "tls.handshake.failed.other", + ), + (&rustls::Error::EncryptError, "tls.handshake.failed.other"), + ( + &rustls::Error::FailedToGetCurrentTime, + "tls.handshake.failed.other", + ), + ( + &rustls::Error::HandshakeNotComplete, + "tls.handshake.failed.other", + ), + ]; + let mut seen = HashSet::new(); + for (err, expected) in cases { + let got = handshake_failure_reason(err); + assert_eq!(got, *expected, "variant {err:?} → {got}, want {expected}"); + assert!(got.starts_with("tls.handshake.failed."), "reason {got} escaped namespace"); + seen.insert(got); + } + assert_eq!(seen.len(), 12, "unexpected key set: {seen:?}"); + } + + #[test] + fn ca_roundtrip_issues_usable_leaf() { // ServerConfig::builder() needs the process-default provider (main() + // installs it in production). + let _ = rustls::crypto::ring::default_provider().install_default(); + let issuer = test_issuer(); + for host in ["deepseek.example.com", "127.0.0.1"] { + let (cert_der, key_der) = issue_leaf(&issuer, host).expect("issue leaf"); + assert!(!cert_der.is_empty() && !key_der.is_empty()); + // Leaf must build a working server config. + let mut cfg = ServerConfig::builder() + .with_no_client_auth() + .with_single_cert( + vec![CertificateDer::from(cert_der)], + PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key_der)), + ) + .expect("server config"); + cfg.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; + } + } + + #[test] + fn missing_ca_disables_mitm_with_actionable_error() { + let dir = std::env::temp_dir().join(format!("llm-proxy-test-{}", std::process::id())); + let err = match load_ca_authority( + &dir.join("does-not-exist-cert.pem"), + &dir.join("does-not-exist-key.pem"), + ) { + Ok(_) => panic!("must fail without CA files"), + Err(e) => e, + }; + assert!(err.contains("baked into the image"), "{err}"); + } + + #[test] + fn tls_version_matrix() { + // Parsing: only "1.2"/"1.3" (or empty = unset) are accepted. + assert_eq!(parse_tls_version("", "V").unwrap(), None); + assert_eq!(parse_tls_version(" ", "V").unwrap(), None); + assert_eq!(parse_tls_version("1.2", "V").unwrap(), Some(2)); + assert_eq!(parse_tls_version("1.3", "V").unwrap(), Some(3)); + for bad in ["1.0", "1.1", "tls1.2", "2", "12", "v1.3"] { + assert!(parse_tls_version(bad, "V").is_err(), "{bad}"); + } + // (min, max) matrix; true = enabled. + let matrix: Vec<(Option, Option, bool, bool)> = vec![ + (None, None, true, true), // default + (None, Some(2), false, true), // max 1.2 + (None, Some(3), true, true), // max 1.3: no-op + (Some(2), None, true, true), // min 1.2: no-op + (Some(2), Some(2), false, true), + (Some(2), Some(3), true, true), + (Some(3), None, true, false), // min 1.3 + (Some(3), Some(3), true, false), + ]; + for (min, max, v13, v12) in matrix { + let versions = tls_versions(min, max).unwrap(); + assert_eq!( + versions.len(), + usize::from(v13) + usize::from(v12), + "min={min:?} max={max:?}" + ); + assert_eq!(versions.contains(&&TLS13), v13, "min={min:?} max={max:?}"); + assert_eq!(versions.contains(&&TLS12), v12, "min={min:?} max={max:?}"); + } + // Contradiction and invalid input are startup errors. + assert!(tls_versions(Some(3), Some(2)).is_err()); + assert!(parse_tls_version("1.1", "LLM_PROXY_TLS_MIN_VERSION").is_err()); + } + + #[test] + fn parses_tunnel_upstream() { + assert!(matches!(parse_tunnel_via(""), TunnelVia::Direct)); + assert!(matches!(parse_tunnel_via("direct"), TunnelVia::Direct)); + match parse_tunnel_via("http://user:pass@corp:3128") { + TunnelVia::HttpProxy { addr, auth } => { + assert_eq!(addr, "corp:3128"); + assert!(auth.is_some()); + } + other => panic!("expected HttpProxy, got {:?}", std::mem::discriminant(&other)), + } + assert!(matches!( + parse_tunnel_via("socks5h://127.0.0.1:1080"), + TunnelVia::Unsupported + )); + } + + #[test] + fn parses_log_levels() { + assert_eq!(parse_log_level("").unwrap(), Level::Info); + assert_eq!(parse_log_level(" ").unwrap(), Level::Info); + assert_eq!(parse_log_level("INFO").unwrap(), Level::Info); + assert_eq!(parse_log_level("info").unwrap(), Level::Info); + assert_eq!(parse_log_level("ERROR").unwrap(), Level::Error); + assert_eq!(parse_log_level("warn").unwrap(), Level::Warn); + assert_eq!(parse_log_level("WARNING").unwrap(), Level::Warn); + assert_eq!(parse_log_level("Debug").unwrap(), Level::Debug); + for bad in ["TRACE", "verbose", "1", "warningg"] { + assert!(parse_log_level(bad).is_err(), "{bad}"); + } + // Ordering: Error < Warn < Info < Debug (level > max means filtered). + assert!(Level::Error < Level::Warn); + assert!(Level::Warn < Level::Info); + assert!(Level::Info < Level::Debug); + } +} diff --git a/scripts/entrypoint.sh b/scripts/entrypoint.sh index c965716..8c41ada 100644 --- a/scripts/entrypoint.sh +++ b/scripts/entrypoint.sh @@ -4,6 +4,81 @@ # Ensure MISE configuration is loaded source /etc/bash.bashrc +: "${LLM_PROXY_LISTEN_ADDR:=127.0.0.1:8899}" +export LLM_PROXY_LISTEN_ADDR + +# LLM_PROXY_ENABLED=off (or 0/false/no) disables the proxy entirely: no env +# enforcement, no startup. +case "${LLM_PROXY_ENABLED,,}" in + off|0|false|no) _llm_proxy_off=1;; +esac +if [[ "${_llm_proxy_off:-}" == "1" ]]; then + echo "llm-proxy disabled via LLM_PROXY_ENABLED=off." >&2 + unset _llm_proxy_off +else + ### + # Proxy lockdown (entrypoint-only, runs at container start): llm-proxy takes + # ALL container traffic, so HTTP(S)_PROXY must point at it — chain llm-proxy + # itself upstream via LLM_PROXY_UPSTREAM_PROXY instead. + _listen="${LLM_PROXY_LISTEN_ADDR}" + [[ "${_listen}" == :* ]] && _listen="127.0.0.1${_listen}" + _proxy_url="http://${_listen}" + for _proxy_var in HTTP_PROXY HTTPS_PROXY http_proxy https_proxy; do + if [[ "${!_proxy_var:-}" != "${_proxy_url}" ]]; then + if [[ -n "${!_proxy_var:-}" ]]; then + echo "WARNING: ${_proxy_var} is set to a custom proxy; overriding it with ${_proxy_url}. Chain llm-proxy upstream via LLM_PROXY_UPSTREAM_PROXY instead." >&2 + fi + export "${_proxy_var}=${_proxy_url}" + fi + done + for _proxy_var in ALL_PROXY all_proxy; do + if [[ -n "${!_proxy_var:-}" ]]; then + echo "WARNING: ${_proxy_var} is set; ignoring it. Chain llm-proxy upstream via LLM_PROXY_UPSTREAM_PROXY instead." >&2 + unset "${_proxy_var}" + fi + done + + # Plain-HTTP traffic to llm-proxy must never be sent to an outbound proxy. + _enforced_no_proxy="localhost,127.0.0.1" + for _proxy_var in NO_PROXY no_proxy; do + if [[ -n "${!_proxy_var:-}" && "${!_proxy_var}" != "${_enforced_no_proxy}" ]]; then + echo "WARNING: ${_proxy_var} is set; overriding it with ${_enforced_no_proxy}." >&2 + fi + export "${_proxy_var}=${_enforced_no_proxy}" + done + unset _proxy_var _listen _proxy_url _enforced_no_proxy + + # LLM_PROXY_UPSTREAM_URL is optional: when set, origin-form requests go there; when + # unset, the proxy connects directly to whatever host each (absolute-form) + # request names. Point your Azure provider baseURL at + # http://127.0.0.1:8899/openai/v1 to route through it. + + ### + # Start llm-proxy and wait for its port. The proxy routes its own logs + # (LLM_PROXY_LOGFILE file, else syslog), so its stdio is dead weight — sever + # it so the TUI never shares a terminal with the proxy. (Pre-init failures + # still surface via the port wait below, not via the proxy's stderr.) + llm-proxy /dev/null 2>&1 & + _llm_proxy_pid=$! + + _llm_proxy_port="${LLM_PROXY_LISTEN_ADDR##*:}" + for _i in $(seq 1 100); do + if (echo >"/dev/tcp/127.0.0.1/${_llm_proxy_port}") 2>/dev/null; then + break + fi + if ! kill -0 "${_llm_proxy_pid}" 2>/dev/null; then + echo "ERROR: llm-proxy exited before listening on ${LLM_PROXY_LISTEN_ADDR}. Check syslog (tag llm-proxy)${LLM_PROXY_LOGFILE:+ or ${LLM_PROXY_LOGFILE}}." >&2 + exit 1 + fi + sleep 0.1 + done + if ! (echo >"/dev/tcp/127.0.0.1/${_llm_proxy_port}") 2>/dev/null; then + echo "ERROR: llm-proxy did not listen on ${LLM_PROXY_LISTEN_ADDR} in time. Check syslog (tag llm-proxy)${LLM_PROXY_LOGFILE:+ or ${LLM_PROXY_LOGFILE}}." >&2 + exit 1 + fi + unset _llm_proxy_pid _llm_proxy_port _i _llm_proxy_off +fi + GEMINI_CREDS_PATH="${GEMINI_OAUTH_CREDS_PATH:-$HOME/.gemini/oauth_creds.json}" CONVERTER_PATH="${CONVERTER_PATH:-/usr/local/bin/convert-gemini.auth.ts}"