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

Add refresh token support for logins #258

Merged
merged 21 commits into from
May 8, 2024
Merged
Show file tree
Hide file tree
Changes from 9 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
3 changes: 0 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,6 @@ tools:
lint:
golangci-lint run

mocks:
@mockgen -source services/loginservice.go -destination services/loginservicemock.go -package services

$(COVER_ROOT):
@mkdir -p $(COVER_ROOT)

Expand Down
14 changes: 7 additions & 7 deletions app/account_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,14 @@ func (s *AccountTestSuite) SetupTest() {
}, nil
})
s.Require().NoError(err)
AutoConfirmFlag.Value = true
s.cliApp = &cli.App{
Name: "test",
Commands: []*cli.Command{out.Command},
Flags: []cli.Flag{
AutoConfirmFlag,
},

cmds := []*cli.Command{
out.Command,
}
flags := []cli.Flag{
AutoConfirmFlag,
}
s.cliApp, _ = NewTestApp(s.T(), cmds, flags)
}

func (s *AccountTestSuite) RunCmd(args ...string) error {
Expand Down
14 changes: 7 additions & 7 deletions app/apikey_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,14 @@ func (s *APIKeyTestSuite) SetupTest() {
}, nil
})
s.Require().NoError(err)
AutoConfirmFlag.Value = true
s.cliApp = &cli.App{
Name: "test",
Commands: []*cli.Command{out.Command},
Flags: []cli.Flag{
AutoConfirmFlag,
},

cmds := []*cli.Command{
out.Command,
}
flags := []cli.Flag{
AutoConfirmFlag,
}
s.cliApp, _ = NewTestApp(s.T(), cmds, flags)
}

func (s *APIKeyTestSuite) RunCmd(args ...string) error {
Expand Down
20 changes: 20 additions & 0 deletions app/app_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package app

import (
"testing"

"github.com/urfave/cli/v2"
)

func NewTestApp(t *testing.T, cmds []*cli.Command, flags []cli.Flag) (*cli.App, string) {
tmpDir := t.TempDir()
ConfigDirFlag.Value = tmpDir
disablePopUpFlag.Value = true
AutoConfirmFlag.Value = true

return &cli.App{
Name: t.Name(),
Commands: cmds,
Flags: flags,
}, tmpDir
}
13 changes: 6 additions & 7 deletions app/certificates_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,13 @@ func (s *CertificatesTestSuite) SetupTest() {
out, err := NewCertificatesCommand()
s.Require().NoError(err)

AutoConfirmFlag.Value = true
s.cliApp = &cli.App{
Name: "test",
Commands: []*cli.Command{out.Command},
Flags: []cli.Flag{
AutoConfirmFlag,
},
cmds := []*cli.Command{
out.Command,
}
flags := []cli.Flag{
AutoConfirmFlag,
}
s.cliApp, _ = NewTestApp(s.T(), cmds, flags)
}

func (s *CertificatesTestSuite) RunCmd(args ...string) error {
Expand Down
15 changes: 8 additions & 7 deletions app/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,25 +77,26 @@ func defaultDialOptions(c *cli.Context, addr *url.URL) ([]grpc.DialOption, error
return opts, nil
}

func newRPCCredential(c *cli.Context) (credentials.PerRPCCredentials, error) {
insecure := c.Bool(InsecureConnectionFlagName)
func newRPCCredential(ctx *cli.Context) (credentials.PerRPCCredentials, error) {
insecure := ctx.Bool(InsecureConnectionFlagName)

apiKey := c.String(APIKeyFlagName)
apiKey := ctx.String(APIKeyFlagName)
if len(apiKey) > 0 {
return apikey.NewCredential(
apiKey,
apikey.WithInsecureTransport(insecure),
)
}

tokens, err := loadLoginConfig(c)
loginConfig, err := NewLoginConfig(ctx.Context, ctx.Path(ConfigDirFlagName))
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to load login config: %w", err)
}

if len(tokens.AccessToken) > 0 {
source := loginConfig.TokenSource()
if source != nil {
return oauth.NewCredential(
tokens.AccessToken,
source,
oauth.WithInsecureTransport(insecure),
)
}
Expand Down
53 changes: 25 additions & 28 deletions app/connection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,22 @@ package app

import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"net"
"os"
"path"
"strings"
"testing"
"time"

"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/temporalio/tcld/app/credentials/apikey"
"github.com/temporalio/tcld/app/credentials/oauth"
"github.com/temporalio/tcld/app/credentials"
"github.com/temporalio/tcld/protogen/api/request/v1"
"github.com/temporalio/tcld/protogen/api/requestservice/v1"
"github.com/urfave/cli/v2"

"golang.org/x/oauth2"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
Expand Down Expand Up @@ -62,12 +61,17 @@ func TestServerConnection(t *testing.T) {

func (s *ServerConnectionTestSuite) SetupTest() {
s.configDir = s.T().TempDir()
data, err := json.Marshal(OAuthTokenResponse{
AccessToken: testAccessToken,
})
require.NoError(s.T(), err)
ConfigDirFlag.Value = s.configDir

loginConfig := LoginConfig{
StoredToken: oauth2.Token{
AccessToken: testAccessToken,
Expiry: time.Now().Add(24 * time.Hour),
},
configDir: s.configDir,
}

err = os.WriteFile(path.Join(s.configDir, tokenFileName), data, 0600)
err := loginConfig.StoreConfig()
require.NoError(s.T(), err)

s.listener = bufconn.Listen(1024 * 1024)
Expand All @@ -87,10 +91,10 @@ func (s *ServerConnectionTestSuite) TeardownTest() {

func (s *ServerConnectionTestSuite) TestGetServerConnection() {
testcases := []struct {
name string
args map[string]string
expectedHeaders map[string]string
expectedErr error
name string
args map[string]string
expectedToken string
expectedErr error
}{
{
name: "ErrorInvalidHostname",
Expand Down Expand Up @@ -119,19 +123,15 @@ func (s *ServerConnectionTestSuite) TestGetServerConnection() {
args: map[string]string{
InsecureConnectionFlagName: "", // required for bufconn
},
expectedHeaders: map[string]string{
oauth.Header: "Bearer " + testAccessToken,
},
expectedToken: testAccessToken,
},
{
name: "APIKeySucess",
args: map[string]string{
InsecureConnectionFlagName: "", // required for bufconn
APIKeyFlagName: testAPIKey,
},
expectedHeaders: map[string]string{
apikey.AuthorizationHeader: "Bearer " + testAPIKey,
},
expectedToken: testAPIKey,
},
}
for _, tc := range testcases {
Expand Down Expand Up @@ -191,14 +191,11 @@ func (s *ServerConnectionTestSuite) TestGetServerConnection() {
commit := getHeaderValue(md, CommitHeader)
s.Equal(buildInfo.Commit, commit)

_, usingAPIKeys := tc.args[APIKeyFlagName]
if usingAPIKeys {
authHeader := getHeaderValue(md, apikey.AuthorizationHeader)
s.Equal("Bearer "+testAPIKey, authHeader)
} else {
token := getHeaderValue(md, oauth.Header)
s.Equal("Bearer "+testAccessToken, token)
}
auth := strings.SplitN(getHeaderValue(md, credentials.AuthorizationHeader), " ", 2)
require.Len(s.T(), auth, 2)

s.Equal(strings.ToLower(credentials.AuthorizationBearer), strings.ToLower(auth[0]))
s.Equal(auth[1], tc.expectedToken)
})
}
}
Expand Down
15 changes: 7 additions & 8 deletions app/credentials/apikey/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@ import (
"context"
"fmt"

"google.golang.org/grpc/credentials"
"github.com/temporalio/tcld/app/credentials"
grpccreds "google.golang.org/grpc/credentials"
)

const (
AuthorizationHeader = "Authorization"
AuthorizationHeaderPrefix = "Bearer"
Separator = "_"
Separator = "_"
)

type Credential struct {
Expand Down Expand Up @@ -42,25 +41,25 @@ func NewCredential(key string, opts ...Option) (Credential, error) {
}

func (c Credential) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
ri, ok := credentials.RequestInfoFromContext(ctx)
ri, ok := grpccreds.RequestInfoFromContext(ctx)
if !ok {
return nil, fmt.Errorf("failed to retrieve request info from context")
}

if !c.allowInsecureTransport {
// Ensure the API key, AKA bearer token, is sent over a secure connection - meaning TLS.
if err := credentials.CheckSecurityLevel(ri.AuthInfo, credentials.PrivacyAndIntegrity); err != nil {
if err := grpccreds.CheckSecurityLevel(ri.AuthInfo, grpccreds.PrivacyAndIntegrity); err != nil {
return nil, fmt.Errorf("the connection's transport security level is too low for API keys: %v", err)
}
}

return map[string]string{
AuthorizationHeader: fmt.Sprintf("%s %s", AuthorizationHeaderPrefix, c.Key),
credentials.AuthorizationHeader: fmt.Sprintf("%s %s", credentials.AuthorizationBearer, c.Key),
}, nil
}

func (c Credential) RequireTransportSecurity() bool {
return !c.allowInsecureTransport
}

var _ credentials.PerRPCCredentials = (*Credential)(nil)
var _ grpccreds.PerRPCCredentials = (*Credential)(nil)
6 changes: 6 additions & 0 deletions app/credentials/header.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package credentials

const (
AuthorizationHeader = "Authorization"
AuthorizationBearer = "Bearer"
shakeelrao marked this conversation as resolved.
Show resolved Hide resolved
)
37 changes: 18 additions & 19 deletions app/credentials/oauth/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,11 @@ import (
"context"
"fmt"

"google.golang.org/grpc/credentials"
"github.com/temporalio/tcld/app/credentials"
"golang.org/x/oauth2"
grpccreds "google.golang.org/grpc/credentials"
)

const (
Header = "authorization"
)

var _ credentials.PerRPCCredentials = (*Credential)(nil)

type Option = func(c *Credential)

func WithInsecureTransport(insecure bool) Option {
Expand All @@ -22,17 +18,17 @@ func WithInsecureTransport(insecure bool) Option {
}

type Credential struct {
accessToken string // keep unexported to prevent accidental leakage of the token.
source oauth2.TokenSource
allowInsecureTransport bool
}

func NewCredential(accessToken string, opts ...Option) (Credential, error) {
if len(accessToken) == 0 {
return Credential{}, fmt.Errorf("an empty access token was provided")
func NewCredential(source oauth2.TokenSource, opts ...Option) (Credential, error) {
if source == nil {
return Credential{}, fmt.Errorf("a nil token source was provided")
}

c := Credential{
accessToken: accessToken,
source: source,
}
for _, opt := range opts {
opt(&c)
Expand All @@ -42,27 +38,30 @@ func NewCredential(accessToken string, opts ...Option) (Credential, error) {
}

func (c Credential) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
ri, ok := credentials.RequestInfoFromContext(ctx)
ri, ok := grpccreds.RequestInfoFromContext(ctx)
if !ok {
return nil, fmt.Errorf("failed to retrieve request info from context")
}

if !c.allowInsecureTransport {
// Ensure the bearer token is sent over a secure connection - meaning TLS.
if err := credentials.CheckSecurityLevel(ri.AuthInfo, credentials.PrivacyAndIntegrity); err != nil {
return nil, fmt.Errorf("the connection's transport security level is too low for OAuth: %v", err)
if err := grpccreds.CheckSecurityLevel(ri.AuthInfo, grpccreds.PrivacyAndIntegrity); err != nil {
return nil, fmt.Errorf("the connection's transport security level is too low for OAuth: %w", err)
}
}

token, err := c.source.Token()
if err != nil {
return nil, fmt.Errorf("failed to retrieve token from token source: %w", err)
}

return map[string]string{
Header: c.token(),
credentials.AuthorizationHeader: fmt.Sprintf("%s %s", token.Type(), token.AccessToken),
tminusplus marked this conversation as resolved.
Show resolved Hide resolved
}, nil
}

func (c Credential) RequireTransportSecurity() bool {
return !c.allowInsecureTransport
}

func (c Credential) token() string {
return "Bearer " + c.accessToken
}
var _ grpccreds.PerRPCCredentials = (*Credential)(nil)
shakeelrao marked this conversation as resolved.
Show resolved Hide resolved
6 changes: 6 additions & 0 deletions app/feature.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ func contains(f FeatureFlag, ffs []string) bool {
}

func getFeatureFlagsFromConfigFile(featureFlagConfigPath string) ([]FeatureFlag, error) {
// Ensure the config directory exists.
configDir := filepath.Dir(featureFlagConfigPath)
if err := os.MkdirAll(configDir, 0700); err != nil {
return nil, err
}

// create config file if not exist
if _, err := os.Stat(featureFlagConfigPath); err != nil {
if err := os.WriteFile(featureFlagConfigPath, []byte("[]"), 0644); err != nil {
Expand Down
Loading
Loading