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

feature.Make client auth service pluggable. #505

Open
wants to merge 1 commit 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
55 changes: 30 additions & 25 deletions common/constant/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@

package constant

import "time"
import (
"time"

"github.com/nacos-group/nacos-sdk-go/v2/model"
)

type ServerConfig struct {
Scheme string // the nacos server scheme,default=http,this is not required in 2.0
Expand All @@ -27,30 +31,31 @@ type ServerConfig struct {
}

type ClientConfig struct {
TimeoutMs uint64 // timeout for requesting Nacos server, default value is 10000ms
ListenInterval uint64 // Deprecated
BeatInterval int64 // the time interval for sending beat to server,default value is 5000ms
NamespaceId string // the namespaceId of Nacos.When namespace is public, fill in the blank string here.
AppName string // the appName
AppKey string // the client identity information
Endpoint string // the endpoint for get Nacos server addresses
RegionId string // the regionId for kms
AccessKey string // the AccessKey for kms
SecretKey string // the SecretKey for kms
OpenKMS bool // it's to open kms,default is false. https://help.aliyun.com/product/28933.html
CacheDir string // the directory for persist nacos service info,default value is current path
UpdateThreadNum int // the number of gorutine for update nacos service info,default value is 20
NotLoadCacheAtStart bool // not to load persistent nacos service info in CacheDir at start time
UpdateCacheWhenEmpty bool // update cache when get empty service instance from server
Username string // the username for nacos auth
Password string // the password for nacos auth
LogDir string // the directory for log, default is current path
LogLevel string // the level of log, it's must be debug,info,warn,error, default value is info
ContextPath string // the nacos server contextpath
AppendToStdout bool // if append log to stdout
LogSampling *ClientLogSamplingConfig // the sampling config of log
LogRollingConfig *ClientLogRollingConfig // log rolling config
TLSCfg TLSConfig // tls Config
TimeoutMs uint64 // timeout for requesting Nacos server, default value is 10000ms
ListenInterval uint64 // Deprecated
BeatInterval int64 // the time interval for sending beat to server,default value is 5000ms
NamespaceId string // the namespaceId of Nacos.When namespace is public, fill in the blank string here.
AppName string // the appName
AppKey string // the client identity information
Endpoint string // the endpoint for get Nacos server addresses
RegionId string // the regionId for kms
AccessKey string // the AccessKey for kms
SecretKey string // the SecretKey for kms
OpenKMS bool // it's to open kms,default is false. https://help.aliyun.com/product/28933.html
CacheDir string // the directory for persist nacos service info,default value is current path
UpdateThreadNum int // the number of gorutine for update nacos service info,default value is 20
NotLoadCacheAtStart bool // not to load persistent nacos service info in CacheDir at start time
UpdateCacheWhenEmpty bool // update cache when get empty service instance from server
Username string // the username for nacos auth
Password string // the password for nacos auth
LogDir string // the directory for log, default is current path
LogLevel string // the level of log, it's must be debug,info,warn,error, default value is info
ContextPath string // the nacos server contextpath
AppendToStdout bool // if append log to stdout
LogSampling *ClientLogSamplingConfig // the sampling config of log
LogRollingConfig *ClientLogRollingConfig // log rolling config
TLSCfg TLSConfig // tls Config
AuthServices []model.ClientAuthService // client auth services
}

type ClientLogSamplingConfig struct {
Expand Down
1 change: 1 addition & 0 deletions common/constant/const.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,5 @@ const (
HTTPS_SERVER_PORT = 443
GRPC = "grpc"
FAILOVER_FILE_SUFFIX = "_failover"
AUTH_MANAGER_STARTED = 1
)
22 changes: 13 additions & 9 deletions common/nacos_server/nacos_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import (

type NacosServer struct {
sync.RWMutex
securityLogin security.AuthClient
securityManager *security.AuthClientDelegate
serverList []constant.ServerConfig
httpAgent http_agent.IHttpAgent
timeoutMs uint64
Expand All @@ -66,11 +66,14 @@ func NewNacosServer(serverList []constant.ServerConfig, clientCfg constant.Clien
return &NacosServer{}, errors.New("both serverlist and endpoint are empty")
}

services := clientCfg.AuthServices
// always add default auth client
securityLogin := security.NewAuthClient(clientCfg, serverList, httpAgent)

services = append(services, &securityLogin)
securityManager := security.NewAuthClientDelegate(services)
ns := NacosServer{
serverList: serverList,
securityLogin: securityLogin,
securityManager: securityManager,
httpAgent: httpAgent,
timeoutMs: timeoutMs,
endpoint: endpoint,
Expand All @@ -83,13 +86,12 @@ func NewNacosServer(serverList []constant.ServerConfig, clientCfg constant.Clien
}

ns.initRefreshSrvIfNeed()
_, err := securityLogin.Login()
err := securityManager.Login()

if err != nil {
return &ns, err
}

securityLogin.AutoRefresh()
securityManager.StartAutoRefresh()
return &ns, nil
}

Expand Down Expand Up @@ -324,9 +326,11 @@ func (server *NacosServer) GetServerList() []constant.ServerConfig {
}

func (server *NacosServer) InjectSecurityInfo(param map[string]string) {
accessToken := server.securityLogin.GetAccessToken()
if accessToken != "" {
param[constant.KEY_ACCESS_TOKEN] = accessToken
content := server.securityManager.GetAllContent()
if len(content) > 0 {
for k, v := range content {
param[k] = v
}
}
}

Expand Down
105 changes: 105 additions & 0 deletions common/security/security_delegate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 security

import (
"fmt"
"sync/atomic"

"github.com/nacos-group/nacos-sdk-go/v2/common/logger"

"github.com/nacos-group/nacos-sdk-go/v2/common/constant"

"github.com/nacos-group/nacos-sdk-go/v2/model"
)

type AuthClientDelegate struct {
authServices []model.ClientAuthService
status int32
}

// NewAuthClientDelegate create new AuthDelegate with authService
func NewAuthClientDelegate(authServices []model.ClientAuthService) *AuthClientDelegate {
if len(authServices) == 0 {
logger.Warn("there is no client auth service using to create auth client delegate")
}
return &AuthClientDelegate{
authServices: authServices,
}
}

// Login to login all auth services
func (manager *AuthClientDelegate) Login() error {
size := len(manager.authServices)
if size == 0 {
logger.Warn("there is no client auth service")
return nil
}
for i := 0; i < size; i++ {
service := manager.authServices[i]
login, err := service.Login()
if !login {
logger.Error(fmt.Sprintf("%s had logined fail.becase of %v", service.Name(), err))
}
if err != nil {
return err
}
}
return nil
}

// GetAllContent collect all auth service content
func (manager *AuthClientDelegate) GetAllContent() map[string]string {
result := make(map[string]string)
for _, as := range manager.authServices {
content := as.GetLoginContent()
if len(content) > 0 {
for k, v := range content {
if _, ok := result[k]; ok {
logger.Warn(fmt.Sprintf("some auth service contain the same content key!the same key is %s", k))
}
result[k] = v
}
}
}
return result
}

// AddNewAuthService add new auth service to manager
func (manager *AuthClientDelegate) AddNewAuthService(service model.ClientAuthService) {
manager.authServices = append(manager.authServices, service)
if manager.status == constant.AUTH_MANAGER_STARTED {
// if auth client has start refresh,the new ClientAuthService should start auto refresh too.
go func() {
service.AutoRefresh()
}()
}
}

// StartAutoRefresh start fresh auth service,this func won't spin to refresh content, it only trigger all auth service's auth refresh func.
func (manager *AuthClientDelegate) StartAutoRefresh() {
// ensure refresh only once.
if atomic.LoadInt32(&manager.status) == constant.AUTH_MANAGER_STARTED {
return
}
atomic.StoreInt32(&manager.status, constant.AUTH_MANAGER_STARTED)
go func() {
for _, as := range manager.authServices {
as.AutoRefresh()
}
}()
}
101 changes: 101 additions & 0 deletions common/security/security_delegate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 security

import (
"fmt"
"strconv"
"sync/atomic"
"testing"
"time"

"github.com/stretchr/testify/assert"

"github.com/nacos-group/nacos-sdk-go/v2/common/logger"

"github.com/nacos-group/nacos-sdk-go/v2/model"
)

// TestAuthClientManager create and use auth client manager
func TestAuthClientManager(t *testing.T) {
// create new auth manager
macs := &MockAuthClientService{name: "first"}
service := []model.ClientAuthService{macs}
acm := NewAuthClientDelegate(service)

// login all client auth service
err := acm.Login()
assert.Nil(t, err)

// get all auth content
content := acm.GetAllContent()
assert.NotNil(t, content)
assert.Equal(t, 1, len(content))
assert.Equal(t, content["count"], "1")

// start auto refresh
acm.StartAutoRefresh()
time.Sleep(time.Second * 5)

// assert the result will be the correct after sleep
content2 := acm.GetAllContent()
assert.True(t, content2["count"] == "5")

// add new auth service
newMacs := &MockAuthClientService{count: 10, name: "second"}
acm.AddNewAuthService(newMacs)
time.Sleep(time.Second * 1)
// check if the content will be covered when content key is same.
content3 := acm.GetAllContent()
assert.NotNil(t, content3)
assert.Equal(t, 1, len(content3))
assert.Equal(t, content3["count"], "10")
}

// MockAuthClientService mock for test
type MockAuthClientService struct {
count int32
name string
}

func (macs *MockAuthClientService) Name() string {
return macs.name
}

func (macs *MockAuthClientService) Login() (bool, error) {
logger.Info("start login with mock auth client")
atomic.AddInt32(&macs.count, 1)
return true, nil
}

func (macs *MockAuthClientService) GetLoginContent() model.LoginContent {
r := atomic.LoadInt32(&macs.count)
c := strconv.Itoa(int(r))
return map[string]string{
"count": c,
}
}

func (macs *MockAuthClientService) AutoRefresh() {
go func() {
for {
time.Sleep(time.Second)
logger.Info(fmt.Sprintf("start refresh:%s", macs.Name()))
macs.Login()
}
}()
}
12 changes: 12 additions & 0 deletions common/security/security_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import (
"sync/atomic"
"time"

"github.com/nacos-group/nacos-sdk-go/v2/model"

"github.com/pkg/errors"

"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
Expand Down Expand Up @@ -160,3 +162,13 @@ func (ac *AuthClient) login(server constant.ServerConfig) (bool, error) {
return true, nil

}

func (ac *AuthClient) GetLoginContent() model.LoginContent {
result := make(map[string]string)
result[constant.KEY_ACCESS_TOKEN] = ac.GetAccessToken()
return result
}

func (ac *AuthClient) Name() string {
return "default security auth service"
}
28 changes: 28 additions & 0 deletions model/auth_service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 model

// ClientAuthService the interface of security proxy
type ClientAuthService interface {
Name() string
Login() (bool, error)
GetLoginContent() LoginContent
AutoRefresh()
}

// LoginContent the content of login operation.
type LoginContent map[string]string