mirror of https://github.com/tailscale/tailscale/
cmd/tailscale/cli,feature: add support for identity federation (#17529)
Add new arguments to `tailscale up` so authkeys can be generated dynamically via identity federation. Updates #9192 Signed-off-by: mcoulombe <max@tailscale.com>bradfitz/test
parent
54cee33bae
commit
6a73c0bdf5
@ -0,0 +1,13 @@
|
||||
// Copyright (c) Tailscale Inc & AUTHORS
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
// Code generated by gen.go; DO NOT EDIT.
|
||||
|
||||
//go:build ts_omit_identity_federation
|
||||
|
||||
package buildfeatures
|
||||
|
||||
// HasIdentityFederation is whether the binary was built with support for modular feature "Identity token exchange for auth key support".
|
||||
// Specifically, it's whether the binary was NOT built with the "ts_omit_identity_federation" build tag.
|
||||
// It's a const so it can be used for dead code elimination.
|
||||
const HasIdentityFederation = false
|
||||
@ -0,0 +1,13 @@
|
||||
// Copyright (c) Tailscale Inc & AUTHORS
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
// Code generated by gen.go; DO NOT EDIT.
|
||||
|
||||
//go:build !ts_omit_identity_federation
|
||||
|
||||
package buildfeatures
|
||||
|
||||
// HasIdentityFederation is whether the binary was built with support for modular feature "Identity token exchange for auth key support".
|
||||
// Specifically, it's whether the binary was NOT built with the "ts_omit_identity_federation" build tag.
|
||||
// It's a const so it can be used for dead code elimination.
|
||||
const HasIdentityFederation = true
|
||||
@ -0,0 +1,7 @@
|
||||
// Copyright (c) Tailscale Inc & AUTHORS
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
// Package identityfederation registers support for authkey resolution
|
||||
// via identity federation if it's not disabled by the
|
||||
// ts_omit_identityfederation build tag.
|
||||
package identityfederation
|
||||
@ -0,0 +1,8 @@
|
||||
// Copyright (c) Tailscale Inc & AUTHORS
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
//go:build !ts_omit_identityfederation
|
||||
|
||||
package identityfederation
|
||||
|
||||
import _ "tailscale.com/feature/identityfederation"
|
||||
@ -0,0 +1,127 @@
|
||||
// Copyright (c) Tailscale Inc & AUTHORS
|
||||
// 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"
|
||||
)
|
||||
|
||||
func init() {
|
||||
feature.Register("identityfederation")
|
||||
tailscale.HookResolveAuthKeyViaWIF.Set(resolveAuthKey)
|
||||
}
|
||||
|
||||
// resolveAuthKey uses OIDC identity federation to exchange the provided ID token and client ID for an authkey.
|
||||
func resolveAuthKey(ctx context.Context, baseURL, clientID, idToken string, tags []string) (string, error) {
|
||||
if clientID == "" {
|
||||
return "", nil // Short-circuit, no client ID means not using identity federation
|
||||
}
|
||||
|
||||
if idToken == "" {
|
||||
return "", errors.New("federated identity authkeys require --id-token")
|
||||
}
|
||||
if len(tags) == 0 {
|
||||
return "", errors.New("federated identity authkeys require --advertise-tags")
|
||||
}
|
||||
if baseURL == "" {
|
||||
baseURL = ipn.DefaultControlURL
|
||||
}
|
||||
|
||||
ephemeral, preauth, err := parseOptionalAttributes(clientID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to parse optional config attributes: %w", err)
|
||||
}
|
||||
|
||||
accessToken, err := exchangeJWTForToken(ctx, baseURL, clientID, 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 = baseURL
|
||||
|
||||
authkey, _, err := tsClient.CreateKey(ctx, tailscale.KeyCapabilities{
|
||||
Devices: tailscale.KeyDeviceCapabilities{
|
||||
Create: tailscale.KeyDeviceCreateCapabilities{
|
||||
Reusable: false,
|
||||
Ephemeral: ephemeral,
|
||||
Preauthorized: preauth,
|
||||
Tags: 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) (ephemeral bool, preauthorized bool, err error) {
|
||||
_, attrs, found := strings.Cut(clientID, "?")
|
||||
if !found {
|
||||
return 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)
|
||||
}
|
||||
}
|
||||
|
||||
return ephemeral, preauthorized, err
|
||||
}
|
||||
|
||||
// exchangeJWTForToken exchanges a JWT for a Tailscale access token.
|
||||
func exchangeJWTForToken(ctx context.Context, baseURL, clientID, idToken string) (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", baseURL),
|
||||
},
|
||||
}).Exchange(ctx, "", oauth2.SetAuthURLParam("client_id", clientID), oauth2.SetAuthURLParam("jwt", idToken))
|
||||
if err != nil {
|
||||
// Try to extract more detailed error message
|
||||
var retrieveErr *oauth2.RetrieveError
|
||||
if errors.As(err, &retrieveErr) {
|
||||
return "", fmt.Errorf("token exchange failed with status %d: %s", retrieveErr.Response.StatusCode, string(retrieveErr.Body))
|
||||
}
|
||||
return "", fmt.Errorf("unexpected token exchange request error: %w", err)
|
||||
}
|
||||
|
||||
return token.AccessToken, nil
|
||||
}
|
||||
@ -0,0 +1,167 @@
|
||||
// Copyright (c) Tailscale Inc & AUTHORS
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
package identityfederation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestResolveAuthKey(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
clientID string
|
||||
idToken string
|
||||
tags []string
|
||||
wantAuthKey string
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "success",
|
||||
clientID: "client-123",
|
||||
idToken: "token",
|
||||
tags: []string{"tag:test"},
|
||||
wantAuthKey: "tskey-auth-xyz",
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "missing client id short-circuits without error",
|
||||
clientID: "",
|
||||
idToken: "token",
|
||||
tags: []string{"tag:test"},
|
||||
wantAuthKey: "",
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "missing id token",
|
||||
clientID: "client-123",
|
||||
idToken: "",
|
||||
tags: []string{"tag:test"},
|
||||
wantErr: "federated identity authkeys require --id-token",
|
||||
},
|
||||
{
|
||||
name: "missing tags",
|
||||
clientID: "client-123",
|
||||
idToken: "token",
|
||||
tags: []string{},
|
||||
wantErr: "federated identity authkeys require --advertise-tags",
|
||||
},
|
||||
{
|
||||
name: "invalid client id attributes",
|
||||
clientID: "client-123?invalid=value",
|
||||
idToken: "token",
|
||||
tags: []string{"tag:test"},
|
||||
wantErr: `failed to parse optional config attributes: unknown optional config attribute "invalid"`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv := mockedControlServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
authKey, err := resolveAuthKey(context.Background(), srv.URL, tt.clientID, tt.idToken, tt.tags)
|
||||
if tt.wantErr != "" {
|
||||
if err == nil {
|
||||
t.Errorf("resolveAuthKey() error = nil, want %q", tt.wantErr)
|
||||
return
|
||||
}
|
||||
if err.Error() != tt.wantErr {
|
||||
t.Errorf("resolveAuthKey() error = %q, want %q", err.Error(), tt.wantErr)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Fatalf("resolveAuthKey() unexpected error = %v", err)
|
||||
}
|
||||
if authKey != tt.wantAuthKey {
|
||||
t.Errorf("resolveAuthKey() = %q, want %q", authKey, tt.wantAuthKey)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseOptionalAttributes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
clientID string
|
||||
wantEphemeral bool
|
||||
wantPreauth bool
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "default values",
|
||||
clientID: "client-123",
|
||||
wantEphemeral: true,
|
||||
wantPreauth: false,
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "custom values",
|
||||
clientID: "client-123?ephemeral=false&preauthorized=true",
|
||||
wantEphemeral: false,
|
||||
wantPreauth: true,
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "unknown attribute",
|
||||
clientID: "client-123?unknown=value",
|
||||
wantEphemeral: false,
|
||||
wantPreauth: false,
|
||||
wantErr: `unknown optional config attribute "unknown"`,
|
||||
},
|
||||
{
|
||||
name: "invalid value",
|
||||
clientID: "client-123?ephemeral=invalid",
|
||||
wantEphemeral: false,
|
||||
wantPreauth: false,
|
||||
wantErr: `strconv.ParseBool: parsing "invalid": invalid syntax`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ephemeral, preauth, err := parseOptionalAttributes(tt.clientID)
|
||||
if tt.wantErr != "" {
|
||||
if err == nil {
|
||||
t.Errorf("parseOptionalAttributes() error = nil, want %q", tt.wantErr)
|
||||
return
|
||||
}
|
||||
if err.Error() != tt.wantErr {
|
||||
t.Errorf("parseOptionalAttributes() error = %q, want %q", err.Error(), tt.wantErr)
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Errorf("parseOptionalAttributes() error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if ephemeral != tt.wantEphemeral {
|
||||
t.Errorf("parseOptionalAttributes() ephemeral = %v, want %v", ephemeral, tt.wantEphemeral)
|
||||
}
|
||||
if preauth != tt.wantPreauth {
|
||||
t.Errorf("parseOptionalAttributes() preauth = %v, want %v", preauth, tt.wantPreauth)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func mockedControlServer(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case strings.Contains(r.URL.Path, "/oauth/token-exchange"):
|
||||
// OAuth2 library sends the token exchange request
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"access_token":"access-123","token_type":"Bearer","expires_in":3600}`))
|
||||
case strings.Contains(r.URL.Path, "/api/v2/tailnet") && strings.Contains(r.URL.Path, "/keys"):
|
||||
// Tailscale client creates the authkey
|
||||
w.Write([]byte(`{"key":"tskey-auth-xyz","created":"2024-01-01T00:00:00Z"}`))
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
// Copyright (c) Tailscale Inc & AUTHORS
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
package tailscale
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"tailscale.com/feature"
|
||||
)
|
||||
|
||||
// HookResolveAuthKeyViaWIF resolves to [identityfederation.ResolveAuthKey] when the
|
||||
// corresponding feature tag is enabled in the build process.
|
||||
//
|
||||
// baseURL is the URL of the control server used for token exchange and authkey generation.
|
||||
// clientID is the federated client ID used for token exchange, the format is <tailnet ID>/<oauth client ID>
|
||||
// idToken is the Identity token from the identity provider
|
||||
// tags is the list of tags to be associated with the auth key
|
||||
var HookResolveAuthKeyViaWIF feature.Hook[func(ctx context.Context, baseURL, clientID, idToken string, tags []string) (string, error)]
|
||||
Loading…
Reference in New Issue