Skip to content

feat(xai): support multi-account SuperGrok OAuth with automatic failover - #40242

Open
HXhlx wants to merge 15 commits into
BerriAI:mainfrom
HXhlx:feat/xai-supergrok-oauth-failover
Open

HXhlx wants to merge 15 commits into
BerriAI:mainfrom
HXhlx:feat/xai-supergrok-oauth-failover

Conversation

@HXhlx

@HXhlx HXhlx commented Sep 8, 2026 •

Copy link
Copy Markdown

TLDR

Problem this solves:

  • A proxy can only use one SuperGrok OAuth account
  • When that account hits its spending limit, every xAI request fails
  • xAI's spending-limit 403 isn't retryable, so the router never fails over

How it solves it:

  • New xai_oauth_token_file deployment param picks that deployment's OAuth account
  • litellm xai-oauth login <account> writes a separate auth-<account>.json
  • The token file must resolve inside XAI_OAUTH_TOKEN_DIR, symlinks included
  • The xAI adapter reports a spending-limit 403 as a 429, so the router fails over
  • The field is server-owned: requests can't set it, and only proxy admins can change it on a deployment

User Flow

Before: an operator with two SuperGrok accounts can serve only one, and traffic stops when it runs out

  1. The admin runs litellm xai-oauth login, which always writes the single auth.json
  2. The admin adds a use_xai_oauth: true deployment for xai/grok-4.7 under the model name grok
  3. A client sends POST http://localhost:4000/v1/chat/completions with "model": "grok" until the account hits its spending limit
  4. The client gets back xAI's 403 spending-limit error and no other account is tried

After: the same operator logs in both accounts, and the proxy moves to the second one when the first runs out

  1. The admin runs litellm xai-oauth login alice and litellm xai-oauth login bob, which write auth-alice.json and auth-bob.json
  2. The admin adds two grok deployments, each with its own xai_oauth_token_file and order
  3. The client sends the same POST, and alice's account returns 403 spending-limit
  4. The proxy retries on bob's deployment, and the client gets a 200
  5. A caller who puts xai_oauth_token_file in the body, its litellm_params, or a fallback target gets a 401 "Rejected Request", so they can't pick another account

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Shared setup: a local proxy with no database, XAI_OAUTH_TOKEN_DIR pointed at an empty directory, and this config. allow_client_side_credentials is on to show that even the proxy-wide opt-in doesn't unlock the field

model_list:
  - model_name: grok
    litellm_params:
      model: xai/grok-4.7
      use_xai_oauth: true
      xai_oauth_token_file: auth-alice.json
general_settings:
  master_key: sk-pr40242-local
  allow_client_side_credentials: true

Before (d553123)

Token file in the request body

  1. curl -s http://localhost:4243/v1/chat/completions -H 'Authorization: Bearer sk-pr40242-local' -H 'Content-Type: application/json' -d '{"model":"grok","messages":[{"role":"user","content":"hi"}],"xai_oauth_token_file":"auth-bob.json"}'
  2. The request gets past the request-body check and goes to the xAI OAuth path: HTTP 401 "litellm.AuthenticationError: xAI OAuth login required. Run `litellm xai-oauth login`."

Token file in body litellm_params

  1. Same curl with "litellm_params":{"xai_oauth_token_file":"auth-bob.json"} in the body
  2. Not rejected: the request is routed and gets HTTP 429 all_deployments_in_cooldown from the previous failure

Token file in a fallback target

  1. Same curl with "fallbacks":[{"model":"grok","xai_oauth_token_file":"auth-bob.json"}] in the body
  2. Not rejected: HTTP 429 all_deployments_in_cooldown

After (9d9b6a7d5f)

Token file in the request body

  1. curl -s http://localhost:4242/v1/chat/completions -H 'Authorization: Bearer sk-pr40242-local' -H 'Content-Type: application/json' -d '{"model":"grok","messages":[{"role":"user","content":"hi"}],"xai_oauth_token_file":"auth-bob.json"}'
  2. HTTP 401 "Rejected Request: xai_oauth_token_file is a server-owned workload identity federation or OAuth token exchange parameter and cannot be set in a request body. A proxy admin configures it on the deployment or on a stored credential."

Token file in body litellm_params

  1. Same curl with "litellm_params":{"xai_oauth_token_file":"auth-bob.json"} in the body
  2. HTTP 401 with the same "Rejected Request: xai_oauth_token_file is a server-owned ..." message

