Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,11 @@
`LITELLM_HEADERS` or provider headers to the IdP, uses `redirect: "manual"` with any 3xx a failure, and reports only
an OAuth error code matching `^[a-z_]{1,64}$` or an HTTP status. Its refresh branch must stay ahead of the `!command`
fallthrough so an IdP refresh token is never executed. The proxy, not Pi, verifies the id_token signature.
- `oidc.deviceCode: true` swaps the loopback redirect for the RFC 8628 device grant (same `oidc_pkce` credential and
refresh). It stays settings-only and off by default because a device code can be phished: never offer it at the
login prompt, never fall back to it, and never show `verification_uri_complete`. The IdP's `interval` is a minimum
wait with no upper bound, so honor a larger one instead of polling faster, and every transient failure doubles the
wait, which covers the connection timeout RFC 8628 requires to slow polling. The Go port mirrors both.
- Google ADC is resolved in process through `src/gcloud-token.ts`; there is no helper subprocess and no `src/gcloud-token-cli.ts`. Only `authorized_user` credentials are supported, and service accounts warn and fail closed.
- `apiKey.check` performs no network call, so it reports credential shape, not mintability. Its source label must mirror the precedence in `resolveCredentials`, so ADC is named whenever a complete ADC file exists; if the refresh token no longer mints, `resolve` falls back and reports the credential it actually used.

Expand Down
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ Prerequisites:

