Skip to content

Studio: accept x-api-key authentication - #7656

Closed
ousamabenyounes wants to merge 8 commits into
unslothai:mainfrom
ousamabenyounes:fix/issue-6399
Closed

ousamabenyounes wants to merge 8 commits into
unslothai:mainfrom
ousamabenyounes:fix/issue-6399

Conversation

@ousamabenyounes

@ousamabenyounes ousamabenyounes commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • accept Studio API keys from the x-api-key header while preserving Bearer authentication
  • route header credentials through the existing API-key validation and credential-generation checks
  • keep rebased keyless API access semantics consistent: real sk-unsloth header keys authenticate as credentials, dummy SDK keys stay keyless, and desktop-only guards treat header-key callers as non-desktop instead of erroring
  • expose both authentication alternatives in FastAPI/OpenAPI and cover invalid, missing, session-token, keyless, and dual-header cases

Closes #6399

Test verification (RED -> GREEN)

RED before the follow-up fix:

  • tests/test_x_api_key_auth.py::test_x_api_key_password_change_routes_reach_desktop_guard failed with assert 500 == 403, reproducing the reviewer's missing-bearer authenticated_via_desktop_jwt failure for an x-api-key password-change route.
  • tests/test_x_api_key_auth.py::test_x_api_key_takes_precedence_over_keyless_admission failed with assert 'unsloth' == 'office-user', showing synthetic keyless credentials shadowed a real header API key after the rebase.
  • tests/test_x_api_key_auth.py::test_dummy_x_api_key_keeps_keyless_admission raised HTTPException: 401, showing dummy SDK x-api-key values no longer stayed keyless.
  • tests/test_keyless_api_access.py::test_credentials_never_downgrade_to_keyless failed because asgi_request_is_keyless(...) returned True for a real sk-unsloth x-api-key.

GREEN after the fix:

  • ./run-ci.sh final: 18 passed, 1 warning; Ruff and py_compile passed for the changed auth/keyless modules and tests; Python changed-line coverage passed at 40/40 changed executable lines.

  • Keyless regression replay: test_tool_policy_and_api_identity, test_scope_off_is_refused_by_the_security_dependency_not_only_the_predicate, and test_the_asgi_twin_agrees_with_the_dependency_on_header_shapes passed locally after preserving strict Bearer failures when no x-api-key is present.

  • python -m pytest -v --tb=short tests/test_python39_compatibility.py::test_studio_evaluated_unions_do_not_grow: passed locally after adding the required future annotations import.

  • ./run-ci.sh baseline on origin/main: applicable syntax/lint passed; existing keyless auth test passed; the new x-api-key test file is absent on baseline.

Earlier branch validation remains relevant for the original PR scope:

  • real GET /v1/models HTTP smoke with x-api-key and no Bearer header: passed
  • targeted auth/desktop suite: passed before the rebase follow-up; the rebased local gate above covers the reviewed auth/keyless paths
  • repo CPU suite had the documented pre-existing environment-dependent disk-space failure (test_window_without_kv_dims_still_saves) on both upstream main and this branch; this follow-up does not touch the root unsloth/ package

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@ousamabenyounes

This comment has been minimized.

ousamabenyounes and others added 7 commits August 30, 2026 09:25
Treat header API keys as real credentials before synthetic keyless credentials, keep dummy SDK keys keyless, and make desktop-JWT classification tolerate missing bearer credentials.

RED: x-api-key desktop guard returned 500 instead of 403; keyless precedence and dummy x-api-key cases failed. GREEN: run-ci.sh passed 16 tests with Ruff, py_compile, and 21/21 changed executable lines covered.
@danielhanchen danielhanchen added conflicts# security# Moves a security boundary: sandbox, allowlist, permission or network guard labels Sep 14, 2026
@danielhanchen danielhanchen self-assigned this Oct 4, 2026
Resolve the authentication.py conflict (keep main's _bind_owner and docstrings with the
x-api-key dependencies), move the x-api-key test mocks to validate_api_key_account, and stop
recording a request as keyless when x-api-key carries a real key, so keyless-only restrictions
do not apply to a keyed caller (the ASGI twin already said so; both now share one predicate).
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 4, 2026
@danielhanchen danielhanchen removed conflicts# security# Moves a security boundary: sandbox, allowlist, permission or network guard labels Oct 4, 2026
jasonjack-jay pushed a commit to jasonjack-jay/unsloth that referenced this pull request Oct 15, 2026
…#13842)