Token file in a fallback target

  1. Same curl with "fallbacks":[{"model":"grok","xai_oauth_token_file":"auth-bob.json"}] in the body
  2. HTTP 401 with the same "Rejected Request: xai_oauth_token_file is a server-owned ..." message

A plain request with no override goes to the deployment's own auth-alice.json, which isn't in the empty token directory, so it returns HTTP 401 "xAI OAuth login required"

Type

🆕 New Feature

Caveats (if any)

Medium

  • No live failover run across two real SuperGrok accounts
    • The router test mocks xAI with respx and asserts that alice's token gets the 403 and bob's token serves the request

Low

  • The rejection message reuses the generic "workload identity federation or OAuth token exchange" wording

@HXhlx
HXhlx requested a review from a team September 8, 2026 11:25
@CLAassistant

CLAassistant commented Sep 8, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@codspeed

codspeed Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 1 benchmark is dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 35 untouched benchmarks


Comparing HXhlx:feat/xai-supergrok-oauth-failover (529b006) with main (ecdc0f9)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds per-deployment xAI OAuth credential files, named-account CLI login, and retryable handling for SuperGrok spending limits

  • Adds token-file selection to chat, Responses, router, and completion parameter paths
  • Adds named OAuth login files for multi-account deployments
  • Maps spending-limit responses to the retry and failover path
  • Leaves the token-file selector controllable by normal proxy request fields

Confidence Score: 3/5

This PR is not safe to merge until request-level OAuth file overrides are blocked and the explicit repository-rule violations are resolved

Normal proxy requests can replace an OAuth-enabled deployment’s credential path and cause upstream calls to execute under another readable local account

Files Needing Attention: litellm/llms/xai/oauth.py, litellm/litellm_core_utils/exception_mapping_utils.py, litellm/proxy/proxy_cli.py, tests/test_litellm/llms/xai/test_xai_oauth_multi_account.py

Security Review

Normal proxy callers can override an OAuth-enabled deployment’s credential-file path. Because the authenticator accepts arbitrary readable paths, callers can make requests under another locally stored xAI account

Important Files Changed

Filename Overview
litellm/llms/xai/oauth.py Adds explicit credential-file selection but does not constrain request-selected paths to the configured token directory
litellm/litellm_core_utils/exception_mapping_utils.py Adds xAI spending-limit handling to a shared mapper used by many providers
litellm/llms/xai/chat/transformation.py Consistently uses the selected OAuth file for chat authorization and API-base resolution
litellm/llms/xai/responses/transformation.py Propagates the selected OAuth file through Responses authorization and URL resolution
litellm/proxy/proxy_cli.py Adds named-account login but accepts unvalidated account strings when constructing credential paths
tests/test_litellm/llms/xai/test_xai_oauth_multi_account.py Covers multi-account behavior but replaces the production authenticator class rather than injecting a dependency

Reviews (1): Last reviewed commit: "feat(xai): support multi-account SuperGr..." | Re-trigger Greptile

Comment thread litellm/llms/xai/oauth.py Outdated
Comment on lines +133 to +134
if auth_file:
self.auth_file = auth_file if os.path.isabs(auth_file) else os.path.join(self.token_dir, auth_file)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 security OAuth File Override

Proxy fields override deployment credentials, and arbitrary readable paths are opened for authorization. How this was verified: Request fields win before file access.

Rule Used: What: Fail any PR which may contains a security in... (source)

Knowledge Base Used: Provider adapters and capabilities

