Skip to content

Support Client Credentials Flow #1231

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
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
13 changes: 12 additions & 1 deletion docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ Flags:
--open-url-after-authentication string [authcode] If set, open the URL in the browser after authentication
--oidc-redirect-url-hostname string [authcode] Hostname of the redirect URL (default "localhost")
--oidc-redirect-url-authcode-keyboard string [authcode-keyboard] Redirect URL (default "urn:ietf:wg:oauth:2.0:oob")
--oidc-auth-request-extra-params stringToString [authcode, authcode-keyboard] Extra query parameters to send with an authentication request (default [])
--oidc-auth-request-extra-params stringToString [authcode, authcode-keyboard, client-credentials] Extra query parameters to send with an authentication request (default [])
--username string [password] Username for resource owner password credentials grant
--password string [password] Password for resource owner password credentials grant
-h, --help help for get-token
Expand Down Expand Up @@ -141,6 +141,7 @@ Kubelogin support the following flows:
- [Authorization code flow with a keyboard](#authorization-code-flow-with-a-keyboard)
- [Device authorization grant](#device-authorization-grant)
- [Resource owner password credentials grant](#resource-owner-password-credentials-grant)
- [Client Credentials flow](#client-credentials-flow)

### Authorization code flow

Expand Down Expand Up @@ -283,6 +284,16 @@ Username: foo
Password:
```

### Client Credentials Flow

Kubelogin performs the [OAuth 2.0 client credentials flow](https://datatracker.ietf.org/doc/html/rfc6749#section-1.3.4) when `--grant-type=client-credentials` is set.

```yaml
- --grant-type=client-credentials
```

Per specification, this flow only returns authorization tokens.

## Run in Docker

You can run [the Docker image](https://ghcr.io/int128/kubelogin) instead of the binary.
Expand Down
57 changes: 57 additions & 0 deletions mocks/github.com/int128/kubelogin/pkg/oidc/client_mock/mocks.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 11 additions & 1 deletion pkg/cmd/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import (
"strings"
"time"

"github.com/spf13/pflag"

"github.com/int128/kubelogin/pkg/oidc/client"
"github.com/int128/kubelogin/pkg/usecases/authentication"
"github.com/int128/kubelogin/pkg/usecases/authentication/authcode"
"github.com/int128/kubelogin/pkg/usecases/authentication/devicecode"
"github.com/int128/kubelogin/pkg/usecases/authentication/ropc"
"github.com/spf13/pflag"
)

const oobRedirectURI = "urn:ietf:wg:oauth:2.0:oob"
Expand All @@ -36,6 +38,7 @@ var allGrantType = strings.Join([]string{
"authcode-keyboard",
"password",
"device-code",
"client-credentials",
}, "|")

func (o *authenticationOptions) addFlags(f *pflag.FlagSet) {
Expand All @@ -52,6 +55,7 @@ func (o *authenticationOptions) addFlags(f *pflag.FlagSet) {
f.StringToStringVar(&o.AuthRequestExtraParams, "oidc-auth-request-extra-params", nil, "[authcode, authcode-keyboard] Extra query parameters to send with an authentication request")
f.StringVar(&o.Username, "username", "", "[password] Username for resource owner password credentials grant")
f.StringVar(&o.Password, "password", "", "[password] Password for resource owner password credentials grant")

}

func (o *authenticationOptions) expandHomedir() {
Expand Down Expand Up @@ -88,6 +92,12 @@ func (o *authenticationOptions) grantOptionSet() (s authentication.GrantOptionSe
SkipOpenBrowser: o.SkipOpenBrowser,
BrowserCommand: o.BrowserCommand,
}
case o.GrantType == "client-credentials":
endpointparams := make(map[string][]string, len(o.AuthRequestExtraParams))
for k, v := range o.AuthRequestExtraParams {
endpointparams[k] = []string{v}
}
s.ClientCredentialsOption = &client.GetTokenByClientCredentialsInput{EndpointParams: endpointparams}
default:
err = fmt.Errorf("grant-type must be one of (%s)", allGrantType)
}
Expand Down
16 changes: 16 additions & 0 deletions pkg/cmd/authentication_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"time"

"github.com/google/go-cmp/cmp"
"github.com/int128/kubelogin/pkg/oidc/client"
"github.com/int128/kubelogin/pkg/usecases/authentication"
"github.com/int128/kubelogin/pkg/usecases/authentication/authcode"
"github.com/int128/kubelogin/pkg/usecases/authentication/ropc"
Expand Down Expand Up @@ -92,6 +93,21 @@ func Test_authenticationOptions_grantOptionSet(t *testing.T) {
},
},
},
"GrantType=client-credentials": {
args: []string{
"--grant-type", "client-credentials",
"--oidc-auth-request-extra-params", "audience=https://example.com/service1",
"--oidc-auth-request-extra-params", "jti=myUUID",
},
want: authentication.GrantOptionSet{
ClientCredentialsOption: &client.GetTokenByClientCredentialsInput{
EndpointParams: map[string][]string{
"audience": []string{"https://example.com/service1"},
"jti": []string{"myUUID"},
},
},
},
},
"GrantType=auto": {
args: []string{
"--listen-address", "127.0.0.1:10080",
Expand Down
17 changes: 11 additions & 6 deletions pkg/di/wire_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 36 additions & 3 deletions pkg/oidc/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ import (
"time"

gooidc "github.com/coreos/go-oidc/v3/oidc"
"github.com/int128/oauth2cli"
"github.com/int128/oauth2dev"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"

"github.com/int128/kubelogin/pkg/infrastructure/clock"
"github.com/int128/kubelogin/pkg/infrastructure/logger"
"github.com/int128/kubelogin/pkg/oidc"
"github.com/int128/kubelogin/pkg/pkce"
"github.com/int128/oauth2cli"
"github.com/int128/oauth2dev"
"golang.org/x/oauth2"
)

type Interface interface {
Expand All @@ -22,6 +24,7 @@ type Interface interface {
GetTokenByAuthCode(ctx context.Context, in GetTokenByAuthCodeInput, localServerReadyChan chan<- string) (*oidc.TokenSet, error)
NegotiatedPKCEMethod() pkce.Method
GetTokenByROPC(ctx context.Context, username, password string) (*oidc.TokenSet, error)
GetTokenByClientCredentials(ctx context.Context, in GetTokenByClientCredentialsInput) (*oidc.TokenSet, error)
GetDeviceAuthorization(ctx context.Context) (*oauth2dev.AuthorizationResponse, error)
ExchangeDeviceCode(ctx context.Context, authResponse *oauth2dev.AuthorizationResponse) (*oidc.TokenSet, error)
Refresh(ctx context.Context, refreshToken string) (*oidc.TokenSet, error)
Expand Down Expand Up @@ -54,6 +57,10 @@ type GetTokenByAuthCodeInput struct {
LocalServerKeyFile string
}

type GetTokenByClientCredentialsInput struct {
EndpointParams map[string][]string
}

type client struct {
httpClient *http.Client
provider *gooidc.Provider
Expand Down Expand Up @@ -151,6 +158,32 @@ func (c *client) GetTokenByROPC(ctx context.Context, username, password string)
return c.verifyToken(ctx, token, "")
}

// GetTokenByClientCredentials performs the client credentials flow.
func (c *client) GetTokenByClientCredentials(ctx context.Context, in GetTokenByClientCredentialsInput) (*oidc.TokenSet, error) {
ctx = c.wrapContext(ctx)
c.logger.V(1).Infof("%s, %s, %v", c.oauth2Config.ClientID, c.oauth2Config.Endpoint.AuthURL, c.oauth2Config.Scopes)

config := clientcredentials.Config{
ClientID: c.oauth2Config.ClientID,
ClientSecret: c.oauth2Config.ClientSecret,
TokenURL: c.oauth2Config.Endpoint.TokenURL,
Scopes: c.oauth2Config.Scopes,
EndpointParams: in.EndpointParams,
AuthStyle: oauth2.AuthStyleInHeader,
}
source := config.TokenSource(ctx)
token, err := source.Token()
if err != nil {
return nil, fmt.Errorf("could not acquire token: %w", err)
}
if c.useAccessToken {
return &oidc.TokenSet{
IDToken: token.AccessToken,
RefreshToken: token.RefreshToken}, nil
}
return c.verifyToken(ctx, token, "")
}

// GetDeviceAuthorization initializes the device authorization code challenge
func (c *client) GetDeviceAuthorization(ctx context.Context) (*oauth2dev.AuthorizationResponse, error) {
ctx = c.wrapContext(ctx)
Expand Down
33 changes: 22 additions & 11 deletions pkg/usecases/authentication/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/int128/kubelogin/pkg/oidc/client"
"github.com/int128/kubelogin/pkg/tlsclientconfig"
"github.com/int128/kubelogin/pkg/usecases/authentication/authcode"
"github.com/int128/kubelogin/pkg/usecases/authentication/clientcredentials"
"github.com/int128/kubelogin/pkg/usecases/authentication/devicecode"
"github.com/int128/kubelogin/pkg/usecases/authentication/ropc"
)
Expand All @@ -22,6 +23,7 @@ var Set = wire.NewSet(
wire.Struct(new(authcode.Keyboard), "*"),
wire.Struct(new(ropc.ROPC), "*"),
wire.Struct(new(devicecode.DeviceCode), "*"),
wire.Struct(new(clientcredentials.ClientCredentials), "*"),
)

type Interface interface {
Expand All @@ -37,10 +39,11 @@ type Input struct {
}

type GrantOptionSet struct {
AuthCodeBrowserOption *authcode.BrowserOption
AuthCodeKeyboardOption *authcode.KeyboardOption
ROPCOption *ropc.Option
DeviceCodeOption *devicecode.Option
AuthCodeBrowserOption *authcode.BrowserOption
AuthCodeKeyboardOption *authcode.KeyboardOption
ROPCOption *ropc.Option
DeviceCodeOption *devicecode.Option
ClientCredentialsOption *client.GetTokenByClientCredentialsInput
}

// Output represents an output DTO of the Authentication use-case.
Expand All @@ -52,7 +55,7 @@ type Output struct {
//
// If the IDToken is not set, it performs the authentication flow.
// If the IDToken is valid, it does nothing.
// If the IDtoken has expired and the RefreshToken is set, it refreshes the token.
// If the IDToken has expired and the RefreshToken is set, it refreshes the token.
// If the RefreshToken has expired, it performs the authentication flow.
//
// The authentication flow is determined as:
Expand All @@ -61,12 +64,13 @@ type Output struct {
// Otherwise, it performs the resource owner password credentials flow.
// If the Password is not set, it asks a password by the prompt.
type Authentication struct {
ClientFactory client.FactoryInterface
Logger logger.Interface
AuthCodeBrowser *authcode.Browser
AuthCodeKeyboard *authcode.Keyboard
ROPC *ropc.ROPC
DeviceCode *devicecode.DeviceCode
ClientFactory client.FactoryInterface
Logger logger.Interface
AuthCodeBrowser *authcode.Browser
AuthCodeKeyboard *authcode.Keyboard
ROPC *ropc.ROPC
DeviceCode *devicecode.DeviceCode
ClientCredentials *clientcredentials.ClientCredentials
}

func (u *Authentication) Do(ctx context.Context, in Input) (*Output, error) {
Expand Down Expand Up @@ -113,5 +117,12 @@ func (u *Authentication) Do(ctx context.Context, in Input) (*Output, error) {
}
return &Output{TokenSet: *tokenSet}, nil
}
if in.GrantOptionSet.ClientCredentialsOption != nil {
tokenSet, err := u.ClientCredentials.Do(ctx, in.GrantOptionSet.ClientCredentialsOption, oidcClient)
if err != nil {
return nil, fmt.Errorf("client-credentials error: %w", err)
}
return &Output{TokenSet: *tokenSet}, nil
}
return nil, fmt.Errorf("any authorization grant must be set")
}
Loading