Fixes unslothai#6399

Studio only read the API key from `Authorization: Bearer`. Anthropic
clients send it in `x-api-key` instead: the Anthropic SDKs (`api_key=`),
CLIs that read `ANTHROPIC_API_KEY`, and the Claude for Microsoft 365
add-ins (their gateway mode sends `x-api-key` by default). So `GET
/v1/models` and `POST /v1/messages` answered `401 Not authenticated`
even with a valid `sk-unsloth-...` key. This is also what tripped unslothai#8663.

## What changes

A small pure ASGI middleware, registered outermost, copies the
`x-api-key` value into `Authorization: Bearer` when:

- there is exactly one `x-api-key` header,
- its value starts with `sk-unsloth-`, and
- the request has no usable `Authorization` (absent or an empty
`Bearer`).

Every existing reader of `Authorization` then handles the request
unchanged: the auth dependency, the keyless access classifier and tool
clamp, keep-warm, and the MCP gate. Doing this once at the edge avoids
teaching each of those readers a second header.

Nothing changes for current clients:

- A request that already carries a Bearer (UI session, desktop JWT, API
key) is left alone, so Bearer always wins.
- Any `x-api-key` value that is not an `sk-unsloth-` key (for example a
dummy such as `not-needed` sent to keyless access, or a cloud
`sk-ant-...` key) is ignored, exactly as today.
- No UI, Desktop, or notebook flow is touched. The rewrite is
idempotent: once `Authorization` is set, a second pass is a no-op.

`GET /v1/models` already existed. CORS already allows any origin outside
the locked-down Desktop API mode, and the preflight echoes `x-api-key`
and `anthropic-version`.

This supersedes unslothai#7656 by @ousamabenyounes (closed, and not editable by
maintainers). Thanks for the original work and the test ideas. That PR
threaded the header through each auth dependency; this version keeps the
change to one place.

## Testing

`tests/test_x_api_key_auth.py` covers the following against a real auth
DB with a real API key:

- `x-api-key` authenticates exactly like Bearer.
- An empty Bearer plus `x-api-key` still works.
- Missing, invalid, dummy and non-Unsloth keys are still refused.
- A session Bearer wins over `x-api-key`.
- Keyless access is unchanged for dummy keys, and a real key is not
treated as keyless.
- The rewrite is idempotent.
- The middleware is the outermost layer in `main.py`. Removing the
registration fails this test.

Real Studio app (`main.app`), merge base vs this branch:

| Request | Before | After |
|---|---|---|
| `GET /v1/models` with `x-api-key: sk-unsloth-...` | 401 `Not
authenticated` | 200, model list |
| `POST /v1/messages` with `x-api-key: sk-unsloth-...` | 401
`authentication_error` | reaches the handler (503 `No GGUF model loaded`
in the test, no model) |
| `GET /v1/models` with an invalid `sk-unsloth-` key | 401 | 401
`Invalid or expired API key` |
| `GET /v1/models` with no credentials | 401 | 401 |
| `GET /v1/models` with Bearer | 200 | 200 |
| CORS preflight from `https://pivot.claude.ai` | 200, echoes
`x-api-key,anthropic-version,content-type` | same |

Also ran `test_keyless_api_access.py`,
`test_keyless_api_access_adversarial.py`, `test_middleware.py`,
`test_mcp_http_integration.py` and `test_python39_compatibility.py`, all
passing. The rewrite costs about 1.6 us per HTTP request (once per
request, not per token).
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.

[Feature] Support Claude for Microsoft Office

2 participants