Skip to content
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

Support oauth2 authentication for pulsar-client-go #313

Merged
merged 11 commits into from
Jul 15, 2020
Next Next commit
Authentication provider for OAuth 2.0
- based on cloud-cli @ bc645b16ca7b7474b132ee1da8b56da35025a616
  • Loading branch information
EronWright committed Jul 6, 2020
commit a12a7c83813546c3a0f0800fd3c2c2a567426474
11 changes: 8 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,23 @@ module github.com/apache/pulsar-client-go
go 1.12

require (
github.com/DataDog/zstd v1.4.6-0.20200617134701-89f69fb7df32
github.com/DataDog/zstd v1.4.5
github.com/apache/pulsar-client-go/oauth2 v0.0.0-00010101000000-000000000000
github.com/beefsack/go-rate v0.0.0-20180408011153-efa7637bb9b6
github.com/bmizerany/perks v0.0.0-20141205001514-d9a9656a3a4b
github.com/gogo/protobuf v1.3.1
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/klauspost/compress v1.10.8
github.com/klauspost/compress v1.10.5
github.com/kr/pretty v0.2.0 // indirect
github.com/pierrec/lz4 v2.0.5+incompatible
github.com/pkg/errors v0.8.1
github.com/pkg/errors v0.9.1
github.com/sirupsen/logrus v1.4.1
github.com/spaolacci/murmur3 v1.1.0
github.com/spf13/cobra v0.0.3
github.com/spf13/pflag v1.0.3 // indirect
github.com/stretchr/testify v1.4.0
github.com/yahoo/athenz v1.8.55
k8s.io/utils v0.0.0-20200619165400-6e3d28b6ed19
Copy link
Contributor

Choose a reason for hiding this comment

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

This dependency was due to the mock clock right? I recall that you forked it elsewhere, would that work here too?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes. Let me replace it.

)

replace github.com/apache/pulsar-client-go/oauth2 => ./oauth2
91 changes: 85 additions & 6 deletions go.sum

Large diffs are not rendered by default.

96 changes: 96 additions & 0 deletions oauth2/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// Copyright (c) 2020 StreamNative, Inc.. All Rights Reserved.

package auth

import (
"fmt"
"time"

"github.com/dgrijalva/jwt-go"
"golang.org/x/oauth2"
"k8s.io/utils/clock"
)

const (
ClaimNameUserName = "https://streamnative.io/username"
)

// Flow abstracts an OAuth 2.0 authentication and authorization flow
type Flow interface {
// Authorize obtains an authorization grant based on an OAuth 2.0 authorization flow.
// The method returns a grant which may contain an initial access token.
Authorize() (*AuthorizationGrant, error)
}

// AuthorizationGrantRefresher refreshes OAuth 2.0 authorization grant
type AuthorizationGrantRefresher interface {
// Refresh refreshes an authorization grant to contain a fresh access token
Refresh(grant *AuthorizationGrant) (*AuthorizationGrant, error)
}

type AuthorizationGrantType string

const (
// GrantTypeClientCredentials represents a client credentials grant
GrantTypeClientCredentials AuthorizationGrantType = "client_credentials"

// GrantTypeDeviceCode represents a device code grant
GrantTypeDeviceCode AuthorizationGrantType = "device_code"
)

// AuthorizationGrant is a credential representing the resource owner's authorization
// to access its protected resources, and is used by the client to obtain an access token
type AuthorizationGrant struct {
// Type describes the type of authorization grant represented by this structure
Type AuthorizationGrantType `json:"type"`

// ClientCredentials is credentials data for the client credentials grant type
ClientCredentials *KeyFile `json:"client_credentials,omitempty"`

// Token contains an access token in the client credentials grant type,
// and a refresh token in the device authorization grant type
Token *oauth2.Token `json:"token,omitempty"`
}

// TokenResult holds token information
type TokenResult struct {
AccessToken string `json:"access_token"`
IDToken string `json:"id_token"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int `json:"expires_in"`
}

// Issuer holds information about the issuer of tokens
type Issuer struct {
IssuerEndpoint string
ClientID string
Audience string
}

func convertToOAuth2Token(token *TokenResult, clock clock.Clock) oauth2.Token {
return oauth2.Token{
AccessToken: token.AccessToken,
TokenType: "bearer",
RefreshToken: token.RefreshToken,
Expiry: clock.Now().Add(time.Duration(token.ExpiresIn) * time.Second),
}
}

// ExtractUserName extracts the username claim from an authorization grant
func ExtractUserName(token oauth2.Token) (string, error) {
p := jwt.Parser{}
claims := jwt.MapClaims{}
if _, _, err := p.ParseUnverified(token.AccessToken, claims); err != nil {
return "", fmt.Errorf("unable to decode the access token: %v", err)
}
username, ok := claims[ClaimNameUserName]
if !ok {
return "", fmt.Errorf("access token doesn't contain a username claim")
}
switch v := username.(type) {
case string:
return v, nil
default:
return "", fmt.Errorf("access token contains an unsupported username claim")
}
}
44 changes: 44 additions & 0 deletions oauth2/auth_suite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright (c) 2020 StreamNative, Inc.. All Rights Reserved.

package auth

import (
"context"
"testing"

. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)

func TestAuth(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "cloud-cli Auth Suite")
}

type MockTokenExchanger struct {
CalledWithRequest interface{}
ReturnsTokens *TokenResult
ReturnsError error
RefreshCalledWithRequest *RefreshTokenExchangeRequest
}

func (te *MockTokenExchanger) ExchangeCode(req AuthorizationCodeExchangeRequest) (*TokenResult, error) {
te.CalledWithRequest = &req
return te.ReturnsTokens, te.ReturnsError
}

func (te *MockTokenExchanger) ExchangeRefreshToken(req RefreshTokenExchangeRequest) (*TokenResult, error) {
te.RefreshCalledWithRequest = &req
return te.ReturnsTokens, te.ReturnsError
}

func (te *MockTokenExchanger) ExchangeClientCredentials(req ClientCredentialsExchangeRequest) (*TokenResult, error) {
te.CalledWithRequest = &req
return te.ReturnsTokens, te.ReturnsError
}

func (te *MockTokenExchanger) ExchangeDeviceCode(ctx context.Context,
req DeviceCodeExchangeRequest) (*TokenResult, error) {
te.CalledWithRequest = &req
return te.ReturnsTokens, te.ReturnsError
}
Loading