Skip to content

Studio: run llama-server with a per-launch API key by default - #13011

Merged
danielhanchen merged 8 commits into
mainfrom
sec/llama-server-key
Oct 8, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
sec/llama-server-key

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 8, 2026 •

Copy link
Copy Markdown
Member

Studio's llama-server children listen on a random 127.0.0.1 port and answer with permissive CORS. Without an API key, a web page the user has open can find the port and read /slots (the prompts and replies of the current conversation), /props, /metrics and /tokenize, or run its own generations. Requests that need no CORS preflight reach it directly. The key existed only behind UNSLOTH_DIRECT_STREAM=1.

Every load now starts llama-server with a random per-launch key, and every Studio request to it sends that key.

  • Key handling:
    • The key goes through --api-key-file, never the command line. The file is 0600 in Studio's auth directory, one per backend, rewritten in place on a relaunch and removed on unload.
    • Key files left behind by a killed Studio are swept on the next launch.
    • UNSLOTH_LLAMA_SERVER_API_KEY=0 turns the key off; UNSLOTH_DIRECT_STREAM=1 still forces it on.
  • Callers that did not send the key yet:
    • /v1/completions (stream and non-stream), /v1/embeddings, the Responses stream, and the /v1/messages passthrough (stream, retry and non-stream) now share one header helper.
    • The /metrics stats scrape now receives the key as well.
    • Chat, tokenize, /props, /slots and template calls already sent it through _auth_headers.
  • Custom builds: the --help capability probe now reports --api-key-file. A custom LLAMA_SERVER_PATH build whose help lacks it starts without a key, as before, and logs a warning instead of failing to load. A failed probe still sends the flag, the same way --jinja is handled.
  • RAG embedding server: the knowledge-base embedding llama-server gets its own per-spawn key, sent on embeddings and /props. The key file is deleted once the server is healthy.
  • Metrics scrape: it now uses a proxy-free opener, so the bearer never reaches an ambient HTTP_PROXY.
  • MTMD dictation server: the dictation llama-server in stt_mtmd_sidecar.py gets its own per-launch key. Its file is deleted once the server is ready, because llama-server reads the key only at startup.
  • Tool sandbox: the sandbox already refused to read the old fixed key file name; its pattern now also covers the per-launch name, including bare and glob searches (find / -name 'llama_api_key_*').

Testing:

  • New tests/test_llama_server_api_key_default.py:
    • the default and the opt-out;
    • the private, per-backend file and the stale-file sweep;
    • the tool guard;
    • the stats scrape header;
    • an AST check that every llama-server request in routes/inference.py sends the key.
  • New MTMD test: the launch gets --api-key-file, the file is gone once the server is ready, and the transcription request sends the bearer.
  • llama_extra_args launch-command tests now mask the per-launch key path, as they already mask the port. 117 passed together with the new tests.
  • STT suites: 441 passed. The related backend suites fail identically on main and this branch, in 4 admission/catalog files this PR does not touch.
  • End to end with a real Studio backend and llama-server (gemma-3-270m, plus Qwen3-0.6B for tool passthroughs):
