From 0edf80ffed659252df9f831bc9214b32e612afeb Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Fri, 25 Oct 2019 11:31:18 +0300 Subject: [PATCH] add admin authenticate --- .version | 2 +- Gopkg.lock | 21 +++++++++++++++------ authenticate/authenticate.go | 36 ++++++++++++++++++++++++++++++------ authenticate/error.go | 6 +----- authenticate/token.go | 29 +++++++++++++++++++++++++++++ authenticate/verification.go | 2 +- conf/remote_config.go | 11 ++++++++--- log_code/code.go | 26 +++++++++++--------------- main.go | 9 ++++++++- routing/routing.go | 24 ++++++++++++++++++++++++ 10 files changed, 128 insertions(+), 38 deletions(-) create mode 100644 authenticate/token.go create mode 100644 routing/routing.go diff --git a/.version b/.version index 99d85ec..5c4511c 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -0.0.6 \ No newline at end of file +0.0.7 \ No newline at end of file diff --git a/Gopkg.lock b/Gopkg.lock index ddd7699..8ca5782 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -17,6 +17,14 @@ revision = "ade4e2031af3aed7fffd241084aad80a58faf421" version = "v0.1.1" +[[projects]] + digest = "1:76dc72490af7174349349838f2fe118996381b31ea83243812a97e5a0fd5ed55" + name = "github.com/dgrijalva/jwt-go" + packages = ["."] + pruneopts = "UT" + revision = "06ea1031745cb8b3dab3f6a236daf2b0aa468b7e" + version = "v3.2.0" + [[projects]] digest = "1:abeb38ade3f32a92943e5be54f55ed6d6e3b6602761d74b4aab4c9dd45c18abd" name = "github.com/fsnotify/fsnotify" @@ -148,7 +156,7 @@ [[projects]] branch = "master" - digest = "1:5d6745d93914f036ecf9c22e20ec2a6885864acad54bec463e59cfde770dd7ee" + digest = "1:a1ebd1a46e87e9343cbabec1ca99c34a7a2e0572c0160fcf266175073b2adf5f" name = "github.com/integration-system/isp-lib" packages = [ "backend", @@ -165,7 +173,7 @@ "utils", ] pruneopts = "UT" - revision = "f72fc522399b23b49e43d8bcc279a54654ea2419" + revision = "5060d1348219abd8fad3628668b229779a5314c7" [[projects]] branch = "master" @@ -382,7 +390,7 @@ [[projects]] branch = "master" - digest = "1:e743d2809ba5299bfe842a8a724172f9ac4e89ee281b46720ac65a688ac398a1" + digest = "1:8df917c05bc5b359af4a95a39049919ec141d6224f48bb7b92a8f44c91c0f5ba" name = "github.com/valyala/fasthttp" packages = [ ".", @@ -390,7 +398,7 @@ "stackless", ] pruneopts = "UT" - revision = "18c619fb0432fa6b21cb134d35118e6b09d9d9ce" + revision = "707b1c1917f38038d0d81e856df73853513100b3" [[projects]] digest = "1:39a425f98fb19427061a693fe6bf0683c9bddec4b25b17067e34fdb465e39cb9" @@ -426,14 +434,14 @@ [[projects]] branch = "master" - digest = "1:3fa58f7377e1d95d496db43dd3281ddcea4185eb46c6394f89fec1cfa4ec3244" + digest = "1:f8c0a298987fa1c452d209f37d2ed9bcf874f2c6eec817607e8ebbba88e6331f" name = "golang.org/x/sys" packages = [ "unix", "windows", ] pruneopts = "UT" - revision = "742c48ecaeb7c624c475e02f3eb0827ebb4970d4" + revision = "e66fe6eb8e0cbfacade8b490cf55cd2494f4db62" [[projects]] digest = "1:8d8faad6b12a3a4c819a3f9618cb6ee1fa1cfc33253abeeea8b55336721e3405" @@ -525,6 +533,7 @@ analyzer-name = "dep" analyzer-version = 1 input-imports = [ + "github.com/dgrijalva/jwt-go", "github.com/go-redis/redis", "github.com/golang/protobuf/proto", "github.com/golang/protobuf/ptypes/struct", diff --git a/authenticate/authenticate.go b/authenticate/authenticate.go index 1795767..334d729 100644 --- a/authenticate/authenticate.go +++ b/authenticate/authenticate.go @@ -6,6 +6,7 @@ import ( "github.com/valyala/fasthttp" "google.golang.org/grpc/codes" "isp-gate-service/log_code" + "isp-gate-service/routing" "strings" ) @@ -25,16 +26,16 @@ func Do(ctx *fasthttp.RequestCtx) error { appToken := ctx.Request.Header.Peek(utils.ApplicationTokenHeader) if len(appToken) == 0 { - return Error.create(codes.Unauthenticated) + return createError(codes.Unauthenticated) } keys, err := verification.appToken(string(appToken)) if err != nil { log.Error(log_code.ErrorAuthenticate, err) - return Error.create(codes.Internal) + return createError(codes.Internal) } if len(keys) != 4 { - return Error.create(codes.Unauthenticated) + return createError(codes.Unauthenticated) } verifiableKeys := make(map[string]string) @@ -42,17 +43,18 @@ func Do(ctx *fasthttp.RequestCtx) error { verifiableKeys[verifiableKeyHeaderKeyMap[i]] = value } - uri := strings.Replace(strings.ToLower(string(ctx.Path())), "/", "", -1) + path := ctx.Path() + uri := strings.Replace(strings.ToLower(string(path)), "/", "", -1) 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 { log.Error(log_code.ErrorAuthenticate, err) - return Error.create(codes.Internal) + return createError(codes.Internal) } if verifiableKeys[permittedToCallInfo] == "0" { - return Error.create(codes.PermissionDenied) + return createError(codes.PermissionDenied) } else { delete(verifiableKeys, permittedToCallInfo) } @@ -62,5 +64,27 @@ func Do(ctx *fasthttp.RequestCtx) error { ctx.Request.Header.Set(key, value) } } + + path = getPathWithoutPrefix(path) + if _, ok := routing.InnerAddressMap[string(path)]; ok { + adminToken := ctx.Request.Header.Peek("x-auth-admin") //todo const key + if token.Check(string(adminToken)) != nil { + return createError(codes.PermissionDenied) + } + } return nil } + +func getPathWithoutPrefix(path []byte) []byte { + firstFound := false + for key, value := range path { + if value == '/' { + if firstFound { + return path[key+1:] + } else { + firstFound = true + } + } + } + return []byte{} +} diff --git a/authenticate/error.go b/authenticate/error.go index 96503ec..472100a 100644 --- a/authenticate/error.go +++ b/authenticate/error.go @@ -5,11 +5,7 @@ import ( "google.golang.org/grpc/codes" ) -var Error errorHelper - -type errorHelper struct{} - -func (errorHelper) create(status codes.Code) ErrorDescription { +func createError(status codes.Code) ErrorDescription { return ErrorDescription{grpcStatus: status} } diff --git a/authenticate/token.go b/authenticate/token.go new file mode 100644 index 0000000..ee02845 --- /dev/null +++ b/authenticate/token.go @@ -0,0 +1,29 @@ +package authenticate + +import ( + "github.com/dgrijalva/jwt-go" + "github.com/integration-system/isp-lib/config" + "github.com/pkg/errors" + "isp-gate-service/conf" +) + +var token tokenHelper + +type tokenHelper struct{} + +func (tokenHelper) Check(token string) error { + secret := config.GetRemote().(*conf.RemoteConfig).SecretKey + + if parsed, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) { + if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, errors.Errorf("unexpected signing method: %v", token.Header["alg"]) + } + return []byte(secret), nil + }); err != nil { + return err + } else if !parsed.Valid { + return errors.New("token is invalid") + } + + return nil +} diff --git a/authenticate/verification.go b/authenticate/verification.go index e62b295..8bc58c3 100644 --- a/authenticate/verification.go +++ b/authenticate/verification.go @@ -126,6 +126,6 @@ func (v *verificationHelper) findStringCmd(cmders []rd.Cmder, arrayKey int) (str return "", errors.New("empty cmd") } } else { - return "", errors.New("") + return "", errors.New("not found cmd") } } diff --git a/conf/remote_config.go b/conf/remote_config.go index 9075610..00c9c7e 100644 --- a/conf/remote_config.go +++ b/conf/remote_config.go @@ -20,6 +20,8 @@ const ( type ( RemoteConfig struct { + SecretKey string + ServerSetting ServerSetting GrpcSetting GrpcSetting Metrics structure.MetricConfiguration `schema:"Настройка метрик"` Journal rx.Config `schema:"Настройка логирования"` @@ -27,11 +29,14 @@ type ( Redis structure.RedisConfiguration `schema:"Настрока Redis" valid:"required~Required"` } + ServerSetting struct { + MaxRequestBodySizeBytes int64 `schema:"Максимальный размер тела запроса,в байтайх, по умолчанию: 512 MB"` + } + 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"` } @@ -58,9 +63,9 @@ func (cfg GrpcSetting) GetTransferFileBufferSize() int64 { return cfg.MultipartDataTransferBufferSizeBytes } -func (cfg GrpcSetting) GetMaxRequestBodySize() int64 { +/*func (cfg GrpcSetting) GetMaxRequestBodySize() int64 { if cfg.MaxRequestBodySizeBytes <= 0 { return defaultMaxRequestBodySize } return cfg.MaxRequestBodySizeBytes -} +}*/ diff --git a/log_code/code.go b/log_code/code.go index 6e1f2a6..2b79341 100644 --- a/log_code/code.go +++ b/log_code/code.go @@ -1,23 +1,19 @@ package log_code const ( - //grpc - WarnProxyGrpcHandler = 604 //metadata: {"typeData":"", "method":""} - WarnConvertErrorDataMarshalResponse = 605 - ErrorGrpcClientDialing = 606 - WarnJournalCouldNotWriteToFile = 607 - WarnJournalClientDialing = 608 + WarnProxyGrpcHandler = 901 //metadata: {"typeData":"", "method":""} + WarnConvertErrorDataMarshalResponse = 902 + WarnJournalCouldNotWriteToFile = 903 - ErrorClientJournal = 903 + WarnHttpServerShutdown = 904 + ErrorHttpServerListen = 905 - WarnHttpServerShutdown = 602 - ErrorHttpServerListen = 603 + ErrorLocalConfig = 906 + ErrorClientGrpc = 907 + ErrorClientHttp = 908 - ErrorLocalConfig = 904 - ErrorClientGrpc = 905 - ErrorClientHttp = 906 + ErrorClientJournal = 909 + ErrorClientRedis = 910 - ErrorClientRedis = 907 - - ErrorAuthenticate = 908 + ErrorAuthenticate = 911 ) diff --git a/main.go b/main.go index 180ec2b..58610e5 100644 --- a/main.go +++ b/main.go @@ -13,6 +13,7 @@ import ( "isp-gate-service/log_code" "isp-gate-service/proxy" "isp-gate-service/redis" + "isp-gate-service/routing" "isp-gate-service/server" "isp-gate-service/service" "os" @@ -32,6 +33,7 @@ func main() { DefaultRemoteConfigPath(schema.ResolveDefaultConfigPath("default_remote_config.json")). DeclareMe(makeDeclaration). SocketConfiguration(socketConfiguration). + RequireRoutes(handleRouteUpdate). RequireModule(journal.RequiredModule()) for _, location := range cfg.Locations { @@ -56,7 +58,7 @@ func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) { journal.Client.ReceiveConfiguration(remoteConfig.Journal, localCfg.ModuleName) redis.Client.ReceiveConfiguration(remoteConfig.Redis) - server.Http.Init(remoteConfig.GrpcSetting.MaxRequestBodySizeBytes) //todo remote config info + server.Http.Init(remoteConfig.ServerSetting.MaxRequestBodySizeBytes) service.JournalMethodsMatcher = service.NewCacheableMethodMatcher(remoteConfig.JournalingMethodsPatterns) @@ -85,6 +87,11 @@ func onShutdown(_ context.Context, _ os.Signal) { server.Http.Close() } +func handleRouteUpdate(configs structure.RoutingConfig) bool { + routing.InitRoutes(configs) + return true +} + func makeDeclaration(localConfig interface{}) bootstrap.ModuleInfo { cfg := localConfig.(*conf.Configuration) return bootstrap.ModuleInfo{ diff --git a/routing/routing.go b/routing/routing.go new file mode 100644 index 0000000..24bc210 --- /dev/null +++ b/routing/routing.go @@ -0,0 +1,24 @@ +package routing + +import ( + "github.com/integration-system/isp-lib/structure" +) + +var ( + InnerAddressMap = make(map[string]bool) +) + +func InitRoutes(configs structure.RoutingConfig) { + newInnerAddressMap := make(map[string]bool) + for _, backend := range configs { + if backend.Address.IP == "" || backend.Address.Port == "" || len(backend.Endpoints) == 0 { + continue + } + for _, v := range backend.Endpoints { + if v.Inner { + newInnerAddressMap[v.Path] = true + } + } + } + InnerAddressMap = newInnerAddressMap +}