Skip to content

Commit

Permalink
Merge 72f9170 into bdc3f32
Browse files Browse the repository at this point in the history
  • Loading branch information
zouyx committed May 27, 2020
2 parents bdc3f32 + 72f9170 commit 6583903
Show file tree
Hide file tree
Showing 12 changed files with 204 additions and 6 deletions.
8 changes: 6 additions & 2 deletions component/notify/componet_notify.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,9 @@ func notifyRemoteConfig(newAppConfig *config.AppConfig, namespace string, isAsyn
//seelog.Debugf("allNotifications.getNotifies():%s",allNotifications.getNotifies())

connectConfig := &env.ConnectConfig{
URI: urlSuffix,
URI: urlSuffix,
AppID: appConfig.AppID,
Secret: appConfig.Secret,
}
if !isAsync {
connectConfig.Timeout = syncNofityConnectTimeout
Expand Down Expand Up @@ -278,7 +280,9 @@ func autoSyncNamespaceConfigServices(newAppConfig *config.AppConfig, allNotifica
urlSuffix := component.GetConfigURLSuffix(appConfig, namespace)

_, err = http.RequestRecovery(appConfig, &env.ConnectConfig{
URI: urlSuffix,
URI: urlSuffix,
AppID: appConfig.AppID,
Secret: appConfig.Secret,
}, &http.CallBack{
SuccessCallBack: AutoSyncConfigServicesSuccessCallBack,
NotModifyCallBack: touchApolloConfigCache,
Expand Down
5 changes: 4 additions & 1 deletion component/serverlist/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,10 @@ func SyncServerIPList(newAppConfig *config.AppConfig) error {
panic("can not find apollo config!please confirm!")
}

_, err := http.Request(env.GetServicesConfigURL(appConfig), &env.ConnectConfig{}, &http.CallBack{
_, err := http.Request(env.GetServicesConfigURL(appConfig), &env.ConnectConfig{
AppID: appConfig.AppID,
Secret: appConfig.Secret,
}, &http.CallBack{
SuccessCallBack: env.SyncServerIPListSuccessCallBack,
})

Expand Down
1 change: 1 addition & 0 deletions env/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ type AppConfig struct {
NextTryConnTime int64 `json:"-"`
IsBackupConfig bool `default:"true" json:"isBackupConfig"`
BackupConfigPath string `json:"backupConfigPath"`
Secret string `json:"secret"`
}

//ServerInfo 服务器信息
Expand Down
4 changes: 4 additions & 0 deletions env/request_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,8 @@ type ConnectConfig struct {
URI string
//是否重试
IsRetry bool
//appID
AppID string
//密钥
Secret string
}
22 changes: 22 additions & 0 deletions extension/sgin_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package extension

import (
"testing"

. "github.com/tevid/gohamcrest"
)

type TestAuth struct{}

func (a *TestAuth) HTTPHeaders(url string, appID string, secret string) map[string][]string {
return nil
}

func TestSetHttpAuth(t *testing.T) {
SetHTTPAuth(&TestAuth{})

a := GetHTTPAuth()

b := a.(*TestAuth)
Assert(t, b, NotNilVal())
}
17 changes: 17 additions & 0 deletions extension/sign.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package extension

import (
"github.com/zouyx/agollo/v3/protocol/auth"
)

var authSign auth.HTTPAuth

// SetHTTPAuth 设置HttpAuth
func SetHTTPAuth(httpAuth auth.HTTPAuth) {
authSign = httpAuth
}

// GetHTTPAuth 获取HttpAuth
func GetHTTPAuth() auth.HTTPAuth {
return authSign
}
7 changes: 7 additions & 0 deletions protocol/auth/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package auth

// HTTPAuth http 授权
type HTTPAuth interface {
// HTTPHeaders 根据 @url 获取 http 授权请求头
HTTPHeaders(url string, appID string, secret string) map[string][]string
}
70 changes: 70 additions & 0 deletions protocol/auth/sign/sign.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package sign

import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"github.com/zouyx/agollo/v3/extension"
"net/url"
"strconv"
"time"
)

const (
httpHeaderAuthorization = "Authorization"
httpHeaderTimestamp = "Timestamp"

authorizationFormat = "Apollo %s:%s"

delimiter = "\n"
question = "?"
)

func init() {
extension.SetHTTPAuth(&AuthSignature{})
}

// AuthSignature apollo 授权
type AuthSignature struct {
}

// HTTPHeaders HTTPHeaders
func (t *AuthSignature) HTTPHeaders(url string, appID string, secret string) map[string][]string {
ms := time.Now().UnixNano() / int64(time.Millisecond)
timestamp := strconv.FormatInt(ms, 10)
pathWithQuery := url2PathWithQuery(url)

stringToSign := timestamp + delimiter + pathWithQuery
signature := signString(stringToSign, secret)
headers := make(map[string][]string, 2)

signatures := make([]string, 0, 1)
signatures = append(signatures, fmt.Sprintf(authorizationFormat, appID, signature))
headers[httpHeaderAuthorization] = signatures

timestamps := make([]string, 0, 1)
timestamps = append(timestamps, timestamp)
headers[httpHeaderTimestamp] = timestamps
return headers
}

func signString(stringToSign string, accessKeySecret string) string {
key := []byte(accessKeySecret)
mac := hmac.New(sha1.New, key)
mac.Write([]byte(stringToSign))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}

func url2PathWithQuery(rawURL string) string {
u, err := url.Parse(rawURL)
if err != nil {
return ""
}
pathWithQuery := u.Path

if len(u.RawQuery) > 0 {
pathWithQuery += question + u.RawQuery
}
return pathWithQuery
}
32 changes: 32 additions & 0 deletions protocol/auth/sign/sign_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package sign

import (
. "github.com/tevid/gohamcrest"
"testing"
)

const (
rawURL = "http://baidu.com/a/b?key=1"
secret = "6ce3ff7e96a24335a9634fe9abca6d51"
appID = "testApplication_yang"
)

func TestSignString(t *testing.T) {
s := signString(rawURL, secret)
Assert(t, s, Equal("mcS95GXa7CpCjIfrbxgjKr0lRu8="))
}

func TestUrl2PathWithQuery(t *testing.T) {

pathWithQuery := url2PathWithQuery(rawURL)

Assert(t, pathWithQuery, Equal("/a/b?key=1"))
}

func TestHttpHeaders(t *testing.T) {
a := &AuthSignature{}
headers := a.HTTPHeaders(rawURL, appID, secret)

Assert(t, headers, HasMapValue("Authorization"))
Assert(t, headers, HasMapValue("Timestamp"))
}
20 changes: 17 additions & 3 deletions protocol/http/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,23 @@ func Request(requestURL string, connectionConfig *env.ConnectConfig, callBack *C
if retry > retries {
break
}
req, err := http.NewRequest("GET", requestURL, nil)
if req == nil || err != nil {
log.Error("Generate connect Apollo request Fail,url:%s,Error:%s", requestURL, err)
// if error then sleep
return nil, errors.New("generate connect Apollo request fail")
}

//增加header选项
httpAuth := extension.GetHTTPAuth()
if httpAuth != nil {
headers := httpAuth.HTTPHeaders(requestURL, connectionConfig.AppID, connectionConfig.Secret)
if len(headers) > 0 {
req.Header = headers
}
}

res, err = client.Get(requestURL)
res, err = client.Do(req)

if res == nil || err != nil {
log.Error("Connect Apollo Server Fail,url:%s,Error:%s", requestURL, err)
Expand Down Expand Up @@ -88,15 +103,14 @@ func Request(requestURL string, connectionConfig *env.ConnectConfig, callBack *C
return nil, nil
default:
log.Error("Connect Apollo Server Fail,url:%s,StatusCode:%s", requestURL, res.StatusCode)
err = errors.New("connect Apollo Server Fail")
// if error then sleep
time.Sleep(onErrorRetryInterval)
continue
}
}

log.Error("Over Max Retry Still Error,Error:", err)
if err != nil {
if retry > retries {
err = errors.New("over Max Retry Still Error")
}
return nil, err
Expand Down
9 changes: 9 additions & 0 deletions start.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import (
"github.com/zouyx/agollo/v3/env/file"
_ "github.com/zouyx/agollo/v3/env/file/json"
"github.com/zouyx/agollo/v3/extension"
"github.com/zouyx/agollo/v3/protocol/auth"
_ "github.com/zouyx/agollo/v3/protocol/auth/sign"
"github.com/zouyx/agollo/v3/storage"
)

Expand All @@ -31,6 +33,13 @@ func Start() error {
return startAgollo()
}

//SetSignature 设置自定义 http 授权控件
func SetSignature(auth auth.HTTPAuth) {
if auth != nil {
extension.SetHTTPAuth(auth)
}
}

//SetBackupFileHandler 设置自定义备份文件处理组件
func SetBackupFileHandler(file file.FileHandler) {
if file != nil {
Expand Down
15 changes: 15 additions & 0 deletions start_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,18 @@ func TestSetBackupFileHandler(t *testing.T) {
SetBackupFileHandler(t2)
Assert(t, t2, Equal(extension.GetFileHandler()))
}

type TestAuth struct{}

func (a *TestAuth) HTTPHeaders(url string, appID string, secret string) map[string][]string {
return nil
}

func TestSetSignature(t *testing.T) {
Assert(t, extension.GetHTTPAuth(), NotNilVal())

t2 := &TestAuth{}
SetSignature(t2)

Assert(t, t2, Equal(extension.GetHTTPAuth()))
}

0 comments on commit 6583903

Please sign in to comment.