Files
tailscale/feature/identityfederation/identityfederation.go
Mario Minardi ed75aa3c1f various: add auth-exchange-attempts flag to up
Add an optional auth-exchange-attempts flag to up that allows for
controlling the number of attempts made on transient errors (e.g, 5XX or
client-side deadline exceeded errors) during OAuth or workload identity
federation auth exchange operations.

This defaults to 1 (e.g., no retries). Specifying a larger number of
attempts enables retrying the auth exchange with exponential backoff
instead of the default of failing after a single try.

Updates https://github.com/tailscale/tailscale/issues/20339

Signed-off-by: Mario Minardi <[email protected]>
2026-11-18 15:15:43 -07:00

159 lines
4.7 KiB
Go

// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
// Package identityfederation registers support for using ID tokens to
// automatically request authkeys for logging in.
package identityfederation
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"golang.org/x/oauth2"
"tailscale.com/feature"
"tailscale.com/internal/client/tailscale"
"tailscale.com/ipn"
"tailscale.com/util/authretry"
"tailscale.com/wif"
)
func init() {
if !feature.Register("identityfederation") {
return
}
tailscale.HookResolveAuthKeyViaWIF.Set(resolveAuthKey)
tailscale.HookExchangeJWTForTokenViaWIF.Set(exchangeJWTForToken)
}
// resolveAuthKey uses OIDC identity federation to exchange the provided ID token and client ID for an authkey.
func resolveAuthKey(ctx context.Context, args tailscale.ResolveAuthKeyWIFArgs) (string, error) {
if args.ClientID == "" {
return "", nil // Short-circuit, no client ID means not using identity federation
}
if args.IDToken == "" {
if args.Audience == "" {
return "", errors.New("federated identity requires either an ID token or an audience")
}
providerIdToken, err := wif.ObtainProviderToken(ctx, args.Audience)
if err != nil {
return "", errors.New("federated identity authkeys require --id-token")
}
args.IDToken = providerIdToken
}
if len(args.Tags) == 0 {
return "", errors.New("federated identity authkeys require --advertise-tags")
}
if args.BaseURL == "" {
args.BaseURL = ipn.DefaultControlURL
}
strippedID, ephemeral, preauth, err := parseOptionalAttributes(args.ClientID)
if err != nil {
return "", fmt.Errorf("failed to parse optional config attributes: %w", err)
}
accessToken, err := authretry.RetryOnTransientFailure(ctx, "exchange-jwt", args.AuthExchangeAttempts, func() (string, error) {
return exchangeJWTForToken(ctx, tailscale.ExchangeJWTForTokenWIFArgs{
BaseURL: args.BaseURL,
ClientID: strippedID,
IDToken: args.IDToken,
})
})
if err != nil {
return "", fmt.Errorf("failed to exchange JWT for access token: %w", err)
}
if accessToken == "" {
return "", errors.New("received empty access token from Tailscale")
}
tsClient := tailscale.NewClient("-", tailscale.APIKey(accessToken))
tsClient.UserAgent = "tailscale-cli-identity-federation"
tsClient.BaseURL = args.BaseURL
authkey, _, err := tsClient.CreateKey(ctx, tailscale.KeyCapabilities{
Devices: tailscale.KeyDeviceCapabilities{
Create: tailscale.KeyDeviceCreateCapabilities{
Reusable: false,
Ephemeral: ephemeral,
Preauthorized: preauth,
Tags: args.Tags,
},
},
})
if err != nil {
return "", fmt.Errorf("unexpected error while creating authkey: %w", err)
}
if authkey == "" {
return "", errors.New("received empty authkey from control server")
}
return authkey, nil
}
func parseOptionalAttributes(clientID string) (strippedID string, ephemeral bool, preauthorized bool, err error) {
strippedID, attrs, found := strings.Cut(clientID, "?")
if !found {
return clientID, true, false, nil
}
parsed, err := url.ParseQuery(attrs)
if err != nil {
return "", false, false, fmt.Errorf("failed to parse optional config attributes: %w", err)
}
for k := range parsed {
switch k {
case "ephemeral":
ephemeral, err = strconv.ParseBool(parsed.Get(k))
case "preauthorized":
preauthorized, err = strconv.ParseBool(parsed.Get(k))
default:
return "", false, false, fmt.Errorf("unknown optional config attribute %q", k)
}
}
if err != nil {
return "", false, false, err
}
return strippedID, ephemeral, preauthorized, nil
}
// exchangeJWTForToken exchanges a JWT for a Tailscale access token.
func exchangeJWTForToken(ctx context.Context, args tailscale.ExchangeJWTForTokenWIFArgs) (string, error) {
httpClient := &http.Client{Timeout: 10 * time.Second}
ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient)
token, err := (&oauth2.Config{
Endpoint: oauth2.Endpoint{
TokenURL: fmt.Sprintf("%s/api/v2/oauth/token-exchange", args.BaseURL),
AuthStyle: oauth2.AuthStyleInParams,
},
}).Exchange(ctx, "", oauth2.SetAuthURLParam("client_id", args.ClientID), oauth2.SetAuthURLParam("jwt", args.IDToken))
if err != nil {
// Try to extract more detailed error message
if retrieveErr, ok := errors.AsType[*oauth2.RetrieveError](err); ok {
return "", exchangeError{retrieveErr}
}
return "", fmt.Errorf("unexpected token exchange request error: %w", err)
}
return token.AccessToken, nil
}
type exchangeError struct {
err *oauth2.RetrieveError
}
func (e exchangeError) Error() string {
return fmt.Sprintf("token exchange failed with status %d: %s", e.err.Response.StatusCode, e.err.Body)
}
func (e exchangeError) Unwrap() error { return e.err }