- The proxy's JWT auth trusts the IdP's issuer and accepts the client ID as an audience.
- The IdP has a public client (no client secret) registered for authorization code + PKCE with the loopback redirect `http://127.0.0.1:<port>/callback`.
- The browser runs on the same machine as Pi.
- The browser runs on the same machine as Pi, unless you turn on `deviceCode` (see [Device code login](#device-code-login)).

To sign in without configuring anything, choose `Your identity provider (OIDC client ID)…` after confirming the proxy URL, then enter the issuer URL, the client ID, and the scopes (blank for `openid`). Pi checks them like the settings below and stores them with the credential, so the next login to the same proxy offers the same identity provider first. The login prompt does not ask for `redirectPorts`; an IdP that only accepts exact pre-registered redirect URIs needs the setting.

Expand All @@ -137,11 +137,18 @@ To skip that prompt, configure the default `litellm` provider in the global `~/.
- `clientId` (required): the public client's ID.
- `scope` (default `"openid"`): must include `openid`.
- `redirectPorts` (optional): ports tried in order, for IdPs that only accept exact pre-registered redirect URIs. Without it the OS assigns a free port.
- `deviceCode` (default `false`): sign in with a device code instead of the loopback redirect; see [Device code login](#device-code-login).

With `oidc` set, `Sign in with LiteLLM SSO` confirms the proxy URL and then runs only this flow. Either way, Pi reads `<issuer>/.well-known/openid-configuration`, opens the IdP's authorization page, and exchanges the code for tokens. Login sends nothing to the proxy, and IdP requests never carry `LITELLM_HEADERS` or provider `headers`. An invalid `oidc` setting or entered value fails login with a message naming the field; it never falls back to the LiteLLM flows.

The `id_token` is the bearer token. Pi checks its issuer, audience, authorized party (when present), subject, expiry, and nonce but not its signature; the proxy verifies the signature against the IdP's keys. Pi refreshes it with the refresh token, so the IdP must return a new `id_token` from the refresh grant. Some IdPs only issue a refresh token when the scope includes `offline_access`; without one, run `/login litellm` again when the `id_token` expires.

###### Device code login

Over SSH, in a devcontainer, or on any machine without a browser, the loopback redirect cannot reach Pi. Set `"deviceCode": true` in the `oidc` setting to use the OAuth device authorization grant ([RFC 8628](https://www.rfc-editor.org/rfc/rfc8628)) instead: Pi shows a code and the IdP's verification URL, you approve the code in a browser on any device, and Pi polls the IdP for the tokens. The IdP must list a `device_authorization_endpoint` in its discovery document and allow the grant for the client (in Keycloak, the client's `OAuth 2.0 Device Authorization Grant` capability).

It is off by default, and the login prompt does not offer it, because a device code is easier to phish: anyone can start a login and send you its code, and approving it signs them in as you. Turn it on only where the loopback flow cannot work, and approve only a code that your own Pi is showing. Pi shows the IdP's plain verification URL, never the one with the code filled in, so you always compare the code yourself. The request carries a PKCE challenge, which Keycloak can require of public clients and other IdPs ignore. The `id_token` checks are the same, except the nonce, which this grant does not have.

Pi never derives the IdP from the proxy: LiteLLM's own `/.well-known/openid-configuration`, `oauth-authorization-server`, and `oauth-protected-resource` documents describe LiteLLM's authorization server, not the IdP that signs the JWTs it accepts. Zero-config IdP discovery from the proxy via RFC 9728 is out of scope until LiteLLM publishes it ([BerriAI/litellm#41135](https://github.com/BerriAI/litellm/issues/41135)).

### Option B — environment variables
Expand Down
140 changes: 121 additions & 19 deletions pig/extensions/litellm/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,7 @@ func loginAPIKey(ctx context.Context, interaction ai.AuthInteraction, definition
type tokenFailure struct {
transient bool
message string
code string // the OAuth error code of a rejected request, which the device flow polls on
}

// postTokenForm POSTs a token form without following redirects; each flow validates its own success fields.
Expand All @@ -416,20 +417,21 @@ func postTokenForm(ctx context.Context, endpoint string, form url.Values, header
response, err := doAuth(ctx, http.MethodPost, endpoint, authRequestHeaders(headers, "application/x-www-form-urlencoded"), []byte(form.Encode()))
if err != nil {
if errors.Is(err, errAuthNetwork) {
return nil, &tokenFailure{true, label + " token exchange failed (network error)"}, nil
return nil, &tokenFailure{transient: true, message: label + " token exchange failed (network error)"}, nil
}
return nil, nil, err
}
if response.bodyErr != nil && response.ok() {
return nil, &tokenFailure{true, label + " token exchange failed (network error)"}, nil
return nil, &tokenFailure{transient: true, message: label + " token exchange failed (network error)"}, nil
}
data := response.object()
if !response.ok() {
message := fmt.Sprintf("%s token exchange failed (HTTP %d)", label, response.status)
if code := oauthErrorCode(data["error"]); code != "" {
code := oauthErrorCode(data["error"])
if code != "" {
message = fmt.Sprintf("%s token exchange rejected (%s)", label, code)
}
return nil, &tokenFailure{response.status == http.StatusTooManyRequests || response.status >= 500, message}, nil
return nil, &tokenFailure{response.status == http.StatusTooManyRequests || response.status >= 500, message, code}, nil
}
if data == nil {
data = map[string]any{}
Expand All @@ -453,7 +455,7 @@ func requestPkceToken(ctx context.Context, endpoint string, form url.Values, hea
if err != nil || failure != nil {
return nil, failure, err
}
invalid := &tokenFailure{false, "LiteLLM token exchange returned an invalid response"}
invalid := &tokenFailure{message: "LiteLLM token exchange returned an invalid response"}
expiresIn, hasLifetime := data["expires_in"].(float64)
if !hasLifetime || math.IsNaN(expiresIn) || math.IsInf(expiresIn, 0) || expiresIn <= 0 {
return nil, invalid, nil
Expand Down Expand Up @@ -758,9 +760,16 @@ func authorizationURL(endpoint string, params map[string]string) (string, error)
type oidcConfig struct {
issuer, clientID, scope string
redirectPorts []int
deviceCode bool
}

type oidcDiscovery struct{ issuer, authorizationEndpoint, tokenEndpoint string }
// deviceAuthorizationEndpoint is empty when the IdP advertises none.
type oidcDiscovery struct {
issuer, authorizationEndpoint, tokenEndpoint, deviceAuthorizationEndpoint string
}

// oidcDeviceSecond is the unit of the device flow's poll interval; tests shorten it.
var oidcDeviceSecond = time.Second

func parseOidcConfig(raw any) (oidcConfig, error) {
invalid := func(field, expected string) error {
Expand Down Expand Up @@ -799,7 +808,15 @@ func parseOidcConfig(raw any) (oidcConfig, error) {
ports = append(ports, int(port))
}
}
return oidcConfig{issuer: issuer, clientID: object["clientId"].(string), scope: scope, redirectPorts: ports}, nil
deviceCode := false
if value := object["deviceCode"]; value != nil {
flag, isBool := value.(bool)
if !isBool {
return oidcConfig{}, invalid("oidc.deviceCode", "true or false")
}
deviceCode = flag
}
return oidcConfig{issuer: issuer, clientID: object["clientId"].(string), scope: scope, redirectPorts: ports, deviceCode: deviceCode}, nil
}

func contains(items []string, want string) bool {
Expand Down Expand Up @@ -844,7 +861,8 @@ func discoverOidc(ctx context.Context, issuer string) (*oidcDiscovery, error) {
if !ok {
return nil, errors.New("OIDC discovery has invalid token_endpoint")
}
return &oidcDiscovery{issuer: advertised, authorizationEndpoint: authorizationEndpoint, tokenEndpoint: tokenEndpoint}, nil
deviceEndpoint, _ := httpsURL(data["device_authorization_endpoint"], true)
return &oidcDiscovery{issuer: advertised, authorizationEndpoint: authorizationEndpoint, tokenEndpoint: tokenEndpoint, deviceAuthorizationEndpoint: deviceEndpoint}, nil
}

type oidcToken struct {
Expand Down Expand Up @@ -873,10 +891,10 @@ func requestOidcToken(ctx context.Context, endpoint string, form url.Values, exp
claims = jwtClaims(idToken)
}
if claims == nil {
return nil, &tokenFailure{false, "OIDC token response has no valid id_token"}, nil
return nil, &tokenFailure{message: "OIDC token response has no valid id_token"}, nil
}
invalid := func(claim string) (*oidcToken, *tokenFailure, error) {
return nil, &tokenFailure{false, "OIDC id_token has invalid " + claim}, nil
return nil, &tokenFailure{message: "OIDC id_token has invalid " + claim}, nil
}
if issuer, ok := claims["iss"].(string); !ok || issuer != expected.issuer {
return invalid("iss")
Expand Down Expand Up @@ -922,11 +940,103 @@ func requestOidcToken(ctx context.Context, endpoint string, form url.Values, exp
return &oidcToken{access: idToken, refresh: refresh, expires: int64(expiresAt), subject: subject}, nil, nil
}

func oidcCredential(token *oidcToken, baseURL string, config oidcConfig, discovery *oidcDiscovery) ai.Credential {
credential := newOAuthCredential(token.access, token.refresh, float64(token.expires), baseURL)
setExtra(&credential, "flow", oidcFlow)
setExtra(&credential, "issuer", discovery.issuer)
setExtra(&credential, "clientId", config.clientID)
setExtra(&credential, "tokenEndpoint", discovery.tokenEndpoint)
setExtra(&credential, "subject", token.subject)
// ai.Credential has its own scope field: PiG would move an Extra "scope" there on the next load.
credential.Scope = config.scope
return credential
}

var oidcUserCode = regexp.MustCompile(`^[\w-]{1,64}$`)

// loginOidcDevice is RFC 8628 device authorization, only under `oidc.deviceCode: true`: the code can be approved
// from any browser, so a code someone else started can be phished, which the loopback flow rules out. The PKCE
// pair is the extension Keycloak can require of public clients; an IdP that does not know it ignores both parameters.
func loginOidcDevice(ctx context.Context, interaction ai.AuthInteraction, baseURL string, config oidcConfig, discovery *oidcDiscovery) (ai.Credential, error) {
if discovery.deviceAuthorizationEndpoint == "" {
return ai.Credential{}, errors.New("OIDC discovery has no device_authorization_endpoint; remove oidc.deviceCode to sign in")
}
verifier := randomToken()
start, failure, err := postTokenForm(ctx, discovery.deviceAuthorizationEndpoint, url.Values{
"client_id": {config.clientID},
"scope": {config.scope},
"code_challenge": {pkceChallenge(verifier)},
"code_challenge_method": {"S256"},
}, nil, "OIDC")
if err != nil {
return ai.Credential{}, err
}
if failure != nil {
if failure.code != "" {
return ai.Credential{}, fmt.Errorf("OIDC device authorization rejected (%s)", failure.code)
}
return ai.Credential{}, errors.New("OIDC device authorization failed")
}
deviceCode, _ := start["device_code"].(string)
userCode, _ := start["user_code"].(string)
// Only verification_uri is shown: verification_uri_complete would skip the step where the user compares the code.
verificationURI, okURI := httpsURL(start["verification_uri"], true)
expiresIn, okExpiry := positiveNumber(start["expires_in"])
if !isAuthToken(start["device_code"]) || !oidcUserCode.MatchString(userCode) || !okURI || !okExpiry {
return ai.Credential{}, errors.New("OIDC device authorization returned an invalid response")
}
notifyAuth(interaction, ai.AuthDeviceCodeEvent{UserCode: userCode, VerificationURI: verificationURI, ExpiresInSeconds: &expiresIn})
seconds := 5.0
// RFC 8628 treats `interval` as a minimum wait with no upper bound, so a larger one is honored rather
// than replaced by a faster default. One past the deadline simply expires the login below.
if interval, ok := start["interval"].(float64); ok && interval >= 1 {
seconds = interval
}
deadline := now().Add(time.Duration(expiresIn * float64(time.Second)))
for {
wait := time.Duration(seconds * float64(oidcDeviceSecond))
if !now().Add(wait).Before(deadline) {
return ai.Credential{}, errors.New("OIDC device login expired")
}
timer := time.NewTimer(wait)
select {
case <-timer.C:
case <-ctx.Done():
timer.Stop()
return ai.Credential{}, context.Cause(ctx)
}
token, failure, err := requestOidcToken(ctx, discovery.tokenEndpoint, url.Values{
"grant_type": {"urn:ietf:params:oauth:grant-type:device_code"},
"device_code": {deviceCode},
"client_id": {config.clientID},
"code_verifier": {verifier},
}, expectedIDToken{issuer: discovery.issuer, clientID: config.clientID}, "")
if err != nil {
return ai.Credential{}, err
}
if failure == nil {
return oidcCredential(token, baseURL, config, discovery), nil
}
if failure.code == "slow_down" {
seconds += 5
} else if failure.transient {
// RFC 8628 requires polling to slow down after a connection timeout, with exponential backoff
// recommended. Every transient failure here is a request that did not complete, so all back off.
seconds *= 2
} else if failure.code != "authorization_pending" {
return ai.Credential{}, errors.New(failure.message)
}
}
}

func loginOidc(ctx context.Context, interaction ai.AuthInteraction, baseURL string, config oidcConfig) (ai.Credential, error) {
discovery, err := discoverOidc(ctx, config.issuer)
if err != nil {
return ai.Credential{}, err
}
if config.deviceCode {
return loginOidcDevice(ctx, interaction, baseURL, config, discovery)
}
verifier, nonce := randomToken(), randomToken()
return withLoopbackCallback(ctx, "OIDC", config.redirectPorts, func(callback loopbackCallback) (ai.Credential, error) {
authorizationURL, err := authorizationURL(discovery.authorizationEndpoint, map[string]string{
Expand Down Expand Up @@ -960,15 +1070,7 @@ func loginOidc(ctx context.Context, interaction ai.AuthInteraction, baseURL stri
if failure != nil {
return ai.Credential{}, errors.New(failure.message)
}
credential := newOAuthCredential(token.access, token.refresh, float64(token.expires), baseURL)
setExtra(&credential, "flow", oidcFlow)
setExtra(&credential, "issuer", discovery.issuer)
setExtra(&credential, "clientId", config.clientID)
setExtra(&credential, "tokenEndpoint", discovery.tokenEndpoint)
setExtra(&credential, "subject", token.subject)
// ai.Credential has its own scope field: PiG would move an Extra "scope" there on the next load.
credential.Scope = config.scope
return credential, nil
return oidcCredential(token, baseURL, config, discovery), nil
})
}

Expand Down
Loading