Skip to content

Commit

Permalink
Merge pull request #202 from xujianhai666/feat-tokencs
Browse files Browse the repository at this point in the history
Add token support
  • Loading branch information
AlexStocks authored Sep 18, 2019
2 parents ef14088 + 0888326 commit a977cc9
Show file tree
Hide file tree
Showing 11 changed files with 186 additions and 6 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ Finished List:
- Configure Center: Zookeeper
- Cluster Strategy: Failover/[Failfast](https://github.com/apache/dubbo-go/pull/140)/[Failsafe/Failback](https://github.com/apache/dubbo-go/pull/136)/[Available](https://github.com/apache/dubbo-go/pull/155)/[Broadcast](https://github.com/apache/dubbo-go/pull/158)/[Forking](https://github.com/apache/dubbo-go/pull/161)
- Load Balance: Random/[RoundRobin](https://github.com/apache/dubbo-go/pull/66)/[LeastActive](https://github.com/apache/dubbo-go/pull/65)
- Filter: Echo Health Check/[Circuit break and service downgrade](https://github.com/apache/dubbo-go/pull/133)
- Filter: Echo Health Check/[Circuit break and service downgrade](https://github.com/apache/dubbo-go/pull/133)/[TokenFilter](https://github.com/apache/dubbo-go/pull/202)
- Other feature: [generic invoke](https://github.com/apache/dubbo-go/pull/122)/start check/connecting certain provider/multi-protocols/multi-registries/multi-versions/service group

Working List:

- Load Balance: ConsistentHash
- Filter: TokenFilter/AccessLogFilter/CountFilter/ExecuteLimitFilter/TpsLimitFilter
- Filter: AccessLogFilter/CountFilter/ExecuteLimitFilter/TpsLimitFilter
- Registry: k8s
- Configure Center: apollo
- Dynamic Configuration Center & Metadata Center (dubbo v2.7.x)
Expand Down
4 changes: 2 additions & 2 deletions README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@ Apache License, Version 2.0
- 配置中心: Zookeeper
- 集群策略: Failover/[Failfast](https://github.com/apache/dubbo-go/pull/140)/[Failsafe/Failback](https://github.com/apache/dubbo-go/pull/136)/[Available](https://github.com/apache/dubbo-go/pull/155)/[Broadcast](https://github.com/apache/dubbo-go/pull/158)/[Forking](https://github.com/apache/dubbo-go/pull/161)
- 负载均衡策略: Random/[RoundRobin](https://github.com/apache/dubbo-go/pull/66)/[LeastActive](https://github.com/apache/dubbo-go/pull/65)
- 过滤器: Echo Health Check/[服务熔断&降级](https://github.com/apache/dubbo-go/pull/133)
- 过滤器: Echo Health Check/[服务熔断&降级](https://github.com/apache/dubbo-go/pull/133)/[TokenFilter](https://github.com/apache/dubbo-go/pull/202)
- 其他功能支持: [泛化调用](https://github.com/apache/dubbo-go/pull/122)/启动时检查/服务直连/多服务协议/多注册中心/多服务版本/服务分组

开发中列表:

- 集群策略: Forking
- 负载均衡策略: ConsistentHash
- 过滤器: TokenFilter/AccessLogFilter/CountFilter/ExecuteLimitFilter/TpsLimitFilter
- 过滤器: AccessLogFilter/CountFilter/ExecuteLimitFilter/TpsLimitFilter
- 注册中心: k8s
- 配置中心: apollo
- 动态配置中心 & 元数据中心 (dubbo v2.7.x)
Expand Down
2 changes: 1 addition & 1 deletion common/constant/default.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const (
const (
DEFAULT_KEY = "default"
PREFIX_DEFAULT_KEY = "default."
DEFAULT_SERVICE_FILTERS = "echo"
DEFAULT_SERVICE_FILTERS = "echo,token"
DEFAULT_REFERENCE_FILTERS = ""
GENERIC_REFERENCE_FILTERS = "generic"
GENERIC = "$invoke"
Expand Down
1 change: 1 addition & 0 deletions common/constant/key.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const (
BEAN_NAME_KEY = "bean.name"
GENERIC_KEY = "generic"
CLASSIFIER_KEY = "classifier"
TOKEN_KEY = "token"
)

const (
Expand Down
13 changes: 13 additions & 0 deletions common/url.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import (
"github.com/dubbogo/gost/container"
"github.com/jinzhu/copier"
perrors "github.com/pkg/errors"
"github.com/satori/go.uuid"
)

import (
Expand Down Expand Up @@ -150,6 +151,18 @@ func WithLocation(location string) option {
}
}

func WithToken(token string) option {
return func(url *URL) {
if len(token) > 0 {
value := token
if strings.ToLower(token) == "true" || strings.ToLower(token) == "default" {
value = uuid.NewV4().String()
}
url.SetParam(constant.TOKEN_KEY, value)
}
}
}

func NewURLWithOptions(opts ...option) *URL {
url := &URL{}
for _, opt := range opts {
Expand Down
6 changes: 5 additions & 1 deletion config/service_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ type ServiceConfig struct {
Warmup string `yaml:"warmup" json:"warmup,omitempty" property:"warmup"`
Retries string `yaml:"retries" json:"retries,omitempty" property:"retries"`
Params map[string]string `yaml:"params" json:"params,omitempty" property:"params"`
Token string `yaml:"token" json:"token,omitempty" property:"token"`
unexported *atomic.Bool
exported *atomic.Bool
rpcService common.RPCService
Expand Down Expand Up @@ -122,7 +123,10 @@ func (srvconfig *ServiceConfig) Export() error {
common.WithPort(proto.Port),
common.WithParams(urlMap),
common.WithParamsValue(constant.BEAN_NAME_KEY, srvconfig.id),
common.WithMethods(strings.Split(methods, ",")))
common.WithMethods(strings.Split(methods, ",")),
common.WithToken(srvconfig.Token),
)

if len(regUrls) > 0 {
for _, regUrl := range regUrls {
regUrl.SubURL = url
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ services:
- name: "GetUser"
retries: "1"
loadbalance: "random"
token: "true"

protocols:
"dubbo":
Expand Down
66 changes: 66 additions & 0 deletions filter/impl/token_filter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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 impl

import (
"strings"
)

import (
perrors "github.com/pkg/errors"
)

import (
"github.com/apache/dubbo-go/common/constant"
"github.com/apache/dubbo-go/common/extension"
"github.com/apache/dubbo-go/filter"
"github.com/apache/dubbo-go/protocol"
)

const (
TOKEN = "token"
)

func init() {
extension.SetFilter(TOKEN, GetTokenFilter)
}

type TokenFilter struct{}

func (tf *TokenFilter) Invoke(invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
invokerTkn := invoker.GetUrl().GetParam(constant.TOKEN_KEY, "")
if len(invokerTkn) > 0 {
attachs := invocation.Attachments()
remoteTkn, exist := attachs[constant.TOKEN_KEY]
if exist && strings.EqualFold(invokerTkn, remoteTkn) {
return invoker.Invoke(invocation)
}
return &protocol.RPCResult{Err: perrors.Errorf("Invalid token! Forbid invoke remote service %v method %s ",
invoker, invocation.MethodName())}
}

return invoker.Invoke(invocation)
}

func (tf *TokenFilter) OnResponse(result protocol.Result, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
return result
}

func GetTokenFilter() filter.Filter {
return &TokenFilter{}
}
85 changes: 85 additions & 0 deletions filter/impl/token_filter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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 impl

import (
"net/url"
"testing"
)

import (
"github.com/stretchr/testify/assert"
)

import (
"github.com/apache/dubbo-go/common"
"github.com/apache/dubbo-go/common/constant"
"github.com/apache/dubbo-go/protocol"
"github.com/apache/dubbo-go/protocol/invocation"
)

func TestTokenFilter_Invoke(t *testing.T) {
filter := GetTokenFilter()

url := common.NewURLWithOptions(
common.WithParams(url.Values{}),
common.WithParamsValue(constant.TOKEN_KEY, "ori_key"))
attch := make(map[string]string, 0)
attch[constant.TOKEN_KEY] = "ori_key"
result := filter.Invoke(protocol.NewBaseInvoker(*url),
invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch))
assert.Nil(t, result.Error())
assert.Nil(t, result.Result())
}

func TestTokenFilter_InvokeEmptyToken(t *testing.T) {
filter := GetTokenFilter()

url := common.URL{}
attch := make(map[string]string, 0)
attch[constant.TOKEN_KEY] = "ori_key"
result := filter.Invoke(protocol.NewBaseInvoker(url),
invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch))
assert.Nil(t, result.Error())
assert.Nil(t, result.Result())
}

func TestTokenFilter_InvokeEmptyAttach(t *testing.T) {
filter := GetTokenFilter()

url := common.NewURLWithOptions(
common.WithParams(url.Values{}),
common.WithParamsValue(constant.TOKEN_KEY, "ori_key"))
attch := make(map[string]string, 0)
result := filter.Invoke(protocol.NewBaseInvoker(*url),
invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch))
assert.NotNil(t, result.Error())
}

func TestTokenFilter_InvokeNotEqual(t *testing.T) {
filter := GetTokenFilter()

url := common.NewURLWithOptions(
common.WithParams(url.Values{}),
common.WithParamsValue(constant.TOKEN_KEY, "ori_key"))
attch := make(map[string]string, 0)
attch[constant.TOKEN_KEY] = "err_key"
result := filter.Invoke(protocol.NewBaseInvoker(*url),
invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch))
assert.NotNil(t, result.Error())
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ require (
github.com/pkg/errors v0.8.1
github.com/prometheus/client_golang v1.1.0 // indirect
github.com/samuel/go-zookeeper v0.0.0-20180130194729-c4fab1ac1bec
github.com/satori/go.uuid v1.2.0
github.com/smartystreets/goconvey v0.0.0-20190710185942-9d28bd7c0945 // indirect
github.com/soheilhy/cmux v0.1.4 // indirect
github.com/stretchr/testify v1.3.0
Expand Down
9 changes: 9 additions & 0 deletions protocol/dubbo/dubbo_invoker.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ import (

var Err_No_Reply = perrors.New("request need @response")

var (
attachmentKey = []string{constant.INTERFACE_KEY, constant.GROUP_KEY, constant.TOKEN_KEY, constant.TIMEOUT_KEY}
)

type DubboInvoker struct {
protocol.BaseInvoker
client *Client
Expand All @@ -57,6 +61,11 @@ func (di *DubboInvoker) Invoke(invocation protocol.Invocation) protocol.Result {
)

inv := invocation.(*invocation_impl.RPCInvocation)
for _, k := range attachmentKey {
if v := di.GetUrl().GetParam(k, ""); len(v) > 0 {
inv.SetAttachments(k, v)
}
}
url := di.GetUrl()
// async
async, err := strconv.ParseBool(inv.AttachmentsByKey(constant.ASYNC_KEY, "false"))
Expand Down

0 comments on commit a977cc9

Please sign in to comment.