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

feat:auth filter #303

Merged
merged 28 commits into from
Dec 3, 2021
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
dc81628
feat:auth filter
baerwang Nov 21, 2021
d2cea76
style: test set request headers
baerwang Nov 21, 2021
13f6ea1
Merge branch 'develop' into develop
baerwang Nov 21, 2021
b4a85f0
fix: go fmt
MasterKenway Nov 21, 2021
74966a4
Merge pull request #1 from MasterKenway/feat/auth-filter
baerwang Nov 21, 2021
d4b7567
feat: upgrade golint version
MasterKenway Nov 21, 2021
47f924e
Merge branch 'develop' into develop
mark4z Nov 21, 2021
8592dc6
Merge pull request #2 from MasterKenway/feat/auth-filter
baerwang Nov 21, 2021
4a85345
style: variable naming
baerwang Nov 22, 2021
17cbc49
fix:variable naming
baerwang Nov 22, 2021
b6134f9
style:FromHeaders set default Authorization: Bearer <token>
baerwang Nov 22, 2021
85af2ed
Merge branch 'develop' into develop
baerwang Nov 23, 2021
be9660b
feat:custom auth error msg
baerwang Nov 24, 2021
e6fbdcf
feat:springcloud integration auth filter
baerwang Nov 26, 2021
350152c
Merge remote-tracking branch 'origin/develop' into develop
baerwang Nov 26, 2021
c28b5b8
fix:mod conflict
baerwang Nov 26, 2021
0f9715f
Merge branch 'develop' into develop
baerwang Nov 26, 2021
fcc47bd
fix:go fmt
baerwang Nov 26, 2021
b6023dc
docs:auth filter
baerwang Nov 26, 2021
cb16ad0
style: clean up commented code
baerwang Nov 26, 2021
64b35a3
add valid any/all function annotation
baerwang Nov 28, 2021
9dec3a3
Merge branch 'develop' into develop
AlexStocks Nov 29, 2021
839abf8
fix: valid router
baerwang Dec 1, 2021
f560714
Merge remote-tracking branch 'origin/develop' into develop
baerwang Dec 1, 2021
8aa1ce0
Merge branch 'develop' into develop
baerwang Dec 1, 2021
c27ed56
style: not need to next
baerwang Dec 1, 2021
7cd11ca
Merge branch 'develop' into develop
ztelur Dec 2, 2021
3ad4abe
fix:inexplicable mod
baerwang Dec 2, 2021
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
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/apache/dubbo-go-pixiu
go 1.14

require (
github.com/MicahParks/keyfunc v0.10.0
github.com/alibaba/sentinel-golang v1.0.2
github.com/apache/dubbo-go v1.5.7
github.com/apache/dubbo-go-hessian2 v1.9.5
Expand All @@ -16,6 +17,7 @@ require (
github.com/go-resty/resty/v2 v2.3.0
github.com/gogo/protobuf v1.3.2
github.com/goinggo/mapstructure v0.0.0-20140717182941-194205d9b4a9
github.com/golang-jwt/jwt/v4 v4.1.0
github.com/golang/protobuf v1.5.2
github.com/google/uuid v1.2.0 // indirect
github.com/jhump/protoreflect v1.9.0
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym
github.com/DataDog/datadog-go v2.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
github.com/MicahParks/keyfunc v0.10.0 h1:jWNhUVtMchsdYVl714lrZL8On+SKPEvPKC+CpIN7HwE=
github.com/MicahParks/keyfunc v0.10.0/go.mod h1:R8RZa27qn+5cHTfYLJ9/+7aSb5JIdz7cl0XFo0o4muo=
github.com/Microsoft/go-winio v0.4.3/go.mod h1:VhR8bwka0BXejwEJY73c50VrPtXAaKcyvVC4A4RozmA=
github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ=
github.com/NYTimes/gziphandler v1.0.1/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ=
Expand Down Expand Up @@ -296,6 +298,8 @@ github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69
github.com/goinggo/mapstructure v0.0.0-20140717182941-194205d9b4a9 h1:wqckanyE9qc/XnvnybC6SHOb8Nyd62QXAZOzA8twFig=
github.com/goinggo/mapstructure v0.0.0-20140717182941-194205d9b4a9/go.mod h1:64ikIrMv84B+raz7akXOqbF7cK3/OQQ/6cClY10oy7A=
github.com/goji/httpauth v0.0.0-20160601135302-2da839ab0f4d/go.mod h1:nnjvkQ9ptGaCkuDUx6wNykzzlUixGxvkme+H/lnzb+A=
github.com/golang-jwt/jwt/v4 v4.1.0 h1:XUgk2Ex5veyVFVeLm0xhusUTQybEbexJXrvPNOKkSY0=
github.com/golang-jwt/jwt/v4 v4.1.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
Expand Down
1 change: 1 addition & 0 deletions pkg/common/constant/key.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ const (
HTTPApiConfigFilter = "dgp.filter.http.apiconfig"
HTTPTimeoutFilter = "dgp.filter.http.timeout"
TracingFilter = "dgp.filters.tracing"
HTTPAuthJwtFilter = "dgp.filter.http.auth.jwt"
HTTPCorsFilter = "dgp.filter.http.cors"
HTTPCsrfFilter = "dgp.filter.http.csrf"
HTTPProxyRewriteFilter = "dgp.filter.http.proxyrewrite"
Expand Down
76 changes: 76 additions & 0 deletions pkg/filter/auth/jwt/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* 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 jwt

import "github.com/MicahParks/keyfunc"

type (
// FromHeaders Get the token from a field in the header,default Authorization: Bearer <token>
FromHeaders struct {
Name string `yaml:"name" json:"name" mapstructure:"name"`
ValuePrefix string `yaml:"value_prefix" json:"value_prefix" mapstructure:"value_prefix"`
}

Rules struct {
Match Match `yaml:"match" json:"match" mapstructure:"match"`
Requires Requires `yaml:"requires" json:"requires" mapstructure:"requires"`
}

Match struct {
Prefix string `yaml:"prefix" json:"prefix" mapstructure:"prefix"`
}

Requires struct {
RequiresAny Requirement `yaml:"requires_any" json:"requires_any" mapstructure:"requires_any"`
RequiresAll []Requirement `yaml:"requires_all" json:"requires_all" mapstructure:"requires_all"`
}

Requirement struct {
ProviderName string `yaml:"provider_name" json:"provider_name" mapstructure:"provider_name"`
}

Providers struct {
Name string `yaml:"name" json:"name" mapstructure:"name"`
ForwardPayloadHeader string `yaml:"forward_payload_header" json:"forward_payload_header" mapstructure:"forward_payload_header"`
FromHeaders FromHeaders `yaml:"from_headers" json:"from_headers" mapstructure:"from_headers"`
Issuer string `yaml:"issuer" json:"issuer" mapstructure:"issuer"`
Local *Local `yaml:"local_jwks" json:"local_jwks" mapstructure:"local_jwks"`
Remote *Remote `yaml:"remote_jwks" json:"remote_jwks" mapstructure:"remote_jwks"`
}

Local struct {
InlineString string `yaml:"inline_string" json:"inline_string" mapstructure:"inline_string"`
}

Remote struct {
HttpUri HttpUri `yaml:"http_uri" json:"http_uri" mapstructure:"http_uri"`
}

HttpUri struct {
baerwang marked this conversation as resolved.
Show resolved Hide resolved
Uri string `yaml:"uri" json:"uri" mapstructure:"uri"`
Cluster string `yaml:"cluster" json:"cluster" mapstructure:"cluster"`
TimeOut string `default:"5s" yaml:"timeout" json:"timeout" mapstructure:"timeout"`
}
)

type Provider struct {
jwk *keyfunc.JWKs
issuer string
forwardPayloadHeader string
headers FromHeaders
}
205 changes: 205 additions & 0 deletions pkg/filter/auth/jwt/jwt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
/*
* 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 jwt

import (
"encoding/json"
"fmt"
stdHttp "net/http"
"strings"
"time"
)

import (
"github.com/MicahParks/keyfunc"
jwt4 "github.com/golang-jwt/jwt/v4"
)

import (
"github.com/apache/dubbo-go-pixiu/pkg/common/constant"
"github.com/apache/dubbo-go-pixiu/pkg/common/extension/filter"
"github.com/apache/dubbo-go-pixiu/pkg/context/http"
"github.com/apache/dubbo-go-pixiu/pkg/logger"
)

const (
Kind = constant.HTTPAuthJwtFilter
)

var (
tokenError, _ = json.Marshal(http.ErrResponse{Message: "token invalid"})
)

func init() {
filter.RegisterHttpFilter(&Plugin{})
}

type (
// Plugin is http filter plugin.
Plugin struct {
}

// Filter is http filter instance
Filter struct {
cfg *Config
providerJwks map[string]Provider
}

// Config describe the config of Filter
Config struct {
Rules []Rules `yaml:"rules" json:"rules" mapstructure:"rules"`
Providers []Providers `yaml:"providers" json:"providers" mapstructure:"providers"`
}
)

func (p Plugin) Kind() string {
return Kind
}

func (p *Plugin) CreateFilter() (filter.HttpFilter, error) {
return &Filter{cfg: &Config{}, providerJwks: map[string]Provider{}}, nil
}

func (f *Filter) PrepareFilterChain(ctx *http.HttpContext) error {
ctx.AppendFilterFunc(f.Handle)
return nil
}

func (f *Filter) Handle(ctx *http.HttpContext) {

path := ctx.Request.RequestURI

router := false

for _, rule := range f.cfg.Rules {
if strings.HasPrefix(path, rule.Match.Prefix) {
router = true
if f.validAny(rule, ctx) || f.validAll(rule, ctx) {
ctx.Next()
baerwang marked this conversation as resolved.
Show resolved Hide resolved
break
}
}
}

if router {
baerwang marked this conversation as resolved.
Show resolved Hide resolved
ctx.WriteJSONWithStatus(stdHttp.StatusUnauthorized, tokenError)
ctx.Abort()
return
}

ctx.Next()

}

func valuePrefix(value, prefix string) string {
if prefix == "" {
return value
}
return strings.TrimPrefix(value, prefix)
}

func (f *Filter) validAny(rule Rules, ctx *http.HttpContext) bool {

providerName := rule.Requires.RequiresAny.ProviderName

if provider, ok := f.providerJwks[providerName]; ok {
ctx.Request.Header.Set(provider.forwardPayloadHeader, provider.issuer)
if key := ctx.Request.Header.Get(provider.headers.Name); key != "" {
token, err := jwt4.Parse(valuePrefix(key, provider.headers.ValuePrefix), provider.jwk.Keyfunc)
if err != nil {
logger.Warnf("failed to parse JWKs from JSON. provider:%s Error: %s", providerName, err.Error())
return false
}
return token.Valid
}
}

return false
baerwang marked this conversation as resolved.
Show resolved Hide resolved
}

func (f *Filter) validAll(rule Rules, ctx *http.HttpContext) bool {

for _, requirement := range rule.Requires.RequiresAll {
if provider, ok := f.providerJwks[requirement.ProviderName]; ok {
ctx.Request.Header.Set(provider.forwardPayloadHeader, provider.issuer)
if key := ctx.Request.Header.Get(provider.headers.Name); key != "" {
token, err := jwt4.Parse(valuePrefix(key, provider.headers.ValuePrefix), provider.jwk.Keyfunc)
if err != nil {
logger.Warnf("failed to parse JWKs from JSON. provider:%s Error: %s", requirement.ProviderName, err.Error())
continue
}

if token.Valid {
return true
}
}
}
}

return false
}

func (f *Filter) Apply() error {

if len(f.cfg.Providers) == 0 {
return fmt.Errorf("providers is null")
}

for _, provider := range f.cfg.Providers {

if provider.Local != nil {
jwksJSON := json.RawMessage(provider.Local.InlineString)
jwks, err := keyfunc.NewJSON(jwksJSON)
if err != nil {
logger.Warnf("failed to create JWKs from JSON. provider:%s Error: %s", provider.Name, err.Error())
} else {
f.providerJwks[provider.Name] = Provider{jwk: jwks, headers: provider.FromHeaders,
issuer: provider.Issuer, forwardPayloadHeader: provider.ForwardPayloadHeader}
continue
}
}

if provider.Remote != nil {
uri := provider.Remote.HttpUri
timeout, err := time.ParseDuration(uri.TimeOut)
if err != nil {
logger.Warnf("jwt provides timeout parse fail: %s", err.Error())
continue
}

options := keyfunc.Options{RefreshTimeout: timeout}
jwks, err := keyfunc.Get(uri.Uri, options)
if err != nil {
logger.Warnf("failed to create JWKs from resource at the given URL. provider:%s Error: %s", provider.Name, err.Error())
} else {
f.providerJwks[provider.Name] = Provider{jwk: jwks, headers: provider.FromHeaders,
issuer: provider.Issuer, forwardPayloadHeader: provider.ForwardPayloadHeader}
}
}
}

if len(f.providerJwks) == 0 {
return fmt.Errorf("providers is null")
}

return nil
}

func (f *Filter) Config() interface{} {
return f.cfg
}
1 change: 1 addition & 0 deletions pkg/pluginregistry/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
_ "github.com/apache/dubbo-go-pixiu/pkg/filter/network/httpconnectionmanager"
// http filters
_ "github.com/apache/dubbo-go-pixiu/pkg/filter/accesslog"
_ "github.com/apache/dubbo-go-pixiu/pkg/filter/auth/jwt"
_ "github.com/apache/dubbo-go-pixiu/pkg/filter/authority"
_ "github.com/apache/dubbo-go-pixiu/pkg/filter/cors"
_ "github.com/apache/dubbo-go-pixiu/pkg/filter/csrf"
Expand Down
Loading