ref
This commit is contained in:
1 parent
4fdf7c0ca2
commit
5b115440f1
12 files changed
+115
-89
No files matched your search
@@ -2,56 +2,64 @@ package authenticate
|
||||
|
||||
import (
|
||||
"github.com/integration-system/isp-lib/utils"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"github.com/valyala/fasthttp"
|
||||
"google.golang.org/grpc/codes"
|
||||
"isp-gate-service/log_code"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
verifiableKeyHeaderKeyMap = map[string]string{
|
||||
SystemIdentity: utils.SystemIdHeader,
|
||||
DomainIdentity: utils.DomainIdHeader,
|
||||
ServiceIdentity: utils.ServiceIdHeader,
|
||||
ApplicationIdentity: utils.ApplicationIdHeader,
|
||||
DeviceIdentity: utils.DeviceIdHeader,
|
||||
UserIdentity: utils.UserIdHeader,
|
||||
DeviceToken: utils.DeviceTokenHeader,
|
||||
UserToken: utils.UserTokenHeader,
|
||||
}
|
||||
notExpectedHeaders = []string{
|
||||
utils.SystemIdHeader, utils.DomainIdHeader, utils.ServiceIdHeader, utils.ApplicationIdHeader,
|
||||
systemIdentity: utils.SystemIdHeader,
|
||||
domainIdentity: utils.DomainIdHeader,
|
||||
serviceIdentity: utils.ServiceIdHeader,
|
||||
applicationIdentity: utils.ApplicationIdHeader,
|
||||
}
|
||||
)
|
||||
|
||||
func Do(ctx *fasthttp.RequestCtx) error {
|
||||
for _, notExpectedHeader := range notExpectedHeaders {
|
||||
for _, notExpectedHeader := range verifiableKeyHeaderKeyMap {
|
||||
ctx.Request.Header.Del(notExpectedHeader)
|
||||
}
|
||||
|
||||
appToken := ctx.Request.Header.Peek(utils.ApplicationTokenHeader)
|
||||
if len(appToken) == 0 {
|
||||
return Error.Create(codes.Unauthenticated)
|
||||
return Error.create(codes.Unauthenticated)
|
||||
}
|
||||
verifiableKeys, err := verification.appToken(string(appToken))
|
||||
|
||||
keys, err := verification.appToken(string(appToken))
|
||||
if err != nil {
|
||||
return err
|
||||
log.Error(log_code.ErrorAuthenticate, err)
|
||||
return Error.create(codes.Internal)
|
||||
}
|
||||
if len(verifiableKeys) != 4 {
|
||||
return Error.Create(codes.Unauthenticated)
|
||||
if len(keys) != 4 {
|
||||
return Error.create(codes.Unauthenticated)
|
||||
}
|
||||
|
||||
verifiableKeys := make(map[string]string)
|
||||
for i, value := range keys {
|
||||
verifiableKeys[verifiableKeyHeaderKeyMap[i]] = value
|
||||
}
|
||||
|
||||
uri := strings.Replace(strings.ToLower(string(ctx.Path())), "/", "", -1)
|
||||
verifiableKeys[DeviceToken] = string(ctx.Request.Header.Peek(utils.DeviceTokenHeader))
|
||||
verifiableKeys[UserToken] = string(ctx.Request.Header.Peek(utils.UserTokenHeader))
|
||||
verifiableKeys[utils.DeviceTokenHeader] = string(ctx.Request.Header.Peek(utils.DeviceTokenHeader))
|
||||
verifiableKeys[utils.UserTokenHeader] = string(ctx.Request.Header.Peek(utils.UserTokenHeader))
|
||||
|
||||
verifiableKeys, err = verification.keys(verifiableKeys, uri)
|
||||
if err != nil {
|
||||
return err
|
||||
log.Error(log_code.ErrorAuthenticate, err)
|
||||
return Error.create(codes.Internal)
|
||||
}
|
||||
if verifiableKeys[permittedToCallInfo] == "0" {
|
||||
return Error.create(codes.PermissionDenied)
|
||||
} else {
|
||||
delete(verifiableKeys, permittedToCallInfo)
|
||||
}
|
||||
|
||||
for key, value := range verifiableKeys {
|
||||
if value != "" {
|
||||
ctx.Request.Header.Set(verifiableKeyHeaderKeyMap[key], value)
|
||||
ctx.Request.Header.Set(key, value)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -7,16 +7,15 @@ import (
|
||||
|
||||
var Error errorHelper
|
||||
|
||||
func (errorHelper) Create(status codes.Code) ErrorDescription {
|
||||
type errorHelper struct{}
|
||||
|
||||
func (errorHelper) create(status codes.Code) ErrorDescription {
|
||||
return ErrorDescription{grpcStatus: status}
|
||||
}
|
||||
|
||||
type (
|
||||
errorHelper struct{}
|
||||
ErrorDescription struct {
|
||||
grpcStatus codes.Code
|
||||
}
|
||||
)
|
||||
type ErrorDescription struct {
|
||||
grpcStatus codes.Code
|
||||
}
|
||||
|
||||
func (e ErrorDescription) Error() string {
|
||||
return fmt.Sprintf("%v", e)
|
||||
|
||||
@@ -5,22 +5,19 @@ import (
|
||||
rd "github.com/go-redis/redis"
|
||||
"github.com/integration-system/isp-lib/config"
|
||||
"github.com/integration-system/isp-lib/redis"
|
||||
"google.golang.org/grpc/codes"
|
||||
"github.com/integration-system/isp-lib/utils"
|
||||
"github.com/pkg/errors"
|
||||
"isp-gate-service/conf"
|
||||
rdClient "isp-gate-service/redis"
|
||||
)
|
||||
|
||||
const (
|
||||
SystemIdentity = "1"
|
||||
DomainIdentity = "2"
|
||||
ServiceIdentity = "3"
|
||||
ApplicationIdentity = "4"
|
||||
systemIdentity = "1"
|
||||
domainIdentity = "2"
|
||||
serviceIdentity = "3"
|
||||
applicationIdentity = "4"
|
||||
|
||||
DeviceIdentity = "5"
|
||||
UserIdentity = "6"
|
||||
|
||||
DeviceToken = "7"
|
||||
UserToken = "8"
|
||||
permittedToCallInfo = "permittedToCallInfo"
|
||||
)
|
||||
|
||||
var verification verificationHelper
|
||||
@@ -40,12 +37,12 @@ func (v verificationHelper) appToken(token string) (map[string]string, error) {
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, Error.Create(codes.Internal)
|
||||
return nil, err
|
||||
} else {
|
||||
if len(resp) < 2 || resp[1].Err() == rd.Nil {
|
||||
return nil, nil
|
||||
} else if resp[1].Err() != nil {
|
||||
return nil, Error.Create(codes.Unauthenticated)
|
||||
return nil, err
|
||||
} else if stringStringMapCmd, ok := resp[1].(*rd.StringStringMapCmd); !ok {
|
||||
return nil, nil
|
||||
} else {
|
||||
@@ -55,9 +52,9 @@ func (v verificationHelper) appToken(token string) (map[string]string, error) {
|
||||
}
|
||||
|
||||
func (v *verificationHelper) keys(t map[string]string, uri string) (map[string]string, error) {
|
||||
secondDbKey := fmt.Sprintf("%s|%s", t[ApplicationIdentity], uri)
|
||||
thirdDbKey := fmt.Sprintf("%s|%s", t[UserToken], t[DomainIdentity])
|
||||
fifthDbKey := fmt.Sprintf("%s|%s", t[DeviceToken], t[DomainIdentity])
|
||||
secondDbKey := fmt.Sprintf("%s|%s", t[utils.ApplicationIdHeader], uri)
|
||||
thirdDbKey := fmt.Sprintf("%s|%s", t[utils.UserTokenHeader], t[utils.DomainIdHeader])
|
||||
fifthDbKey := fmt.Sprintf("%s|%s", t[utils.DeviceTokenHeader], t[utils.DomainIdHeader])
|
||||
|
||||
if resp, err := rdClient.Client.Get().Pipelined(func(p rd.Pipeliner) error {
|
||||
if cmd := p.Select(int(redis.ApplicationPermissionDb)); v.notEmptyError(cmd.Err()) {
|
||||
@@ -81,26 +78,26 @@ func (v *verificationHelper) keys(t map[string]string, uri string) (map[string]s
|
||||
return cmd.Err()
|
||||
}
|
||||
return nil
|
||||
}); err != nil && err != rd.Nil {
|
||||
return t, Error.Create(codes.Internal)
|
||||
}); v.notEmptyError(err) {
|
||||
return t, err
|
||||
} else {
|
||||
// It is not permitted to call this methodParts
|
||||
if v.fineCmd(resp, 1) {
|
||||
if intCmd, ok := resp[1].(*rd.IntCmd); ok && intCmd.Val() == 0 {
|
||||
return t, Error.Create(codes.PermissionDenied)
|
||||
}
|
||||
if msg, err := v.findStringCmd(resp, 1); err != nil {
|
||||
return t, err
|
||||
} else {
|
||||
t[permittedToCallInfo] = msg
|
||||
}
|
||||
// ===== CHECK USER TOKEN =====
|
||||
if v.fineCmd(resp, 3) {
|
||||
if stringCmd, ok := resp[3].(*rd.StringCmd); ok {
|
||||
t[UserIdentity] = stringCmd.Val()
|
||||
}
|
||||
if msg, err := v.findStringCmd(resp, 3); err != nil {
|
||||
return t, err
|
||||
} else {
|
||||
t[utils.UserIdHeader] = msg
|
||||
}
|
||||
// ===== CHECK DEVICE TOKEN =====
|
||||
if v.fineCmd(resp, 5) {
|
||||
if stringCmd, ok := resp[5].(*rd.StringCmd); ok {
|
||||
t[DeviceIdentity] = stringCmd.Val()
|
||||
}
|
||||
if msg, err := v.findStringCmd(resp, 5); err != nil {
|
||||
return t, err
|
||||
} else {
|
||||
t[utils.DeviceIdHeader] = msg
|
||||
}
|
||||
}
|
||||
return t, nil
|
||||
@@ -110,11 +107,25 @@ func (v *verificationHelper) notEmptyError(err error) bool {
|
||||
return err != nil && err != rd.Nil
|
||||
}
|
||||
|
||||
func (v *verificationHelper) fineCmd(cmders []rd.Cmder, arrayKey int) bool {
|
||||
if len(cmders) > arrayKey+1 {
|
||||
cmder := cmders[arrayKey]
|
||||
return cmder != nil && (cmder.Err() == nil || cmder.Err() == rd.Nil)
|
||||
func (v *verificationHelper) findStringCmd(cmders []rd.Cmder, arrayKey int) (string, error) {
|
||||
if len(cmders) > arrayKey {
|
||||
cmd := cmders[arrayKey]
|
||||
if cmd != nil {
|
||||
if cmd.Err() != nil {
|
||||
if cmd.Err() == rd.Nil {
|
||||
return "", nil
|
||||
}
|
||||
return "", cmd.Err()
|
||||
}
|
||||
if stringCmd, ok := cmd.(*rd.StringCmd); !ok {
|
||||
return "", errors.New("unexpected type")
|
||||
} else {
|
||||
return stringCmd.Val(), nil
|
||||
}
|
||||
} else {
|
||||
return "", errors.New("empty cmd")
|
||||
}
|
||||
} else {
|
||||
return false
|
||||
return "", errors.New("")
|
||||
}
|
||||
}
|
||||
+22
-16
@@ -18,41 +18,47 @@ const (
|
||||
DefaultMaxResponseBodySize = 32 * MB
|
||||
)
|
||||
|
||||
type RemoteConfig struct {
|
||||
EnableOriginalProtoErrors bool `schema:"Проксирование ошибок в протобаф,включение/отключение проксирования, по умолчанию отключено"`
|
||||
ProxyGrpcErrorDetails bool `schema:"Проксирование первого элемента из details GRPC ошибки,включение/отключение проксирования, по умолчанию отключено"`
|
||||
MultipartDataTransferBufferSizeBytes int64 `schema:"Размер буфера для передачи бинарных файлов,по умолчанию 4 KB"`
|
||||
MaxRequestBodySizeBytes int64 `schema:"Максимальный размер тела запроса,в байтайх, по умолчанию: 512 MB"`
|
||||
SyncInvokeMethodTimeoutMs int64 `schema:"Время ожидания вызова метода,значение в миллисекундах, по умолчанию: 30000"`
|
||||
StreamInvokeMethodTimeoutMs int64 `schema:"Время ожидания передачи и обработки файла,значение в миллисекундах, по умолчанию: 60000"`
|
||||
Metrics structure.MetricConfiguration `schema:"Настройка метрик"`
|
||||
Journal rx.Config `schema:"Настройка логирования"`
|
||||
JournalingMethodsPatterns []string `schema:"Список методов для логирования,список строк вида: 'module/group/method'(* - для частичного совпадения). При обработке запроса, если вызываемый метод совпадает со строкой из списка, тела запроса и ответа записываются в лог"`
|
||||
Redis structure.RedisConfiguration `schema:"Настрока Redis" valid:"required~Required"`
|
||||
}
|
||||
type (
|
||||
RemoteConfig struct {
|
||||
GrpcSetting GrpcSetting
|
||||
Metrics structure.MetricConfiguration `schema:"Настройка метрик"`
|
||||
Journal rx.Config `schema:"Настройка логирования"`
|
||||
JournalingMethodsPatterns []string `schema:"Список методов для логирования,список строк вида: 'module/group/method'(* - для частичного совпадения). При обработке запроса, если вызываемый метод совпадает со строкой из списка, тела запроса и ответа записываются в лог"`
|
||||
Redis structure.RedisConfiguration `schema:"Настрока Redis" valid:"required~Required"`
|
||||
}
|
||||
|
||||
func (cfg RemoteConfig) GetSyncInvokeTimeout() time.Duration {
|
||||
GrpcSetting struct {
|
||||
EnableOriginalProtoErrors bool `schema:"Проксирование ошибок в протобаф,включение/отключение проксирования, по умолчанию отключено"`
|
||||
ProxyGrpcErrorDetails bool `schema:"Проксирование первого элемента из details GRPC ошибки,включение/отключение проксирования, по умолчанию отключено"`
|
||||
MultipartDataTransferBufferSizeBytes int64 `schema:"Размер буфера для передачи бинарных файлов,по умолчанию 4 KB"`
|
||||
MaxRequestBodySizeBytes int64 `schema:"Максимальный размер тела запроса,в байтайх, по умолчанию: 512 MB"`
|
||||
SyncInvokeMethodTimeoutMs int64 `schema:"Время ожидания вызова метода,значение в миллисекундах, по умолчанию: 30000"`
|
||||
StreamInvokeMethodTimeoutMs int64 `schema:"Время ожидания передачи и обработки файла,значение в миллисекундах, по умолчанию: 60000"`
|
||||
}
|
||||
)
|
||||
|
||||
func (cfg GrpcSetting) GetSyncInvokeTimeout() time.Duration {
|
||||
if cfg.SyncInvokeMethodTimeoutMs <= 0 {
|
||||
return defaultSyncTimeout
|
||||
}
|
||||
return time.Duration(cfg.SyncInvokeMethodTimeoutMs) * time.Millisecond
|
||||
}
|
||||
|
||||
func (cfg RemoteConfig) GetStreamInvokeTimeout() time.Duration {
|
||||
func (cfg GrpcSetting) GetStreamInvokeTimeout() time.Duration {
|
||||
if cfg.StreamInvokeMethodTimeoutMs <= 0 {
|
||||
return defaultStreamTimeout
|
||||
}
|
||||
return time.Duration(cfg.StreamInvokeMethodTimeoutMs) * time.Millisecond
|
||||
}
|
||||
|
||||
func (cfg RemoteConfig) GetTransferFileBufferSize() int64 {
|
||||
func (cfg GrpcSetting) GetTransferFileBufferSize() int64 {
|
||||
if cfg.MultipartDataTransferBufferSizeBytes <= 0 {
|
||||
return defaultBufferSize
|
||||
}
|
||||
return cfg.MultipartDataTransferBufferSizeBytes
|
||||
}
|
||||
|
||||
func (cfg RemoteConfig) GetMaxRequestBodySize() int64 {
|
||||
func (cfg GrpcSetting) GetMaxRequestBodySize() int64 {
|
||||
if cfg.MaxRequestBodySizeBytes <= 0 {
|
||||
return defaultMaxRequestBodySize
|
||||
}
|
||||
|
||||
+1
-2
@@ -9,8 +9,6 @@ import (
|
||||
)
|
||||
|
||||
func Complete(ctx *fasthttp.RequestCtx) {
|
||||
path := string(ctx.Path())
|
||||
|
||||
if err := authenticate.Do(ctx); err != nil {
|
||||
status := codes.Unknown
|
||||
switch e := err.(type) {
|
||||
@@ -21,6 +19,7 @@ func Complete(ctx *fasthttp.RequestCtx) {
|
||||
return
|
||||
}
|
||||
|
||||
path := string(ctx.Path())
|
||||
p := proxy.Find(path)
|
||||
if p != nil {
|
||||
p.ProxyRequest(ctx)
|
||||
|
||||
+4
-1
@@ -1,7 +1,8 @@
|
||||
package log_code
|
||||
|
||||
const (
|
||||
WarnRequestHandler = 604 //metadata: {"typeData":"", "method":""}
|
||||
//grpc
|
||||
WarnProxyGrpcHandler = 604 //metadata: {"typeData":"", "method":""}
|
||||
WarnConvertErrorDataMarshalResponse = 605
|
||||
ErrorGrpcClientDialing = 606
|
||||
WarnJournalCouldNotWriteToFile = 607
|
||||
@@ -17,4 +18,6 @@ const (
|
||||
ErrorClientHttp = 906
|
||||
|
||||
ErrorClientRedis = 907
|
||||
|
||||
ErrorAuthenticate = 908
|
||||
)
|
||||
@@ -56,7 +56,7 @@ func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) {
|
||||
|
||||
journal.Client.ReceiveConfiguration(remoteConfig.Journal, localCfg.ModuleName)
|
||||
redis.Client.ReceiveConfiguration(remoteConfig.Redis)
|
||||
server.Http.Init(remoteConfig.MaxRequestBodySizeBytes)
|
||||
server.Http.Init(remoteConfig.GrpcSetting.MaxRequestBodySizeBytes) //todo remote config info
|
||||
|
||||
service.JournalMethodsMatcher = service.NewCacheableMethodMatcher(remoteConfig.JournalingMethodsPatterns)
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ var (
|
||||
func convertError(err error) ([]byte, int) {
|
||||
s, ok := status.FromError(err)
|
||||
if ok {
|
||||
cfg := config.GetRemote().(*conf.RemoteConfig)
|
||||
cfg := config.GetRemote().(*conf.RemoteConfig).GrpcSetting
|
||||
if cfg.EnableOriginalProtoErrors {
|
||||
if body, err := proto.Marshal(s.Proto()); err != nil {
|
||||
return []byte(utils.ServiceError), http.StatusServiceUnavailable
|
||||
@@ -105,7 +105,7 @@ func logHandlerError(typeData, method string, err error) {
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
log_code.MdTypeData: typeData,
|
||||
log_code.MdMethod: method,
|
||||
}).Warn(log_code.WarnRequestHandler, err)
|
||||
}).Warn(log_code.WarnProxyGrpcHandler, err)
|
||||
}
|
||||
|
||||
func openStream(headers *fasthttp.RequestHeader, method string, timeout time.Duration, client *backend.RxGrpcClient) (
|
||||
|
||||
@@ -22,7 +22,7 @@ var getFile getFileDesc
|
||||
type getFileDesc struct{}
|
||||
|
||||
func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) {
|
||||
cfg := config.GetRemote().(*conf.RemoteConfig)
|
||||
cfg := config.GetRemote().(*conf.RemoteConfig).GrpcSetting
|
||||
timeout := cfg.GetStreamInvokeTimeout()
|
||||
|
||||
req, err := g.readJsonBody(ctx)
|
||||
@@ -96,7 +96,7 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
log_code.MdTypeData: log_code.TypeData.GetFile,
|
||||
log_code.MdMethod: method,
|
||||
}).Errorf(log_code.WarnRequestHandler, "Method %s. Expected bytes array", method)
|
||||
}).Errorf(log_code.WarnProxyGrpcHandler, "Method %s. Expected bytes array", method)
|
||||
break
|
||||
}
|
||||
_, err = ctx.Write(bytes)
|
||||
|
||||
@@ -33,7 +33,7 @@ func (p handleJsonDesc) Complete(c *fasthttp.RequestCtx, method string, client *
|
||||
md, methodName := makeMetadata(&c.Request.Header, method)
|
||||
ctx := metadata.NewOutgoingContext(context.Background(), md)
|
||||
cfg := config.GetRemote().(*conf.RemoteConfig)
|
||||
ctx, cancel := context.WithTimeout(ctx, cfg.GetSyncInvokeTimeout())
|
||||
ctx, cancel := context.WithTimeout(ctx, cfg.GrpcSetting.GetSyncInvokeTimeout())
|
||||
defer cancel()
|
||||
|
||||
cli, err := client.Conn()
|
||||
|
||||
@@ -19,7 +19,7 @@ var sendMultipartData sendMultipartDataDesc
|
||||
type sendMultipartDataDesc struct{}
|
||||
|
||||
func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) {
|
||||
cfg := config.GetRemote().(*conf.RemoteConfig)
|
||||
cfg := config.GetRemote().(*conf.RemoteConfig).GrpcSetting
|
||||
timeout := cfg.GetStreamInvokeTimeout()
|
||||
bufferSize := cfg.GetTransferFileBufferSize()
|
||||
|
||||
|
||||
Reference in new issue
Block a user