From 94bdcca9ec59110c6a5a2f4217f03f22bd3d46d4 Mon Sep 17 00:00:00 2001 From: wklken Date: Tue, 11 Jan 2022 15:54:46 +0800 Subject: [PATCH 1/6] feat(support/bkauth): add bkauth support, check app_code/app_secret --- cmd/init.go | 26 +++- pkg/api/model/handler/system_test.go | 4 +- pkg/cacheimpls/init.go | 4 + pkg/cacheimpls/local_app_code_secret.go | 30 ++++ pkg/cacheimpls/local_remote_resource_list.go | 4 +- pkg/cacheimpls/remote_resource_test.go | 2 +- pkg/component/auth.go | 145 +++++++++++++++++++ pkg/component/init.go | 14 +- pkg/component/types.go | 16 ++ pkg/config/config.go | 39 +++-- pkg/database/init.go | 2 +- pkg/middleware/client.go | 11 +- pkg/middleware/client_test.go | 2 +- 13 files changed, 267 insertions(+), 32 deletions(-) create mode 100644 pkg/component/auth.go diff --git a/cmd/init.go b/cmd/init.go index cda99330..33c5f109 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -76,13 +76,19 @@ func initDatabase() { panic("database bk-iam should be configured") } + if globalConfig.EnableBkAuth { + database.InitDBClients(&defaultDBConfig, nil) + log.Info("init Database success") + return + } + // TODO: 不应该成为强依赖 bkPaaSDBConfig, ok := globalConfig.DatabaseMap["open_paas"] if !ok { - panic("database open_paas should be configured") + panic("bkauth is not enabled, so database open_paas should be configured") } - database.InitDBClients(&defaultDBConfig, &bkPaaSDBConfig) + log.Info("init Database success") } @@ -142,7 +148,21 @@ func initSupportShieldFeatures() { } func initComponents() { - component.InitComponentClients() + component.InitBkRemoteResourceClient() + + if globalConfig.EnableBkAuth { + bkAuthHost, ok := globalConfig.HostMap["bkauth"] + if !ok { + panic("bkauth is enabled, so host bkauth should be configured") + } + + if globalConfig.BkAppCode == "" || globalConfig.BkAppSecret == "" { + panic("bkauth is enabled, but iam's bkAppCode and bkAppSecret is not configured") + } + + component.InitBkAuthClient(bkAuthHost.Addr, globalConfig.BkAppCode, globalConfig.BkAppSecret) + log.Infof("init bkauth client success, host = %s", bkAuthHost.Addr) + } } func initQuota() { diff --git a/pkg/api/model/handler/system_test.go b/pkg/api/model/handler/system_test.go index 23ac5a0a..0e6db01c 100644 --- a/pkg/api/model/handler/system_test.go +++ b/pkg/api/model/handler/system_test.go @@ -90,7 +90,7 @@ func TestCreateSystem(t *testing.T) { // init the router r := util.SetupRouter() - r.Use(middleware.ClientAuthMiddleware([]byte(""))) + r.Use(middleware.ClientAuthMiddleware([]byte(""), false)) url := "/api/v1/systems" r.POST(url, CreateSystem) @@ -287,7 +287,7 @@ func TestUpdateSystem(t *testing.T) { // init the router r := util.SetupRouter() - r.Use(middleware.ClientAuthMiddleware([]byte(""))) + r.Use(middleware.ClientAuthMiddleware([]byte(""), false)) url := "/api/v1/systems/test" r.POST(url, UpdateSystem) diff --git a/pkg/cacheimpls/init.go b/pkg/cacheimpls/init.go index 294df534..34e951bb 100644 --- a/pkg/cacheimpls/init.go +++ b/pkg/cacheimpls/init.go @@ -30,6 +30,7 @@ const CacheLayer = "Cache" // LocalAppCodeAppSecretCache ... var ( LocalAppCodeAppSecretCache memory.Cache + LocalAuthAppAccessKeyCache *gocache.Cache LocalSubjectCache memory.Cache LocalSubjectRoleCache memory.Cache LocalSystemClientsCache memory.Cache @@ -81,6 +82,9 @@ func InitCaches(disabled bool) { nil, ) + // auth app_code/app_secret cache + LocalAuthAppAccessKeyCache = gocache.New(12*time.Hour, 5*time.Minute) + // 影响: engine增量同步 LocalSubjectCache = memory.NewCache( diff --git a/pkg/cacheimpls/local_app_code_secret.go b/pkg/cacheimpls/local_app_code_secret.go index 055ef850..6c082eb7 100644 --- a/pkg/cacheimpls/local_app_code_secret.go +++ b/pkg/cacheimpls/local_app_code_secret.go @@ -11,9 +11,13 @@ package cacheimpls import ( + "time" + "github.com/TencentBlueKing/gopkg/cache" + gocache "github.com/patrickmn/go-cache" log "github.com/sirupsen/logrus" + "iam/pkg/component" "iam/pkg/database/edao" ) @@ -48,3 +52,29 @@ func VerifyAppCodeAppSecret(appCode, appSecret string) bool { } return exists } + +func VerifyAppCodeAppSecretFromAuth(appCode, appSecret string) bool { + // 1. get from cache + key := appCode + ":" + appSecret + + value, found := LocalAuthAppAccessKeyCache.Get(key) + if found { + return value.(bool) + } + + // 2. get from auth + valid, err := component.BkAuth.Verify(appCode, appSecret) + if err != nil { + log.Errorf("verify app_code_app_secret from auth fail, key=%s, err=%s", key, err) + return false + } + + // 3. set to cache, default 12 hours, if not valid, only keep in cache for 1 minutes + // in case of auth server down, we can still get the valid matched accessKeys from cache + ttl := gocache.DefaultExpiration + if !valid { + ttl = 1 * time.Minute + } + LocalAuthAppAccessKeyCache.Set(key, valid, ttl) + return valid +} diff --git a/pkg/cacheimpls/local_remote_resource_list.go b/pkg/cacheimpls/local_remote_resource_list.go index dbc9dbb1..d157f71e 100644 --- a/pkg/cacheimpls/local_remote_resource_list.go +++ b/pkg/cacheimpls/local_remote_resource_list.go @@ -81,10 +81,10 @@ func listRemoteResources(systemID, _type string, ids []string, fields []string) return nil, err } - resources, err := component.BKRemoteResource.GetResources(req, systemID, _type, ids, fields) + resources, err := component.BkRemoteResource.GetResources(req, systemID, _type, ids, fields) if err != nil { err = errorWrapf( - err, "BKRemoteResource.GetResource systemID=`%s`, resourceTypeID=`%s`, ids length=`%d`, fields=`%s` fail", + err, "BkRemoteResource.GetResource systemID=`%s`, resourceTypeID=`%s`, ids length=`%d`, fields=`%s` fail", systemID, _type, len(ids), fields) return nil, err } diff --git a/pkg/cacheimpls/remote_resource_test.go b/pkg/cacheimpls/remote_resource_test.go index 693fe590..c5d585ab 100644 --- a/pkg/cacheimpls/remote_resource_test.go +++ b/pkg/cacheimpls/remote_resource_test.go @@ -84,7 +84,7 @@ func TestGetCMDBResource(t *testing.T) { "id": "checklist", }}, nil).AnyTimes() - component.BKRemoteResource = mockService + component.BkRemoteResource = mockService mockCache := redis.NewMockCache("mockCache", expiration) diff --git a/pkg/component/auth.go b/pkg/component/auth.go new file mode 100644 index 00000000..d4afb2db --- /dev/null +++ b/pkg/component/auth.go @@ -0,0 +1,145 @@ +package component + +import ( + "errors" + "fmt" + "net/http" + "strings" + "time" + + "github.com/TencentBlueKing/gopkg/errorx" + "github.com/parnurzeal/gorequest" + + "iam/pkg/logging" +) + +// AuthResponse is the struct of iam backend response +type AuthResponse struct { + Code int `json:"code"` + Message string `json:"message"` + Data map[string]interface{} `json:"data"` +} + +// Error will check if the response with error +func (r *AuthResponse) Error() error { + if r.Code == 0 { + return nil + } + + return fmt.Errorf("response error[code=`%d`, message=`%s`]", r.Code, r.Message) +} + +// String will return the detail text of the response +func (r *AuthResponse) String() string { + return fmt.Sprintf("response[code=`%d`, message=`%s`, data=`%v`]", r.Code, r.Message, r.Data) +} + +// AuthClient is the interface of auth client +type AuthClient interface { + Verify(bkAppCode, bkAppSecret string) (bool, error) +} + +type authClient struct { + Host string + + appCode string + appSecret string +} + +// NewAuthClient will create a auth client +func NewAuthClient(host string, appCode string, appSecret string) AuthClient { + host = strings.TrimRight(host, "/") + return &authClient{ + Host: host, + appCode: appCode, + appSecret: appSecret, + } +} + +func (c *authClient) call( + method Method, + path string, + data interface{}, + timeout int64, +) (map[string]interface{}, error) { + errorWrapf := errorx.NewLayerFunctionErrorWrapf("component", "authClient.call") + + callTimeout := time.Duration(timeout) * time.Second + if timeout == 0 { + callTimeout = defaultTimeout + } + + url := fmt.Sprintf("%s%s", c.Host, path) + result := AuthResponse{} + start := time.Now() + callbackFunc := NewMetricCallback("Auth", start) + + request := gorequest.New() + switch method { + case POST: + request = request.Post(url) + case GET: + request = request.Get(url) + } + request = request.Timeout(callTimeout).Type("json") + + // set headers + request.Header.Set("X-BK-APP-CODE", c.appCode) + request.Header.Set("X-BK-APP-SECRET", c.appSecret) + + // do request + resp, _, errs := request. + Send(data). + EndStruct(&result, callbackFunc) + + // NOTE: it's a sensitive api, so, no log request detail! + // logFailHTTPRequest(start, request, resp, respBody, errs, &result) + logger := logging.GetComponentLogger() + + var err error + if len(errs) != 0 { + // 敏感信息泄漏 ip+端口号, 替换为 *.*.*.* + errsMessage := fmt.Sprintf("gorequest errorx=`%s`", errs) + errsMessage = ipRegex.ReplaceAllString(errsMessage, replaceToIP) + err = errors.New(errsMessage) + + err = errorWrapf(err, "errsCount=`%d`", len(errs)) + logger.Errorf("call auth api %s fail, err=%s", path, err.Error()) + return nil, err + } + if resp.StatusCode != http.StatusOK { + err = fmt.Errorf("gorequest statusCode is %d not 200", resp.StatusCode) + logger.Errorf("call auth api %s fail , err=%s", path, err.Error()) + return nil, errorWrapf(err, "status=%d", resp.StatusCode) + } + if result.Code != 0 { + err = errors.New(result.Message) + err = errorWrapf(err, "result.Code=%d", result.Code) + logger.Errorf("call auth api %s ok but code in response is not 0, err=%s", path, err.Error()) + return nil, err + } + + return result.Data, nil +} + +// Verify will check bkAppCode, bkAppSecret is valid +func (c *authClient) Verify(bkAppCode, bkAppSecret string) (bool, error) { + path := fmt.Sprintf("/api/v1/apps/%s/access-keys/verify", bkAppCode) + + data, err := c.call(GET, path, map[string]interface{}{ + "bk_app_secret": bkAppSecret, + }, 5) + if err != nil { + return false, err + } + matchI, ok := data["is_match"] + if !ok { + return false, errors.New("no is_match in response body") + } + + match, ok := matchI.(bool) + if !ok { + return false, errors.New("is_match is not a valid bool") + } + return match, nil +} diff --git a/pkg/component/init.go b/pkg/component/init.go index e9cf463e..4b7658f4 100644 --- a/pkg/component/init.go +++ b/pkg/component/init.go @@ -29,14 +29,18 @@ const ( maxResponseBodyLength = 10240 ) -// BKRemoteResource ... var ( - BKRemoteResource RemoteResourceClient + BkRemoteResource RemoteResourceClient + BkAuth AuthClient ) -// InitComponentClients ... -func InitComponentClients() { - BKRemoteResource = NewRemoteResourceClient() +// InitBkRemoteResourceClient ... +func InitBkRemoteResourceClient() { + BkRemoteResource = NewRemoteResourceClient() +} + +func InitBkAuthClient(bkAuthHost, appCode, appSecret string) { + BkAuth = NewAuthClient(bkAuthHost, appCode, appSecret) } // CallbackFunc ... diff --git a/pkg/component/types.go b/pkg/component/types.go index d3ac1234..7c21a157 100644 --- a/pkg/component/types.go +++ b/pkg/component/types.go @@ -10,6 +10,22 @@ package component +import "time" + +const ( + defaultTimeout = 5 * time.Second +) + +// Method is the type of http method +type Method string + +var ( + // POST http post + POST Method = "POST" + // GET http get + GET Method = "GET" +) + type responseStruct interface { Error() error } diff --git a/pkg/config/config.go b/pkg/config/config.go index 5a357a1d..8ea29408 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -109,10 +109,10 @@ type SystemQuota struct { Quota Quota } -// type Host struct { -// ID string -// Addr string -// } +type Host struct { + ID string + Addr string +} // Crypto store the keys for crypto type Crypto struct { @@ -127,6 +127,10 @@ type Config struct { Server Server Sentry Sentry + // iam's app_code and app_secret + BkAppCode string + BkAppSecret string + SuperAppCode string // default superuser SuperUser string @@ -139,13 +143,15 @@ type Config struct { Redis []Redis RedisMap map[string]Redis + EnableBkAuth bool + Hosts []Host + HostMap map[string]Host + Quota Quota CustomQuotas []SystemQuota CustomQuotasMap map[string]Quota - // Hosts []Host - // HostMap map[string]Host Switch map[string]bool Cache Cache @@ -155,7 +161,7 @@ type Config struct { Cryptos map[string]*Crypto } -// Load: 从viper中读取配置文件 +// Load 从viper中读取配置文件 func Load(v *viper.Viper) (*Config, error) { var cfg Config // 将配置信息绑定到结构体上 @@ -180,17 +186,22 @@ func Load(v *viper.Viper) (*Config, error) { cfg.RedisMap[rds.ID] = rds } - // 3. init quota + // 3. hosts + cfg.HostMap = make(map[string]Host) + for _, host := range cfg.Hosts { + cfg.HostMap[host.ID] = host + } + if cfg.EnableBkAuth { + if len(cfg.HostMap) == 0 { + return nil, errors.New("hosts cannot be empty") + } + } + + // 4. init quota cfg.CustomQuotasMap = make(map[string]Quota) for _, q := range cfg.CustomQuotas { cfg.CustomQuotasMap[q.ID] = q.Quota } - // 3. hosts - // cfg.HostMap = make(map[string]Host) - // for _, host := range cfg.Hosts { - // cfg.HostMap[host.ID] = host - // } - return &cfg, nil } diff --git a/pkg/database/init.go b/pkg/database/init.go index fe601811..7d4b7028 100644 --- a/pkg/database/init.go +++ b/pkg/database/init.go @@ -51,7 +51,7 @@ func InitDBClients(defaultDBConfig, bkPaaSDBConfig *config.Database) { } // NOTE: change to app_code/app_secret verify api in the future - if BKPaaSDBClient == nil { + if BKPaaSDBClient == nil && bkPaaSDBConfig != nil { bkPaaSDBClientOnce.Do(func() { BKPaaSDBClient = NewDBClient(bkPaaSDBConfig) if err := BKPaaSDBClient.Connect(); err != nil { diff --git a/pkg/middleware/client.go b/pkg/middleware/client.go index 2a301658..462eca61 100644 --- a/pkg/middleware/client.go +++ b/pkg/middleware/client.go @@ -33,11 +33,11 @@ func NewClientAuthMiddleware(c *config.Config) gin.HandlerFunc { apiGatewayPublicKey = []byte(apigwCrypto.Key) } - return ClientAuthMiddleware(apiGatewayPublicKey) + return ClientAuthMiddleware(apiGatewayPublicKey, c.EnableBkAuth) } // ClientAuthMiddleware ... -func ClientAuthMiddleware(apiGatewayPublicKey []byte) gin.HandlerFunc { +func ClientAuthMiddleware(apiGatewayPublicKey []byte, enableBkAuth bool) gin.HandlerFunc { return func(c *gin.Context) { log.Debug("Middleware: ClientAuthMiddleware") @@ -80,7 +80,12 @@ func ClientAuthMiddleware(apiGatewayPublicKey []byte) gin.HandlerFunc { } // 2. validate from cache -> database - valid := cacheimpls.VerifyAppCodeAppSecret(appCode, appSecret) + var valid bool + if enableBkAuth { + valid = cacheimpls.VerifyAppCodeAppSecretFromAuth(appCode, appSecret) + } else { + valid = cacheimpls.VerifyAppCodeAppSecret(appCode, appSecret) + } if !valid { util.UnauthorizedJSONResponse(c, "app code or app secret wrong") c.Abort() diff --git a/pkg/middleware/client_test.go b/pkg/middleware/client_test.go index 33629c6f..dbebeb7f 100644 --- a/pkg/middleware/client_test.go +++ b/pkg/middleware/client_test.go @@ -29,7 +29,7 @@ func TestClientAuthMiddleware(t *testing.T) { // 1. without appCode appSecret r := gin.Default() - r.Use(ClientAuthMiddleware([]byte(""))) + r.Use(ClientAuthMiddleware([]byte(""), false)) util.NewTestRouter(r) req, _ := http.NewRequest("GET", "/ping", nil) From e1af85afcffba781818d2a2405f975b2a80c8929 Mon Sep 17 00:00:00 2001 From: wklken Date: Tue, 11 Jan 2022 16:49:01 +0800 Subject: [PATCH 2/6] fix(support/auth): a. remove sensitive info from log b.verify from get to post c.more error detail --- pkg/cacheimpls/local_app_code_secret.go | 11 +++++++++-- pkg/component/auth.go | 16 ++++++++++++---- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/pkg/cacheimpls/local_app_code_secret.go b/pkg/cacheimpls/local_app_code_secret.go index 6c082eb7..9ba08634 100644 --- a/pkg/cacheimpls/local_app_code_secret.go +++ b/pkg/cacheimpls/local_app_code_secret.go @@ -14,6 +14,7 @@ import ( "time" "github.com/TencentBlueKing/gopkg/cache" + "github.com/TencentBlueKing/gopkg/stringx" gocache "github.com/patrickmn/go-cache" log "github.com/sirupsen/logrus" @@ -47,7 +48,10 @@ func VerifyAppCodeAppSecret(appCode, appSecret string) bool { } exists, err := LocalAppCodeAppSecretCache.GetBool(key) if err != nil { - log.Errorf("get app_code_app_secret from memory cache fail, key=%s, err=%s", key.Key(), err) + log.Errorf("get app_code_app_secret from memory cache fail, app_code=%s, app_secret=%s, err=%s", + appCode, + stringx.Truncate(appSecret, 6)+"******", + err) return false } return exists @@ -65,7 +69,10 @@ func VerifyAppCodeAppSecretFromAuth(appCode, appSecret string) bool { // 2. get from auth valid, err := component.BkAuth.Verify(appCode, appSecret) if err != nil { - log.Errorf("verify app_code_app_secret from auth fail, key=%s, err=%s", key, err) + log.Errorf("verify app_code_app_secret from auth fail, app_code=%s, app_secret=%s, err=%s", + appCode, + stringx.Truncate(appSecret, 6)+"******", + err) return false } diff --git a/pkg/component/auth.go b/pkg/component/auth.go index d4afb2db..ef7d54e3 100644 --- a/pkg/component/auth.go +++ b/pkg/component/auth.go @@ -7,6 +7,7 @@ import ( "strings" "time" + "github.com/TencentBlueKing/gopkg/conv" "github.com/TencentBlueKing/gopkg/errorx" "github.com/parnurzeal/gorequest" @@ -88,7 +89,7 @@ func (c *authClient) call( request.Header.Set("X-BK-APP-SECRET", c.appSecret) // do request - resp, _, errs := request. + resp, respBody, errs := request. Send(data). EndStruct(&result, callbackFunc) @@ -108,28 +109,35 @@ func (c *authClient) call( return nil, err } if resp.StatusCode != http.StatusOK { - err = fmt.Errorf("gorequest statusCode is %d not 200", resp.StatusCode) + err = fmt.Errorf("gorequest statusCode is %d not 200, respBody=%s", + resp.StatusCode, conv.BytesToString(respBody)) logger.Errorf("call auth api %s fail , err=%s", path, err.Error()) return nil, errorWrapf(err, "status=%d", resp.StatusCode) } if result.Code != 0 { err = errors.New(result.Message) err = errorWrapf(err, "result.Code=%d", result.Code) - logger.Errorf("call auth api %s ok but code in response is not 0, err=%s", path, err.Error()) + logger.Errorf("call auth api %s ok but code in response is not 0, respBody=%s, err=%s", + path, conv.BytesToString(respBody), err.Error()) return nil, err } + fmt.Println("result.Data", result.Data) return result.Data, nil } // Verify will check bkAppCode, bkAppSecret is valid func (c *authClient) Verify(bkAppCode, bkAppSecret string) (bool, error) { + errorWrapf := errorx.NewLayerFunctionErrorWrapf("component", "authClient.Verify") + path := fmt.Sprintf("/api/v1/apps/%s/access-keys/verify", bkAppCode) - data, err := c.call(GET, path, map[string]interface{}{ + data, err := c.call(POST, path, map[string]interface{}{ "bk_app_secret": bkAppSecret, }, 5) if err != nil { + err = errorWrapf(err, "verify app_code=`%s` fail", bkAppCode) + return false, err } matchI, ok := data["is_match"] From 2ccd043d82ee563b253cbd9c28baa624158023eb Mon Sep 17 00:00:00 2001 From: wklken Date: Tue, 11 Jan 2022 16:55:40 +0800 Subject: [PATCH 3/6] fix(lint): fix lints --- pkg/component/auth.go | 1 - 1 file changed, 1 deletion(-) diff --git a/pkg/component/auth.go b/pkg/component/auth.go index ef7d54e3..013776cb 100644 --- a/pkg/component/auth.go +++ b/pkg/component/auth.go @@ -121,7 +121,6 @@ func (c *authClient) call( path, conv.BytesToString(respBody), err.Error()) return nil, err } - fmt.Println("result.Data", result.Data) return result.Data, nil } From 4f3d734292ea6135cd22a6f5897b3fd76062d041 Mon Sep 17 00:00:00 2001 From: wklken Date: Tue, 11 Jan 2022 17:07:52 +0800 Subject: [PATCH 4/6] chore(version): to 1.9.4 --- VERSION | 2 +- release.md | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/VERSION b/VERSION index 77fee73a..d615fd0c 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.9.3 +1.9.4 diff --git a/release.md b/release.md index a2da06ef..06982985 100644 --- a/release.md +++ b/release.md @@ -1,3 +1,7 @@ +# 1.9.4 + +- add: bkauth support + # 1.9.3 - update: replace some lib with https://github.com/TencentBlueKing/gopkg From ed8cb08f510dd8dd20fa35fa94f8b78181c06e28 Mon Sep 17 00:00:00 2001 From: wklken Date: Wed, 12 Jan 2022 16:47:51 +0800 Subject: [PATCH 5/6] fix(cr/comments): fix cr comments --- pkg/component/auth.go | 27 ++++++++++++++------------- pkg/component/init.go | 4 ++-- pkg/config/config.go | 5 ----- 3 files changed, 16 insertions(+), 20 deletions(-) diff --git a/pkg/component/auth.go b/pkg/component/auth.go index 013776cb..9a3342e5 100644 --- a/pkg/component/auth.go +++ b/pkg/component/auth.go @@ -37,23 +37,24 @@ func (r *AuthResponse) String() string { // AuthClient is the interface of auth client type AuthClient interface { - Verify(bkAppCode, bkAppSecret string) (bool, error) + Verify(appCode, appSecret string) (bool, error) } type authClient struct { Host string - appCode string - appSecret string + // iam's app_code/app_secret, credentials for bkauth + bkAppCode string + bkAppSecret string } // NewAuthClient will create a auth client -func NewAuthClient(host string, appCode string, appSecret string) AuthClient { +func NewAuthClient(host string, bkAppCode string, bkAppSecret string) AuthClient { host = strings.TrimRight(host, "/") return &authClient{ - Host: host, - appCode: appCode, - appSecret: appSecret, + Host: host, + bkAppCode: bkAppCode, + bkAppSecret: bkAppSecret, } } @@ -85,8 +86,8 @@ func (c *authClient) call( request = request.Timeout(callTimeout).Type("json") // set headers - request.Header.Set("X-BK-APP-CODE", c.appCode) - request.Header.Set("X-BK-APP-SECRET", c.appSecret) + request.Header.Set("X-BK-APP-CODE", c.bkAppCode) + request.Header.Set("X-BK-APP-SECRET", c.bkAppSecret) // do request resp, respBody, errs := request. @@ -126,16 +127,16 @@ func (c *authClient) call( } // Verify will check bkAppCode, bkAppSecret is valid -func (c *authClient) Verify(bkAppCode, bkAppSecret string) (bool, error) { +func (c *authClient) Verify(appCode, appSecret string) (bool, error) { errorWrapf := errorx.NewLayerFunctionErrorWrapf("component", "authClient.Verify") - path := fmt.Sprintf("/api/v1/apps/%s/access-keys/verify", bkAppCode) + path := fmt.Sprintf("/api/v1/apps/%s/access-keys/verify", appCode) data, err := c.call(POST, path, map[string]interface{}{ - "bk_app_secret": bkAppSecret, + "bk_app_secret": appSecret, }, 5) if err != nil { - err = errorWrapf(err, "verify app_code=`%s` fail", bkAppCode) + err = errorWrapf(err, "verify app_code=`%s` fail", appCode) return false, err } diff --git a/pkg/component/init.go b/pkg/component/init.go index 4b7658f4..33d4492a 100644 --- a/pkg/component/init.go +++ b/pkg/component/init.go @@ -39,8 +39,8 @@ func InitBkRemoteResourceClient() { BkRemoteResource = NewRemoteResourceClient() } -func InitBkAuthClient(bkAuthHost, appCode, appSecret string) { - BkAuth = NewAuthClient(bkAuthHost, appCode, appSecret) +func InitBkAuthClient(bkAuthHost, bkAppCode, bkAppSecret string) { + BkAuth = NewAuthClient(bkAuthHost, bkAppCode, bkAppSecret) } // CallbackFunc ... diff --git a/pkg/config/config.go b/pkg/config/config.go index 8ea29408..58ef5f25 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -191,11 +191,6 @@ func Load(v *viper.Viper) (*Config, error) { for _, host := range cfg.Hosts { cfg.HostMap[host.ID] = host } - if cfg.EnableBkAuth { - if len(cfg.HostMap) == 0 { - return nil, errors.New("hosts cannot be empty") - } - } // 4. init quota cfg.CustomQuotasMap = make(map[string]Quota) From afaab8ad7c8176e32fa751e86b8f079025bdf1da Mon Sep 17 00:00:00 2001 From: wklken Date: Wed, 12 Jan 2022 16:52:12 +0800 Subject: [PATCH 6/6] chore(copyright): add copyright --- pkg/component/auth.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/pkg/component/auth.go b/pkg/component/auth.go index 9a3342e5..30170893 100644 --- a/pkg/component/auth.go +++ b/pkg/component/auth.go @@ -1,3 +1,13 @@ +/* + * TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available. + * Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. + * You may obtain a copy of the License at http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + package component import (