Comment on lines +416 to +423
elif original_exception.status_code == 403 and "spending-limit" in error_str:
raise RateLimitError(
message=f"RateLimitError: {exception_provider} - {message}",
model=model,
llm_provider=custom_llm_provider,
response=getattr(original_exception, "response", None),
litellm_debug_info=extra_information,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Provider Logic Outside Adapter

This adds xAI-specific classification to shared exception mapping, violating the requirement that provider behavior stay under llms/. Fix this before merging.

Rule Used: What: Avoid writing provider-specific code outside... (source)

Knowledge Base Used: Fallbacks, retries, and failure handling

Comment thread litellm/proxy/proxy_cli.py Outdated
Comment on lines +1004 to +1009
account: Final = cli_args[2] if len(cli_args) >= 3 else None
token_dir: Final = get_secret_str("XAI_OAUTH_TOKEN_DIR") or os.path.expanduser(
"~/.config/litellm/xai_oauth"
)
authenticator: Final = (
XAIOAuthAuthenticator(auth_file=os.path.join(token_dir, f"auth-{account}.json"))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Unvalidated Account Path

Account names enter credential paths without validation. Names containing separators can make login fail after the OAuth callback completes.

Knowledge Base Used: Proxy configuration and deployment

def login(self):
return {"expires_at": 1234567890}

monkeypatch.setattr("litellm.llms.xai.oauth.XAIOAuthAuthenticator", FakeAuthenticator)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Authenticator Class Monkeypatch

This test replaces the authenticator class, violating the requirement to inject mocked dependencies. Fix this before merging.

Context Used: CLAUDE.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment thread litellm/llms/xai/chat/transformation.py Resolved
@veria-ai

veria-ai Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

@codecov

codecov Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@HXhlx
HXhlx force-pushed the feat/xai-supergrok-oauth-failover branch from 7780025 to 53b1255 Compare September 9, 2026 08:22
@yuneng-berri
yuneng-berri deleted the branch BerriAI:main September 13, 2026 04:50
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 14:39
@HXhlx
HXhlx force-pushed the feat/xai-supergrok-oauth-failover branch 2 times, most recently from 5cfaedb to 712cf29 Compare October 2, 2026 16:07
@HXhlx
HXhlx force-pushed the feat/xai-supergrok-oauth-failover branch from 7c6fff7 to 623f740 Compare October 5, 2026 10:55
@HXhlx
HXhlx force-pushed the feat/xai-supergrok-oauth-failover branch from 497ecff to 9d9b6a7 Compare October 15, 2026 12:32
@HXhlx

HXhlx commented Oct 15, 2026

Copy link
Copy Markdown
Author

@greptileai review

@greptile-apps

greptile-apps Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Automatic reviews are disabled for this repository.

@HXhlx
HXhlx force-pushed the feat/xai-supergrok-oauth-failover branch from 9d9b6a7 to 15cb9d4 Compare October 17, 2026 03:13
@HXhlx
HXhlx force-pushed the feat/xai-supergrok-oauth-failover branch from 15cb9d4 to 529b006 Compare October 24, 2026 04:02
HXhlx and others added 9 commits October 31, 2026 12:09
Add per-deployment xai_oauth_token_file so multiple SuperGrok accounts
can share one proxy. Map xAI 403 spending-limit to RateLimitError so the
router can fail over to another deployment

Co-authored-by: HX <HXhlx@users.noreply.github.com>
… client-side opt-ins

The token file picks which OAuth account stored on the proxy host signs the
request, so allow_client_side_credentials and configurable_clientside_auth_params
must not hand it to callers. Only deployment config may set it
…n file handling

Move the spending-limit to rate-limit mapping out of the shared exception mapper
into XAIChatConfig and XAIResponsesAPIConfig get_error_class. Keep the operator's
XAI_OAUTH_AUTH_FILE behaviour, reject symlinks that escape the token dir, report a
usage error for unsafe CLI account names, and cover per-account router failover
Adding xai_oauth_token_file to GenericLiteLLMParams adds one unknown
argument at every GenericLiteLLMParams(**kwargs) call site. Building the
params in responses() with model_validate, which behaves the same for a
model without a custom __init__, keeps the basedpyright total below base.
HXhlx added 6 commits October 31, 2026 12:18
Route the token file through the shared server-owned gate so it is refused in
body litellm_params, stored key/team fallback targets and health check params,
and so only proxy admins can set it on a deployment. Drops the parallel
operator-only check this replaces
@HXhlx
HXhlx force-pushed the feat/xai-supergrok-oauth-failover branch from 529b006 to e4942c2 Compare October 31, 2026 04:51
@HXhlx

HXhlx commented Oct 31, 2026

Copy link
Copy Markdown
Author

@ryan-crabbe-berri @mateo-berri @joshua-berri @kerry-berri @klu-berri rebased onto main today, CI green, would appreciate a review when you get a chance

@HXhlx

HXhlx commented Nov 2, 2026

Copy link
Copy Markdown
Author

@ryan-crabbe-berri @mateo-berri @joshua-berri @kerry-berri @klu-berri all five PRs are rebased onto main and merge clean, CI awaits a workflow approval, reviews welcome when you get a chance

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants