Merge branch 'MSP-1069' into 'master'
Resolve MSP-1069 Closes MSP-1069 See merge request integration-system/isp-gate-service!12
This commit is contained in:
commit
2ab43de749
17 files changed
+177
-105
No files matched your search
@@ -1,3 +1,5 @@
|
||||
### v4.0.0
|
||||
* реализована аутентификация токена администратора через msp-admin-service
|
||||
### v3.0.3
|
||||
* исправлено тело ответа grpc ошибок валидации
|
||||
* обновлены зависимости
|
||||
|
||||
+13
-4
@@ -3,6 +3,9 @@ package assembly
|
||||
import (
|
||||
"context"
|
||||
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/routes"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
"github.com/integration-system/isp-kit/app"
|
||||
"github.com/integration-system/isp-kit/bootstrap"
|
||||
@@ -12,8 +15,6 @@ import (
|
||||
"github.com/integration-system/isp-kit/lb"
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/pkg/errors"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/routes"
|
||||
)
|
||||
|
||||
type Assembly struct {
|
||||
@@ -23,6 +24,7 @@ type Assembly struct {
|
||||
routes *routes.Routes
|
||||
redisCli redis.UniversalClient
|
||||
systemCli *client.Client
|
||||
adminCli *client.Client
|
||||
|
||||
locations []conf.Location
|
||||
grpcClientByModuleName map[string]*client.Client
|
||||
@@ -61,6 +63,11 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
||||
return nil, errors.WithMessage(err, "create system cli")
|
||||
}
|
||||
|
||||
adminCli, err := client.Default()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "create admin cli")
|
||||
}
|
||||
|
||||
return &Assembly{
|
||||
boot: boot,
|
||||
server: server,
|
||||
@@ -70,6 +77,7 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
||||
grpcClientByModuleName: grpcClientByModuleName,
|
||||
httpHostManagerByModuleName: httpHostManagerByModuleName,
|
||||
systemCli: systemCli,
|
||||
adminCli: adminCli,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -94,7 +102,7 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error
|
||||
newRedisCli = a.redisClient(*newCfg.Redis)
|
||||
}
|
||||
|
||||
locator := NewLocator(a.logger, a.grpcClientByModuleName, a.httpHostManagerByModuleName, a.routes, a.systemCli)
|
||||
locator := NewLocator(a.logger, a.grpcClientByModuleName, a.httpHostManagerByModuleName, a.routes, a.systemCli, a.adminCli)
|
||||
|
||||
handler, err := locator.Handler(newCfg, a.locations, newRedisCli)
|
||||
if err != nil {
|
||||
@@ -124,6 +132,7 @@ func (a *Assembly) Runners() []app.Runner {
|
||||
}
|
||||
|
||||
eventHandler.RequireModule("isp-system-service", a.systemCli)
|
||||
eventHandler.RequireModule("msp-admin-service", a.adminCli)
|
||||
|
||||
return []app.Runner{
|
||||
app.RunnerFunc(func(ctx context.Context) error {
|
||||
@@ -145,7 +154,7 @@ func (a *Assembly) Closers() []app.Closer {
|
||||
for _, cliCloser := range a.grpcClientByModuleName {
|
||||
closers = append(closers, cliCloser)
|
||||
}
|
||||
closers = append(closers, a.systemCli, app.CloserFunc(func() error {
|
||||
closers = append(closers, a.systemCli, a.adminCli, app.CloserFunc(func() error {
|
||||
if a.redisCli != nil {
|
||||
return a.redisCli.Close()
|
||||
}
|
||||
|
||||
+11
-6
@@ -5,17 +5,18 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
"github.com/integration-system/isp-kit/grpc/client"
|
||||
"github.com/integration-system/isp-kit/lb"
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/pkg/errors"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/middleware"
|
||||
"isp-gate-service/proxy"
|
||||
"isp-gate-service/repository"
|
||||
"isp-gate-service/routes"
|
||||
"isp-gate-service/service"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
"github.com/integration-system/isp-kit/grpc/client"
|
||||
"github.com/integration-system/isp-kit/lb"
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type Locator struct {
|
||||
@@ -24,6 +25,7 @@ type Locator struct {
|
||||
httpHostManagerByModuleName map[string]*lb.RoundRobin
|
||||
routes *routes.Routes
|
||||
systemCli *client.Client
|
||||
adminCli *client.Client
|
||||
}
|
||||
|
||||
func NewLocator(
|
||||
@@ -32,6 +34,7 @@ func NewLocator(
|
||||
httpHostManagerByModuleName map[string]*lb.RoundRobin,
|
||||
routes *routes.Routes,
|
||||
systemCli *client.Client,
|
||||
adminCli *client.Client,
|
||||
) Locator {
|
||||
return Locator{
|
||||
logger: logger,
|
||||
@@ -39,16 +42,18 @@ func NewLocator(
|
||||
httpHostManagerByModuleName: httpHostManagerByModuleName,
|
||||
routes: routes,
|
||||
systemCli: systemCli,
|
||||
adminCli: adminCli,
|
||||
}
|
||||
}
|
||||
|
||||
func (l Locator) Handler(config conf.Remote, locations []conf.Location, redisCli redis.UniversalClient) (http.Handler, error) {
|
||||
systemRepo := repository.NewSystem(l.systemCli)
|
||||
adminRepo := repository.NewAdmin(l.adminCli)
|
||||
|
||||
authenticationCache := repository.NewAuthenticationCache(time.Duration(config.Caching.AuthenticationDataInSec) * time.Second)
|
||||
authentication := service.NewAuthentication(authenticationCache, systemRepo)
|
||||
|
||||
adminService := service.NewAdmin(config.Secrets.AdminTokenSecret)
|
||||
adminService := service.NewAdmin(adminRepo)
|
||||
|
||||
authorizationCache := repository.NewAuthorizationCache(time.Duration(config.Caching.AuthorizationDataInSec) * time.Second)
|
||||
authorization := service.NewAuthorization(authorizationCache, systemRepo)
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
{
|
||||
"secrets": {
|
||||
"adminTokenSecret": "{{ msp_admin_secret }}"
|
||||
},
|
||||
"logging": {
|
||||
"logLevel": "debug",
|
||||
"requestLogEnable": true,
|
||||
|
||||
@@ -18,7 +18,6 @@ func init() {
|
||||
|
||||
type Remote struct {
|
||||
Redis *Redis `schema:"Настройки Redis,обязательно, если используется механизм суточных ограничений или ограничений пропускной способности"`
|
||||
Secrets Secrets `schema:"Настройки секретов"`
|
||||
Http Http `schema:"Настройки HTTP"`
|
||||
Logging Logging `schema:"Настройки логирования"`
|
||||
Caching Caching `schema:"Настройки кеширования"`
|
||||
@@ -26,10 +25,6 @@ type Remote struct {
|
||||
Throttling []Throttling `schema:"Настройки пропускной способности"`
|
||||
}
|
||||
|
||||
type Secrets struct {
|
||||
AdminTokenSecret string `valid:"required" schema:"Секрет токена администратора"`
|
||||
}
|
||||
|
||||
type Http struct {
|
||||
MaxRequestBodySizeInMb int64 `valid:"required" schema:"Максимальная длинна тела запроса,в мегабайтах"`
|
||||
ProxyTimeoutInSec int `valid:"required" schema:"Таймаут на проксирование,в секундах"`
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package domain
|
||||
|
||||
type AdminAuthenticateResponse struct {
|
||||
Authenticated bool
|
||||
ErrorReason string
|
||||
AdminId int
|
||||
}
|
||||
@@ -6,9 +6,8 @@ require (
|
||||
github.com/go-redis/redis/v8 v8.11.5
|
||||
github.com/go-redis/redis_rate/v9 v9.1.2
|
||||
github.com/go-resty/resty/v2 v2.7.0
|
||||
github.com/golang-jwt/jwt/v4 v4.4.2
|
||||
github.com/google/uuid v1.1.2
|
||||
github.com/integration-system/isp-kit v1.11.0
|
||||
github.com/integration-system/isp-kit v1.12.0
|
||||
github.com/integration-system/jsonschema v1.0.1
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/stretchr/testify v1.8.0
|
||||
@@ -56,7 +55,6 @@ require (
|
||||
go.uber.org/atomic v1.10.0 // indirect
|
||||
go.uber.org/multierr v1.8.0 // indirect
|
||||
go.uber.org/zap v1.23.0 // indirect
|
||||
golang.org/x/sync v0.0.0-20220923202941-7f9b1623fab7 // indirect
|
||||
golang.org/x/sys v0.0.0-20220926163933-8cfa568d3c25 // indirect
|
||||
golang.org/x/text v0.3.7 // indirect
|
||||
google.golang.org/protobuf v1.28.1 // indirect
|
||||
|
||||
@@ -114,8 +114,6 @@ github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6Wezm
|
||||
github.com/gobwas/ws v1.0.2 h1:CoAavW/wd/kulfZmSIBt6p24n4j7tHgNVCjsfHVNUbo=
|
||||
github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM=
|
||||
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
|
||||
github.com/golang-jwt/jwt/v4 v4.4.2 h1:rcc4lwaZgFMCZ5jxF9ABolDcIHdBytAFgqFPbSJQAYs=
|
||||
github.com/golang-jwt/jwt/v4 v4.4.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
@@ -193,8 +191,8 @@ github.com/integration-system/bellows v1.0.1/go.mod h1:qHPg1ptN3AHHr0f/wvoicfA2L
|
||||
github.com/integration-system/grmq v1.2.0 h1:wD2dQ2ds8n/2nAivrjVU+iyLFT4izGnFbJGcstjrBto=
|
||||
github.com/integration-system/isp-etp-go/v2 v2.1.3 h1:vcHP/PE7p1G3rxqoVKrKtXzoSxFA4ryxigd+zPkAb3w=
|
||||
github.com/integration-system/isp-etp-go/v2 v2.1.3/go.mod h1:ZpB+FIH3hy7md+f8ylVSQx5zwZVjczhkc45f1B2z9nw=
|
||||
github.com/integration-system/isp-kit v1.11.0 h1:tnQ+AYJXphNvvsP5tTFgBiLrD3zVqrw9n20mc8K1h9I=
|
||||
github.com/integration-system/isp-kit v1.11.0/go.mod h1:a3KYQMsma05ZxPnogojzf0uyiqsbc83x0+4v6B9OlEQ=
|
||||
github.com/integration-system/isp-kit v1.12.0 h1:ULf3CBH4fulA5VbsFT4kUnc4Q64vsPCB5yS6sbiDRvc=
|
||||
github.com/integration-system/isp-kit v1.12.0/go.mod h1:5wHdXzI8fWeZQbPfQdel5Jnf0zZ3R+KnYdat/NN0RRo=
|
||||
github.com/integration-system/jsonschema v1.0.1 h1:nR78BEDG9djX2uXQ1YP66a/9yQOMmp2HFmw8VPUdAa8=
|
||||
github.com/integration-system/jsonschema v1.0.1/go.mod h1:EoqDH7RmC8Epg5EgjboIxDo7Udv3WX2exGqtIVB4hI0=
|
||||
github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4=
|
||||
@@ -345,7 +343,7 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
|
||||
golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90 h1:Y/gsMcFOcR+6S6f3YeMKl5g+dZMEWqcz5Czj/GWYbkM=
|
||||
golang.org/x/crypto v0.0.0-20220919173607-35f4265a4bc0 h1:a5Yg6ylndHHYJqIPrdq0AhvR6KTvDTAvgBtaidhEevY=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
||||
@@ -439,8 +437,6 @@ golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJ
|
||||
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220923202941-7f9b1623fab7 h1:ZrnxWX62AgTKOSagEqxvb3ffipvEDX2pl7E1TdqLqIc=
|
||||
golang.org/x/sync v0.0.0-20220923202941-7f9b1623fab7/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"isp-gate-service/domain"
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -14,7 +17,7 @@ const (
|
||||
)
|
||||
|
||||
type AdminAuthenticator interface {
|
||||
Authenticate(token string) (int, error)
|
||||
AdminAuthenticate(ctx context.Context, token string) (*domain.AdminAuthenticateResponse, error)
|
||||
}
|
||||
|
||||
func AdminAuthenticate(auth AdminAuthenticator) Middleware {
|
||||
@@ -24,7 +27,7 @@ func AdminAuthenticate(auth AdminAuthenticator) Middleware {
|
||||
if adminToken == "" {
|
||||
return next.Handle(ctx)
|
||||
}
|
||||
adminId, err := auth.Authenticate(adminToken)
|
||||
resp, err := auth.AdminAuthenticate(ctx.Context(), adminToken)
|
||||
if err != nil {
|
||||
return httperrors.New(
|
||||
http.StatusUnauthorized,
|
||||
@@ -32,7 +35,14 @@ func AdminAuthenticate(auth AdminAuthenticator) Middleware {
|
||||
errors.WithMessage(err, "admin authenticate: authenticate"),
|
||||
)
|
||||
}
|
||||
ctx.AuthenticateAdmin(adminId, adminToken)
|
||||
if !resp.Authenticated {
|
||||
return httperrors.New(
|
||||
http.StatusUnauthorized,
|
||||
"invalid admin token",
|
||||
errors.WithMessage(errors.New(resp.ErrorReason), "admin authenticate: authenticate"),
|
||||
)
|
||||
}
|
||||
ctx.AuthenticateAdmin(resp.AdminId, adminToken)
|
||||
return next.Handle(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
package proxy
|
||||
|
||||
const (
|
||||
xAdminIdHeader = "x-admin-id"
|
||||
)
|
||||
+4
-7
@@ -7,6 +7,9 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
|
||||
"github.com/integration-system/isp-kit/grpc"
|
||||
"github.com/integration-system/isp-kit/grpc/client"
|
||||
"github.com/integration-system/isp-kit/grpc/isp"
|
||||
@@ -17,12 +20,6 @@ import (
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
)
|
||||
|
||||
const (
|
||||
adminAuthHeader = "x-auth-admin"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -84,7 +81,7 @@ func (p Grpc) Handle(ctx *request.Context) error {
|
||||
md[grpc.ServiceIdHeader] = []string{strconv.Itoa(authData.ServiceId)}
|
||||
md[grpc.ApplicationIdHeader] = []string{strconv.Itoa(authData.ApplicationId)}
|
||||
if ctx.IsAdminAuthenticated() {
|
||||
md[adminAuthHeader] = []string{ctx.AdminToken()}
|
||||
md[xAdminIdHeader] = []string{strconv.Itoa(ctx.AdminId())}
|
||||
}
|
||||
}
|
||||
requestContext := metadata.NewOutgoingContext(ctx.Context(), md)
|
||||
|
||||
+6
-3
@@ -8,12 +8,13 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
|
||||
"github.com/integration-system/isp-kit/grpc"
|
||||
"github.com/integration-system/isp-kit/requestid"
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/net/context"
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
)
|
||||
|
||||
type HttpHostManager interface {
|
||||
@@ -59,7 +60,9 @@ func (p Http) Handle(ctx *request.Context) error {
|
||||
request.Header.Set(grpc.ServiceIdHeader, strconv.Itoa(authData.ServiceId))
|
||||
request.Header.Set(grpc.ApplicationIdHeader, strconv.Itoa(authData.ApplicationId))
|
||||
if ctx.IsAdminAuthenticated() {
|
||||
request.Header.Set(adminAuthHeader, ctx.AdminToken())
|
||||
request.Header.Set(xAdminIdHeader, strconv.Itoa(ctx.AdminId()))
|
||||
} else {
|
||||
request.Header.Del(xAdminIdHeader)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"isp-gate-service/domain"
|
||||
|
||||
"github.com/integration-system/isp-kit/grpc/client"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
adminAuthenticate = "admin/secure/authenticate"
|
||||
)
|
||||
|
||||
type Admin struct {
|
||||
cli *client.Client
|
||||
}
|
||||
|
||||
func NewAdmin(cli *client.Client) Admin {
|
||||
return Admin{cli: cli}
|
||||
}
|
||||
|
||||
func (r Admin) Authenticate(ctx context.Context, token string) (*domain.AdminAuthenticateResponse, error) {
|
||||
resp := domain.AdminAuthenticateResponse{}
|
||||
err := r.cli.Invoke(adminAuthenticate).
|
||||
JsonRequestBody(domain.AuthenticateRequest{Token: token}).
|
||||
ReadJsonResponse(&resp).
|
||||
Do(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "grpc client invoke %s", adminAuthenticate)
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
+12
-36
@@ -1,54 +1,30 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
"context"
|
||||
"isp-gate-service/domain"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type adminClaims struct {
|
||||
*jwt.RegisteredClaims
|
||||
Id int64
|
||||
type AdminAuth interface {
|
||||
Authenticate(ctx context.Context, token string) (*domain.AdminAuthenticateResponse, error)
|
||||
}
|
||||
|
||||
type Admin struct {
|
||||
secret string
|
||||
admin AdminAuth
|
||||
}
|
||||
|
||||
func NewAdmin(secret string) Admin {
|
||||
func NewAdmin(adminAuth AdminAuth) Admin {
|
||||
return Admin{
|
||||
secret: secret,
|
||||
admin: adminAuth,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Admin) Authenticate(token string) (int, error) {
|
||||
parsed, err := s.parseToken(token, &adminClaims{RegisteredClaims: &jwt.RegisteredClaims{}})
|
||||
func (s Admin) AdminAuthenticate(ctx context.Context, token string) (*domain.AdminAuthenticateResponse, error) {
|
||||
resp, err := s.admin.Authenticate(ctx, token)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessage(err, "parse token")
|
||||
return nil, errors.WithMessage(err, "get admin token data from admin service")
|
||||
}
|
||||
|
||||
claims, ok := parsed.Claims.(*adminClaims)
|
||||
if !ok {
|
||||
return 0, errors.New("invalid token")
|
||||
}
|
||||
|
||||
return int(claims.Id), nil
|
||||
}
|
||||
|
||||
func (s Admin) parseToken(token string, claims jwt.Claims) (*jwt.Token, error) {
|
||||
parsed, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
|
||||
_, ok := token.Method.(*jwt.SigningMethodHMAC)
|
||||
if !ok {
|
||||
return nil, errors.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
|
||||
return []byte(s.secret), nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "jwt parse with claims")
|
||||
}
|
||||
if !parsed.Valid {
|
||||
return nil, errors.New("invalid token")
|
||||
}
|
||||
|
||||
return parsed, nil
|
||||
return resp, nil
|
||||
}
|
||||
+38
-11
@@ -8,6 +8,11 @@ import (
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"isp-gate-service/assembly"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/domain"
|
||||
"isp-gate-service/routes"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
"github.com/go-resty/resty/v2"
|
||||
"github.com/google/uuid"
|
||||
@@ -20,10 +25,7 @@ import (
|
||||
"github.com/integration-system/isp-kit/test/grpct"
|
||||
"github.com/integration-system/isp-kit/test/httpt"
|
||||
"github.com/stretchr/testify/suite"
|
||||
"isp-gate-service/assembly"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/domain"
|
||||
"isp-gate-service/routes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
type request struct {
|
||||
@@ -40,7 +42,7 @@ type HappyPathTestSuite struct {
|
||||
|
||||
func (s *HappyPathTestSuite) TestGrpcProxy() {
|
||||
test, require := test.New(s.T())
|
||||
config, redisCli, systemCli := s.commonDependencies(test)
|
||||
config, redisCli, systemCli, adminCli := s.commonDependencies(test)
|
||||
|
||||
requestId := requestid.Next()
|
||||
targetService, targetCli := grpct.NewMock(test)
|
||||
@@ -58,12 +60,18 @@ func (s *HappyPathTestSuite) TestGrpcProxy() {
|
||||
require.EqualValues(2, domainId)
|
||||
require.EqualValues(3, serviceId)
|
||||
require.EqualValues(4, applicationId)
|
||||
|
||||
adminId, err := grpc.StringFromMd("x-admin-id", metadata.MD(authData))
|
||||
require.NoError(err)
|
||||
require.EqualValues("1", adminId)
|
||||
|
||||
return response{Id: req.Id} //nolint:gosimple
|
||||
})
|
||||
targetClients := map[string]*client.Client{"target": targetCli}
|
||||
logger, err := log.New(log.WithLevel(log.DebugLevel))
|
||||
require.NoError(err)
|
||||
locator := assembly.NewLocator(logger, targetClients, nil, routes.NewRoutes(), systemCli)
|
||||
locator := assembly.NewLocator(logger, targetClients, nil, routes.NewRoutes(), systemCli, adminCli)
|
||||
|
||||
locations := []conf.Location{{
|
||||
SkipAuth: false,
|
||||
PathPrefix: "/api",
|
||||
@@ -80,6 +88,7 @@ func (s *HappyPathTestSuite) TestGrpcProxy() {
|
||||
_, err = cli.R().
|
||||
SetHeader("x-application-token", "token").
|
||||
SetHeader("x-request-id", requestId).
|
||||
SetHeader("x-auth-admin", "mock-token").
|
||||
SetBody(req).
|
||||
SetResult(&resp).
|
||||
Post("/api/endpoint")
|
||||
@@ -89,7 +98,7 @@ func (s *HappyPathTestSuite) TestGrpcProxy() {
|
||||
|
||||
func (s *HappyPathTestSuite) TestHttpProxy() {
|
||||
test, require := test.New(s.T())
|
||||
config, redisCli, systemCli := s.commonDependencies(test)
|
||||
config, redisCli, systemCli, adminCli := s.commonDependencies(test)
|
||||
|
||||
requestId := requestid.Next()
|
||||
targetService := httpt.NewMock(test)
|
||||
@@ -107,13 +116,18 @@ func (s *HappyPathTestSuite) TestHttpProxy() {
|
||||
require.EqualValues(2, domainId)
|
||||
require.EqualValues(3, serviceId)
|
||||
require.EqualValues(4, applicationId)
|
||||
|
||||
adminId, err := strconv.Atoi(httpReq.Header.Get("x-admin-id"))
|
||||
require.NoError(err)
|
||||
require.EqualValues(1, adminId)
|
||||
|
||||
return response{Id: req.Id} //nolint:gosimple
|
||||
})
|
||||
targetUrl, err := url.Parse(targetService.BaseURL())
|
||||
require.NoError(err)
|
||||
rr := lb.NewRoundRobin([]string{targetUrl.Host})
|
||||
targetClients := map[string]*lb.RoundRobin{"target": rr}
|
||||
locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes.NewRoutes(), systemCli)
|
||||
locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes.NewRoutes(), systemCli, adminCli)
|
||||
locations := []conf.Location{{
|
||||
SkipAuth: false,
|
||||
PathPrefix: "/api",
|
||||
@@ -130,6 +144,7 @@ func (s *HappyPathTestSuite) TestHttpProxy() {
|
||||
_, err = cli.R().
|
||||
SetHeader("x-application-token", "token").
|
||||
SetHeader("x-request-id", requestId).
|
||||
SetHeader("x-auth-admin", "mock-token").
|
||||
SetBody(req).
|
||||
SetResult(&resp).
|
||||
Post("/api/endpoint")
|
||||
@@ -137,10 +152,11 @@ func (s *HappyPathTestSuite) TestHttpProxy() {
|
||||
require.EqualValues(req.Id, resp.Id)
|
||||
}
|
||||
|
||||
func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, redis.UniversalClient, *client.Client) {
|
||||
func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, redis.UniversalClient, *client.Client, *client.Client) {
|
||||
require := test.Assert()
|
||||
redisCli := NewRedis(test)
|
||||
ctx := context.Background()
|
||||
|
||||
s.T().Cleanup(func() {
|
||||
_, err := redisCli.Pipelined(ctx, func(p redis.Pipeliner) error {
|
||||
p.Select(ctx, 0)
|
||||
@@ -153,15 +169,16 @@ func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, r
|
||||
})
|
||||
require.NoError(err)
|
||||
})
|
||||
|
||||
config := conf.Remote{
|
||||
Redis: &conf.Redis{Address: redisCli.address},
|
||||
Secrets: conf.Secrets{AdminTokenSecret: "secret"},
|
||||
Http: conf.Http{MaxRequestBodySizeInMb: 1, ProxyTimeoutInSec: 15},
|
||||
Logging: conf.Logging{LogLevel: log.DebugLevel, RequestLogEnable: true, BodyLogEnable: true},
|
||||
Caching: conf.Caching{AuthorizationDataInSec: 1, AuthenticationDataInSec: 1},
|
||||
DailyLimits: []conf.DailyLimit{{ApplicationId: 1, RequestsPerDay: 100}},
|
||||
Throttling: []conf.Throttling{{ApplicationId: 1, RequestsPerSeconds: 100}},
|
||||
}
|
||||
|
||||
systemService, systemCli := grpct.NewMock(test)
|
||||
systemService.Mock("system/secure/authenticate", func() domain.AuthenticateResponse {
|
||||
return domain.AuthenticateResponse{
|
||||
@@ -177,7 +194,17 @@ func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, r
|
||||
}).Mock("system/secure/authorize", func() domain.AuthorizeResponse {
|
||||
return domain.AuthorizeResponse{Authorized: true}
|
||||
})
|
||||
return config, redisCli, systemCli
|
||||
|
||||
adminService, adminCli := grpct.NewMock(test)
|
||||
adminService.Mock("admin/secure/authenticate", func() domain.AdminAuthenticateResponse {
|
||||
return domain.AdminAuthenticateResponse{
|
||||
Authenticated: true,
|
||||
ErrorReason: "",
|
||||
AdminId: 1,
|
||||
}
|
||||
})
|
||||
|
||||
return config, redisCli, systemCli, adminCli
|
||||
}
|
||||
|
||||
func TestHappyPathTestSuite(t *testing.T) {
|
||||
|
||||
+27
-15
@@ -5,16 +5,17 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
|
||||
"isp-gate-service/assembly"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/domain"
|
||||
"isp-gate-service/routes"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
"github.com/integration-system/isp-kit/grpc"
|
||||
"github.com/integration-system/isp-kit/grpc/client"
|
||||
endpoint2 "github.com/integration-system/isp-kit/grpc/endpoint"
|
||||
"github.com/integration-system/isp-kit/grpc/isp"
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"isp-gate-service/assembly"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/domain"
|
||||
"isp-gate-service/routes"
|
||||
)
|
||||
|
||||
type request struct {
|
||||
@@ -46,14 +47,14 @@ func main() {
|
||||
}()
|
||||
config := conf.Remote{
|
||||
Redis: &conf.Redis{Address: "localhost:6379"},
|
||||
Secrets: conf.Secrets{AdminTokenSecret: "secret"},
|
||||
Http: conf.Http{MaxRequestBodySizeInMb: 1, ProxyTimeoutInSec: 15},
|
||||
Logging: conf.Logging{LogLevel: log.DebugLevel, RequestLogEnable: true, BodyLogEnable: true},
|
||||
Caching: conf.Caching{AuthorizationDataInSec: 15, AuthenticationDataInSec: 15},
|
||||
DailyLimits: []conf.DailyLimit{{ApplicationId: 1, RequestsPerDay: 100000000}},
|
||||
Throttling: []conf.Throttling{{ApplicationId: 1, RequestsPerSeconds: 5000}},
|
||||
}
|
||||
systemService, systemCli := NewMock(logger)
|
||||
|
||||
systemService, systemCli, _ := NewMock(logger)
|
||||
systemService.Mock("system/secure/authenticate", func() domain.AuthenticateResponse {
|
||||
return domain.AuthenticateResponse{
|
||||
Authenticated: true,
|
||||
@@ -69,13 +70,22 @@ func main() {
|
||||
return domain.AuthorizeResponse{Authorized: true}
|
||||
})
|
||||
|
||||
targetService, targetCli := NewMock(logger)
|
||||
adminService, _, adminCli := NewMock(logger)
|
||||
adminService.Mock("admin/secure/authenticate", func() domain.AdminAuthenticateResponse {
|
||||
return domain.AdminAuthenticateResponse{
|
||||
Authenticated: true,
|
||||
ErrorReason: "",
|
||||
AdminId: 1,
|
||||
}
|
||||
})
|
||||
|
||||
targetService, targetCli, _ := NewMock(logger)
|
||||
targetService.Mock("endpoint", func(req request) response {
|
||||
return response{Id: req.Id}
|
||||
})
|
||||
targetClients := map[string]*client.Client{"target": targetCli}
|
||||
logger, _ = log.New(log.WithLevel(log.DebugLevel))
|
||||
locator := assembly.NewLocator(logger, targetClients, nil, routes.NewRoutes(), systemCli)
|
||||
locator := assembly.NewLocator(logger, targetClients, nil, routes.NewRoutes(), systemCli, adminCli)
|
||||
locations := []conf.Location{{
|
||||
SkipAuth: false,
|
||||
PathPrefix: "/api",
|
||||
@@ -91,17 +101,19 @@ func main() {
|
||||
srv.ListenAndServe()
|
||||
}
|
||||
|
||||
func TestServer(service isp.BackendServiceServer) (*grpc.Server, *client.Client) {
|
||||
func TestServer(service isp.BackendServiceServer) (*grpc.Server, *client.Client, *client.Client) {
|
||||
listener, _ := net.Listen("tcp", "127.0.0.1:")
|
||||
srv := grpc.NewServer()
|
||||
cli, _ := client.Default()
|
||||
sysCli, _ := client.Default()
|
||||
adminCli, _ := client.Default()
|
||||
srv.Upgrade(service)
|
||||
go func() {
|
||||
_ = srv.Serve(listener)
|
||||
}()
|
||||
|
||||
cli.Upgrade([]string{listener.Addr().String()})
|
||||
return srv, cli
|
||||
sysCli.Upgrade([]string{listener.Addr().String()})
|
||||
adminCli.Upgrade([]string{listener.Addr().String()})
|
||||
return srv, sysCli, adminCli
|
||||
}
|
||||
|
||||
type MockServer struct {
|
||||
@@ -110,13 +122,13 @@ type MockServer struct {
|
||||
mockEndpoints map[string]interface{}
|
||||
}
|
||||
|
||||
func NewMock(logger log.Logger) (*MockServer, *client.Client) {
|
||||
srv, cli := TestServer(grpc.NewMux())
|
||||
func NewMock(logger log.Logger) (*MockServer, *client.Client, *client.Client) {
|
||||
srv, syscli, admincli := TestServer(grpc.NewMux())
|
||||
return &MockServer{
|
||||
srv: srv,
|
||||
logger: logger,
|
||||
mockEndpoints: make(map[string]interface{}),
|
||||
}, cli
|
||||
}, syscli, admincli
|
||||
}
|
||||
|
||||
func (m *MockServer) Mock(endpoint string, handler interface{}) *MockServer {
|
||||
|
||||
Reference in new issue
Block a user