request main this PR
raw /slots, /props, /tokenize, /metrics, /v1/chat/completions without the key (also with Origin: https://evil.example) 200 401
raw /health 200 200
Studio chat (stream, non-stream, UI stream, tools), /v1/completions, /v1/embeddings, /v1/responses, /v1/messages (with tools), count_tokens, /props works works
main with only the key turned on n/a /v1/completions, Responses stream and /v1/messages tool passthrough fail with Invalid API Key (the header fixes above)
  • Real RAG embedding server (bge-small): Studio's embedding calls return 384-dim vectors. Raw keyless /slots and /v1/embeddings return 401, and no key file is left on disk.
  • A real llama-server whose key file is deleted after /health turns 200 still answers 401 without the key and 200 with it.

Performance: the key costs nothing measurable. Six alternating launches per arm, 20 requests each, same GPU and model, through Studio's /v1/chat/completions:

metric key off (main) key on spread across key-off launches
streaming TTFT 21.64 ms 21.92 ms 1.24 ms
decode tokens/s 865 830 121
non-streaming latency (128 tokens) 130.2 ms 129.3 ms 16.8 ms

llama-server answers with permissive CORS, so any web page the user has
open could drive the loopback server and read /slots, /props and
completions. Every launch now writes a random key to a 0600 file under
the auth directory and passes --api-key-file; /health stays public.

Every Studio request to llama-server already sent the backend's Bearer
header except /v1/completions (stream and non-stream), /v1/embeddings,
the Responses stream, the Anthropic passthrough (stream and non-stream)
and the /metrics stats scrape. Those now send it too.

UNSLOTH_LLAMA_SERVER_API_KEY=0 opts out (UNSLOTH_DIRECT_STREAM=1 still
forces the key on). The key file is one per backend, rewritten on a
relaunch and removed on unload, and the tool sandbox refuses the new
suffixed name.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-08T06:54:24.101916Z a4a805d New commits
🔒 Security Review ⚠️ Failed 2026-10-08T03:07:49.132969Z a891b2e PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a891b2e1db

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +7568 to +7573
def _llama_server_api_key_enabled() -> bool:
"""Launch llama-server with a per-launch API key; UNSLOTH_LLAMA_SERVER_API_KEY=0 opts out unless direct streaming
(UNSLOTH_DIRECT_STREAM=1) needs the key."""
return (
os.getenv("UNSLOTH_DIRECT_STREAM", "0") == "1"
or os.getenv("UNSLOTH_LLAMA_SERVER_API_KEY", "1") != "0"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Protect the RAG embedding llama-server too

Apply this default-key policy to core/rag/embed_llama_server.py as well. Whenever the resolved RAG backend is llama-server, _build_cmd() still launches a dedicated server without --api-key-file and _post_active() sends no authorization header, so a web page can probe its loopback port and access endpoints such as /slots while document chunks are being embedded—the same exposure this change closes for chat and MTMD servers.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ed20342: the RAG embed llama-server gets its own per-spawn key (file removed once healthy) and sends it on embeddings and /props. Real check with bge-small: embeddings work, keyless /slots and /v1/embeddings return 401, no key file left. Test added.

Comment on lines +28459 to +28463
if _llama_server_api_key_enabled():
self._api_key = _secrets.token_urlsafe(32)
# Through a file, not argv: a command line is readable by every process of this Unix user, and the auth directory is not.
cmd.extend(["--api-key-file", str(_write_direct_stream_key(self._api_key))])
logger.info("llama-server started with --api-key-file for direct streaming")
self._api_key_file = _write_direct_stream_key(self._api_key, self._api_key_file)
cmd.extend(["--api-key-file", str(self._api_key_file)])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Probe custom binaries before requiring api-key-file

Gate this flag through the existing llama-server --help capability probe. Studio explicitly supports arbitrary binaries through LLAMA_SERVER_PATH, UNSLOTH_LLAMA_CPP_PATH, custom settings, and PATH, and the surrounding launcher already notes that an unknown option makes such a server exit immediately; because the key is now enabled by default, any otherwise-compatible custom build that predates --api-key-file can no longer load any GGUF model unless the operator discovers and sets the opt-out environment variable.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ed20342: the --help capability probe now reports supports_api_key_file (fail open like --jinja), and a build whose help positively lacks it starts without a key and logs a warning. The RAG server uses the same check.

# Path form only: the bare name is an ordinary identifier. auth.db is absent for the same reason,
# and Studio's copy is covered by the auth-directory patterns below.
+ r"|[/\\]llama_api_key"
+ r"|[/\\]llama_api_key(?:_\w+)?"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject basename searches for randomized key files

When server tools are enabled, this pattern still allows discovery commands such as find / -name 'llama_api_key_*' -exec cat {} +: the new regex requires a slash immediately before the basename, while the separate bare-basename check only triggers when the command also names the Studio root. Because the main server's live key file remains on disk until unload and tool subprocesses run as the same OS user, a tool can recover and expose the bearer key without triggering the credential guard; basename/glob searches for this prefix need to be classified as credential access too.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ed20342: the credential guard matches the per-launch name bare and as a glob (find / -name 'llama_api_key_*'), not only after a slash. The unsuffixed name stays an ordinary identifier. Test added.

Comment on lines +63 to +65
with urllib.request.urlopen(
urllib.request.Request(self._url, headers = self._headers), timeout = 3
) as r:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bypass ambient proxies for authenticated metrics scrapes

Use a proxy-disabled opener for this loopback request. urllib.request.urlopen() honors HTTP_PROXY, so when that variable is set and NO_PROXY does not include 127.0.0.1, every scrape forwards the newly added Authorization: Bearer … header to the ambient proxy instead of directly to llama-server; the other loopback clients in this repository explicitly use trust_env=False for this reason. Building an opener with ProxyHandler({}) (or using a proxy-disabled HTTP client) avoids disclosing the per-launch key.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ed20342: the metrics scrape uses an opener with an empty ProxyHandler, so the bearer only goes to the loopback server. Test checks the opener.

…i-key-file, proxy-free metrics scrape, refuse key-file searches
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 8, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ed20342eb7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

)

api_key = key_file = None
if _llama_server_api_key_enabled():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Probe the MTMD binary before adding api-key-file

Gate the MTMD key flag with LlamaCppBackend.probe_server_capabilities() as the chat and RAG launchers do. find_llama_server_binary() uses the same resolver that accepts LLAMA_SERVER_PATH, UNSLOTH_LLAMA_CPP_PATH, and other custom binaries, but this new path unconditionally adds --api-key-file; an otherwise MTMD-capable custom build without that option exits immediately, making dictation unavailable unless the operator discovers the global key opt-out. Although the earlier custom-binary issue was fixed for the chat and RAG servers, this newly added MTMD launch remains ungated.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9f1a3ff: the MTMD sidecar checks the same supports_api_key_file capability (fail open on a failed probe) and starts a build without the flag keyless, as before. Test added.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 8, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 9f1a3ff314

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 9e7fb4a49d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 26, 2026
…ver recovers on every API route (unslothai#15138)

Every Studio route that proxies to llama-server built its own URL, auth
header, per-request client, cancel watcher and crash-respawn retry:
eight copies across `/v1/chat/completions`, `/v1/messages`,
`/v1/responses`, `/v1/completions` and `/v1/embeddings`, holding 20
hand-built llama-server URLs and headers in `routes/inference.py`. Fixes
landed one copy at a time:
- unslothai#8999 gave `/v1/chat/completions` the respawn `/v1/messages` already
had, and stopped there.
- unslothai#13011 found `/v1/completions`, `/v1/embeddings`, the Responses stream
and `/v1/messages` still sending no per-launch key.
- The disconnect handling was copied path by path in unslothai#10096, unslothai#9312,
unslothai#11961 and unslothai#9616.

So when llama-server was killed and relaunched on a new port, only chat
recovered fully. `/v1/messages` recovered from a refused connection but
not from a connection dropped before upstream response headers, and
every other route failed each request until something else reloaded the
model.

## Changes

- `_LlamaUpstream` owns a request's calls to llama-server:
  - the URL and per-launch key, which move together after a relaunch;
- one respawn per request, on a lost connection and never on a timeout;
  - a per-request client that a Stop or a disconnect closes;
- a recovery wait that continues streaming keepalives and lets cancelled
requests release their resources while the backend reload finishes
independently;
  - the rule that tells a cancel from a transport error.
- `_monitored_llama_call` replaces the swap-gate and API-monitor shell
that `/v1/completions` and `/v1/embeddings` each spelled out.
- `_llama_stream_client` replaces four streaming client constructions
that disagreed on keep-alive.
- Every llama-server request in `routes/inference.py` goes through
`_LlamaUpstream`. The source scan that counted call sites for the key
now checks that instead.
- The non-streaming OpenAI passthrough's pooled-client branch is gone.
Production always passes a request, so only tests reached it; they now
patch the per-request client.

## Crash recovery

- **Streaming `/v1/responses` (Codex) now respawns.** It had no retry,
so after a crash every Codex request failed with "Lost connection to the
model server" until a chat request or a manual reload.
- **`/v1/completions` and `/v1/embeddings` now respawn.** Non-streaming,
they previously surfaced the raw `ConnectError` as a 500.
- **`/v1/messages` now retries lost connections**
(`RemoteProtocolError`, `ReadError`), not only a refused connection,
which is the rule chat already used. Streaming recovery applies only
before upstream response headers arrive; a server can send those headers
before prefill finishes. A failure after headers is not replayed. Its
non-streaming nudge retry shares the request's one respawn.
- **Responses, completions and embeddings now hand an MTP crash to its
recovery (unslothai#13316)** before respawning; they never called it.
- **A Stop that lands between two POSTs of one request now reports 499
instead of a server error.** This covers an embeddings `/tokenize` call
or a `/v1/messages` nudge retry sent after the Stop closed the client.
- **Streaming chat errors after recovery keepalives use the SSE
response.** If recovery outlasts the pre-header status window, the
response can already be HTTP 200; a later failure is delivered as an
error event. Recovery failures completed within that window still return
502.

Reloads still run in the shared thread pool and are serialized by the
backend. Burst-load behavior during a reload is unmeasured.

## Validation

- **Teardown and tokenization:** 1,096 selected backend tests passed; 1
skipped. Six new cases cover cancellation during watcher cleanup on all
four non-streaming paths and embedding truncation after another request
restarts the server, including a restart between the two tokenization
calls.
- **Recovery-wait follow-up:** 80 recovery tests and 1,317 other
selected backend tests passed; 1 skipped. These cover delayed reload
keepalives, Stop/disconnect and task cancellation, admission and
registration cleanup, retry limits, refreshed URL/key pairs, and
cancellation at reload completion. The broad-suite and live socket
checks below preceded this follow-up; no live model reload was repeated.
- **Initial Linux, Python 3.13, CPU run:** I ran the 344 backend test
files that import `routes/inference.py` (CI's serial-only and
live-server exclusions applied). 23,011 passed and 386 skipped.
- **Existing failures, not from this change:** 261 failures and errors
in torch-backed diffusion, audio and GPU tests also fail on `main` with
this sandbox's broken torch. None fails only on this branch.
- **Count-the-call-sites guards:** three source scans counted copies
(the auth-header scan, the five-client `trust_env` scan and the
direct-counter placement scan). They now check the one owner instead.
- `test_llama_upstream_single_owner.py` exercises refused connections
and connections dropped before upstream headers, along with blocked
reloads that verify keepalives and prompt Stop/disconnect cleanup
without a retry after cancellation.
- Formatted with `scripts/run_ruff_format.py` (ruff 0.6.9); `ruff check`
(0.16.10) is clean.

Initial live crash check: a real stand-in llama-server process on a real
port, either SIGKILLed or exiting mid-request, then relaunched by
`_respawn_if_dead` on a new port with a new key. Each route was driven
over real sockets.

| Case | Before | After |
|---|---|---|
| `/v1/responses` stream (Codex), server killed | `response.failed`:
"Lost connection to the model server" | Answers from the relaunched
server |
| `/v1/completions`, server killed | 500 Internal Server Error
(`ConnectError`) | Answers |
| `/v1/completions` stream, server killed | Error chunk: "Lost
connection…" | Answers |
| `/v1/embeddings`, server killed | 500 Internal Server Error
(`ConnectError`) | Answers |
| `/v1/messages`, server dies mid-prefill | 500 Internal Server Error
(`RemoteProtocolError`) | Answers |
| `/v1/messages` stream, connection drops before upstream headers |
`error` event: "Lost connection…" | Answers |
| `/v1/chat/completions`, stream and non-stream, both crashes | Answers
| Answers |

---------

Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant