Skip to content

Commit

Permalink
Fixed auth configuration issue
Browse files Browse the repository at this point in the history
  • Loading branch information
micahlmartin committed Feb 2, 2022
1 parent 24ed3e8 commit 92e9185
Show file tree
Hide file tree
Showing 9 changed files with 203 additions and 81 deletions.
2 changes: 1 addition & 1 deletion harness/cd/cac_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func TestGetServiceById(t *testing.T) {

// Create application
c := getClient()
appName := fmt.Sprintf("app_%s_%s", t.Name(), utils.RandStringBytes(4))
appName := fmt.Sprintf("%s_%s", t.Name(), utils.RandStringBytes(4))
app, err := createApplication(appName)
require.NotNil(t, app)
require.NoError(t, err)
Expand Down
45 changes: 23 additions & 22 deletions harness/cd/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ type service struct {
ApiClient *ApiClient
}

type Configuration struct {
type Config struct {
AccountId string
APIKey string
Endpoint string
Expand All @@ -31,7 +31,7 @@ type Configuration struct {

type ApiClient struct {
common service // Reuse a single struct instead of allocating one for each service on the heap.
Configuration *Configuration
Configuration *Config
ApplicationClient *ApplicationClient
CloudProviderClient *CloudProviderClient
ConfigAsCodeClient *ConfigAsCodeClient
Expand All @@ -43,21 +43,36 @@ type ApiClient struct {
Log *log.Logger
}

func NewClient(cfg *Configuration) *ApiClient {
cfg.Endpoint = utils.CoalesceStr(cfg.Endpoint, helpers.EnvVars.Endpoint.GetWithDefault(utils.BaseUrl))
func NewClient(cfg *Config) (*ApiClient, error) {
cfg.AccountId = utils.CoalesceStr(cfg.AccountId, helpers.EnvVars.AccountId.Get())
if cfg.AccountId == "" {
return nil, cfg.NewInvalidConfigError("AccountId", nil)
}

cfg.APIKey = utils.CoalesceStr(cfg.APIKey, helpers.EnvVars.ApiKey.Get())
if cfg.APIKey == "" {
return nil, cfg.NewInvalidConfigError("ApiKey", nil)
}

validateConfig(cfg)
cfg.Endpoint = utils.CoalesceStr(cfg.Endpoint, helpers.EnvVars.Endpoint.GetWithDefault(utils.BaseUrl))

if cfg.Logger == nil {
cfg.Logger = logging.GetDefaultLogger(cfg.DebugLogging)
logger := logging.NewLogger()

if cfg.DebugLogging {
logger.SetLevel(log.DebugLevel)
}

cfg.Logger = logger
}

if cfg.HTTPClient == nil {
cfg.HTTPClient = utils.GetDefaultHttpClient(cfg.Logger)
}

// defaultHeaders
if cfg.DefaultHeaders == nil {
cfg.DefaultHeaders = map[string]string{}
cfg.DefaultHeaders = make(map[string]string)
}

// Set default headers for all requests
Expand All @@ -81,21 +96,7 @@ func NewClient(cfg *Configuration) *ApiClient {
c.SSOClient = (*SSOClient)(&c.common)
c.UserClient = (*UserClient)(&c.common)

return c
}

func validateConfig(cfg *Configuration) {
if cfg == nil {
panic("Configuration is required")
}

if cfg.Endpoint == "" {
panic("Endpoint must be set")
}

if cfg.APIKey == "" {
panic("APIKey must be set")
}
return c, nil
}

func (client *ApiClient) NewAuthorizedGetRequest(path string) (*retryablehttp.Request, error) {
Expand Down
80 changes: 78 additions & 2 deletions harness/cd/client_test.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,96 @@
package cd

import (
"os"
"testing"

"github.com/harness-io/harness-go-sdk/harness/helpers"
"github.com/stretchr/testify/require"
)

func getClient() *ApiClient {
return NewClient(&Configuration{
c, _ := NewClient(&Config{
AccountId: helpers.EnvVars.AccountId.Get(),
APIKey: helpers.EnvVars.ApiKey.Get(),
DebugLogging: false,
})

return c
}

func GetUnauthorizedClient() *ApiClient {
return NewClient(&Configuration{
c, _ := NewClient(&Config{
AccountId: helpers.EnvVars.AccountId.Get(),
APIKey: "BAD KEY",
})

return c
}

func TestClientRequireApiKey_Config(t *testing.T) {
os.Clearenv()

cfg := &Config{
AccountId: "ACCOUNT_ID",
}
_, err := NewClient(cfg)

require.Error(t, err, InvalidConfigError{})
require.Equal(t, "ApiKey", err.(InvalidConfigError).Field)

cfg = &Config{
AccountId: "ACCOUNT_ID",
APIKey: "APIKEY",
}
c, err := NewClient(cfg)

require.Equal(t, c.Configuration.APIKey, cfg.APIKey)
require.NoError(t, err)
}

func TestClientRequireApiKey_Envvar(t *testing.T) {
os.Clearenv()
os.Setenv(helpers.EnvVars.ApiKey.String(), "APIKEY")

cfg := &Config{
AccountId: "ACCOUNT_ID",
}
c, err := NewClient(cfg)

require.NoError(t, err, InvalidConfigError{})
require.Equal(t, "APIKEY", c.Configuration.APIKey)
}

func TestClientRequireAccountId_Config(t *testing.T) {
os.Clearenv()

cfg := &Config{
APIKey: "APIKEY",
}
_, err := NewClient(cfg)

require.Error(t, err, InvalidConfigError{})
require.Equal(t, "AccountId", err.(InvalidConfigError).Field)

cfg = &Config{
AccountId: "ACCOUNT_ID",
APIKey: "APIKEY",
}
c, err := NewClient(cfg)

require.Equal(t, c.Configuration.AccountId, cfg.AccountId)
require.NoError(t, err)
}

func TestClientRequireAccountId_Envvar(t *testing.T) {
os.Clearenv()
os.Setenv(helpers.EnvVars.AccountId.String(), "ACCOUNT_ID")

cfg := &Config{
APIKey: "APIKEY",
}
c, err := NewClient(cfg)

require.NoError(t, err, InvalidConfigError{})
require.Equal(t, "ACCOUNT_ID", c.Configuration.AccountId)
}
25 changes: 25 additions & 0 deletions harness/cd/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package cd

import "fmt"

type InvalidConfigError struct {
Config *Config
Field string
Err error
}

func (c *Config) NewInvalidConfigError(field string, err error) InvalidConfigError {
return InvalidConfigError{
Config: c,
Field: field,
Err: err,
}
}

func (e InvalidConfigError) Error() string {
return fmt.Sprintf("invalid config: %s must be set %s", e.Field, e.Err)
}

func (e InvalidConfigError) Unwrap() error {
return e.Err
}
2 changes: 0 additions & 2 deletions harness/helpers/envvars.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,13 @@ var EnvVars = struct {
DelegateSecret EnvVar
Endpoint EnvVar
NGApiKey EnvVar
NGEndpoint EnvVar
}{
AccountId: "HARNESS_ACCOUNT_ID",
ApiKey: "HARNESS_API_KEY",
BearerToken: "HARNESS_BEARER_TOKEN",
DelegateSecret: "HARNESS_DELEGATE_SECRET",
Endpoint: "HARNESS_ENDPOINT",
NGApiKey: "HARNESS_NG_API_KEY",
NGEndpoint: "HARNESS_NG_ENDPOINT",
}

func (e EnvVar) String() string {
Expand Down
2 changes: 1 addition & 1 deletion harness/utils/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ var (

func GetDefaultHttpClient(logger *log.Logger) *retryablehttp.Client {
httpClient := retryablehttp.NewClient()
httpClient.Logger = retryablehttp.LeveledLogger(&logging.LeveledLogger{Logger: logger})
httpClient.Logger = retryablehttp.LeveledLogger(&logging.Logger{Logger: logger})
httpClient.HTTPClient.Transport = logging.NewTransport(harness.SDKName, logger, cleanhttp.DefaultPooledClient().Transport)
httpClient.RetryMax = defaultRetryMax
return httpClient
Expand Down
45 changes: 19 additions & 26 deletions logging/logging.go
Original file line number Diff line number Diff line change
@@ -1,56 +1,49 @@
package logging

import (
"os"

log "github.com/sirupsen/logrus"
easy "github.com/t-tomalak/logrus-easy-formatter"
)

// func IsDebugOrHigher() bool {
// lvl := log.GetLevel()
// return lvl == log.DebugLevel || lvl == log.TraceLevel
// }

func IsDebugOrHigher(logger *log.Logger) bool {
lvl := logger.GetLevel()
return lvl == log.DebugLevel || lvl == log.TraceLevel
}

func GetDefaultLogger(debug bool) *log.Logger {
level := log.InfoLevel
if debug {
level = log.DebugLevel
}

logger := &log.Logger{
Out: os.Stderr,
Level: level,
Formatter: &easy.Formatter{
TimestampFormat: "2006-01-02 15:04:05",
LogFormat: "%time% [%lvl%] harness-go-sdk %msg%\n",
},
// NewLogger creates a new logger with default settings.
func NewLogger() *log.Logger {
logger := log.New()
logger.Formatter = &easy.Formatter{
TimestampFormat: "2006-01-02 15:04:05",
LogFormat: "%time% [%lvl%] harness-go-sdk %msg%\n",
}

return logger
}

type LeveledLogger struct {
type LeveledLogger interface {
Error(msg string, keysAndValues ...interface{})
Warn(msg string, keysAndValues ...interface{})
Info(msg string, keysAndValues ...interface{})
Debug(msg string, keysAndValues ...interface{})
IsDebugOrHigher() bool
}

type Logger struct {
Logger *log.Logger
}

func (l *LeveledLogger) Error(msg string, keysAndValues ...interface{}) {
func (l *Logger) Error(msg string, keysAndValues ...interface{}) {
l.Logger.Errorf(msg, keysAndValues...)
}

func (l *LeveledLogger) Info(msg string, keysAndValues ...interface{}) {
func (l *Logger) Info(msg string, keysAndValues ...interface{}) {
l.Logger.Infof(msg, keysAndValues...)
}

func (l *LeveledLogger) Debug(msg string, keysAndValues ...interface{}) {
func (l *Logger) Debug(msg string, keysAndValues ...interface{}) {
l.Logger.Debugf(msg, keysAndValues...)
}

func (l *LeveledLogger) Warn(msg string, keysAndValues ...interface{}) {
func (l *Logger) Warn(msg string, keysAndValues ...interface{}) {
l.Logger.Warnf(msg, keysAndValues...)
}
1 change: 1 addition & 0 deletions logging/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ type transport struct {
transport http.RoundTripper
}

// RoundTrip impelements the http.RoundTripper interface and adds rich debug logging.
func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
if IsDebugOrHigher(t.logger) {
reqData, err := httputil.DumpRequestOut(req, true)
Expand Down
Loading

0 comments on commit 92e9185

Please sign in to comment.