From 23ede62f24427cc1f432746082e89891256b40b1 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Wed, 13 Nov 2019 17:32:42 +0300 Subject: [PATCH 1/2] add(jwt verify) --- authenticate/authenticate.go | 66 ++++++++++++------- authenticate/error.go | 9 ++- authenticate/token.go | 36 +++++++--- conf/default_remote_config.json | 32 ++++++++- conf/remote_config.go | 43 +++++++++--- handler/handler.go | 8 ++- log_code/code.go | 4 +- main.go | 13 ++-- service/veritification/cacheable_verify.go | 52 +++++++++++++++ .../veritification/runtime_verify.go | 49 +++++++------- service/veritification/verify.go | 24 +++++++ 11 files changed, 259 insertions(+), 77 deletions(-) create mode 100644 service/veritification/cacheable_verify.go rename authenticate/verification.go => service/veritification/runtime_verify.go (73%) create mode 100644 service/veritification/verify.go diff --git a/authenticate/authenticate.go b/authenticate/authenticate.go index 7c340e6..f03145b 100644 --- a/authenticate/authenticate.go +++ b/authenticate/authenticate.go @@ -1,73 +1,93 @@ package authenticate import ( + "github.com/integration-system/isp-lib/config" "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/conf" "isp-gate-service/log_code" "isp-gate-service/routing" + "isp-gate-service/service/veritification" "strconv" "strings" + "time" ) -var ( - verifiableKeyHeaderKeyMap = map[string]string{ - systemIdentity: utils.SystemIdHeader, - domainIdentity: utils.DomainIdHeader, - serviceIdentity: utils.ServiceIdHeader, - applicationIdentity: utils.ApplicationIdHeader, +var notExpectedHeaders = []string{ + utils.SystemIdHeader, utils.DomainIdHeader, utils.ServiceIdHeader, utils.ApplicationIdHeader, +} + +var auth = authenticate{} + +type authenticate struct { + verify veritification.Verify +} + +func ReceiveConfiguration(conf conf.Authenticate) { + if conf.EnableCash { + if timeout, err := time.ParseDuration(conf.Timeout); err != nil { + log.Fatalf(log_code.ErrorConfigAuth, "invalid timeout '%s'", timeout) + } else { + auth.verify = veritification.NewCacheableVerify(timeout) + } + } else { + auth.verify = veritification.NewRuntimeVerify() } -) +} func Do(ctx *fasthttp.RequestCtx) (int64, error) { path := ctx.Path() - uri := strings.Replace(strings.ToLower(string(path)), "/", "", -1) + uri := strings.Replace(strings.ToLower(string(path)), "/", "", -1) //todo await routing path = getPathWithoutPrefix(path) + var ( + err error + appId int + ) + if _, ok := routing.AddressMap[string(path)]; !ok { return 0, createError(codes.Unimplemented) } - for _, notExpectedHeader := range verifiableKeyHeaderKeyMap { + for _, notExpectedHeader := range notExpectedHeaders { ctx.Request.Header.Del(notExpectedHeader) } appToken := ctx.Request.Header.Peek(utils.ApplicationTokenHeader) if len(appToken) == 0 { return 0, createError(codes.Unauthenticated) + } else if config.GetRemote().(*conf.RemoteConfig).TokenVerification.Enable { + if appId, err = validateToken.Application(string(appToken)); err != nil { + return 0, createError(codes.Unauthenticated, "application token parse") + } } - keys, err := verification.appToken(string(appToken)) + verifiableKeys, err := auth.verify.ApplicationToken(string(appToken)) if err != nil { log.Error(log_code.ErrorAuthenticate, err) return 0, createError(codes.Internal) } - if len(keys) != 4 { - return 0, createError(codes.Unauthenticated) - } - - verifiableKeys := make(map[string]string) - for i, value := range keys { - verifiableKeys[verifiableKeyHeaderKeyMap[i]] = value + if len(verifiableKeys) != 4 { + return 0, createError(codes.Unauthenticated, "application token value") } 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) + permittedToCall := false + verifiableKeys, permittedToCall, err = auth.verify.Identity(verifiableKeys, uri) if err != nil { log.Error(log_code.ErrorAuthenticate, err) return 0, createError(codes.Internal) } - if verifiableKeys[permittedToCallInfo] == "0" { + if permittedToCall { return 0, createError(codes.PermissionDenied) - } else { - delete(verifiableKeys, permittedToCallInfo) } applicationId, err := strconv.Atoi(verifiableKeys[utils.ApplicationIdHeader]) - if err != nil { + if err != nil || (appId != 0 && applicationId != appId) { log.Error(log_code.ErrorAuthenticate, err) return 0, createError(codes.Internal) } @@ -80,7 +100,7 @@ func Do(ctx *fasthttp.RequestCtx) (int64, error) { if _, ok := routing.InnerAddressMap[string(path)]; ok { adminToken := ctx.Request.Header.Peek("x-auth-admin") //todo const key - if token.Check(string(adminToken)) != nil { + if validateToken.Admin(string(adminToken)) != nil { return 0, createError(codes.PermissionDenied) } } diff --git a/authenticate/error.go b/authenticate/error.go index 472100a..9df68a0 100644 --- a/authenticate/error.go +++ b/authenticate/error.go @@ -5,12 +5,13 @@ import ( "google.golang.org/grpc/codes" ) -func createError(status codes.Code) ErrorDescription { - return ErrorDescription{grpcStatus: status} +func createError(status codes.Code, details ...interface{}) ErrorDescription { + return ErrorDescription{grpcStatus: status, details: details} } type ErrorDescription struct { grpcStatus codes.Code + details []interface{} } func (e ErrorDescription) Error() string { @@ -20,3 +21,7 @@ func (e ErrorDescription) Error() string { func (e ErrorDescription) ConvertToGrpcStatus() codes.Code { return e.grpcStatus } + +func (e ErrorDescription) Details() []interface{} { + return e.details +} diff --git a/authenticate/token.go b/authenticate/token.go index ee02845..bda69bc 100644 --- a/authenticate/token.go +++ b/authenticate/token.go @@ -7,23 +7,43 @@ import ( "isp-gate-service/conf" ) -var token tokenHelper +var validateToken token -type tokenHelper struct{} +type token struct{} -func (tokenHelper) Check(token string) error { - secret := config.GetRemote().(*conf.RemoteConfig).SecretKey +func (t token) Admin(token string) error { + secret := config.GetRemote().(*conf.RemoteConfig).SecretSetting.Admin + _, err := t.parse(token, secret) + return err +} +func (t token) Application(token string) (int, error) { + secret := config.GetRemote().(*conf.RemoteConfig).SecretSetting.Application + + if parsed, err := t.parse(token, secret); err != nil { + return 0, err + } else if claims, ok := parsed.Claims.(jwt.MapClaims); !ok { + return 0, errors.New("token is invalid") + } else if appId, ok := claims["appId"]; !ok { + return 0, errors.New("token is invalid") + } else if applicationId, ok := appId.(float64); !ok { + return 0, errors.New("token is invalid") + } else { + return int(applicationId), nil + } +} + +func (token) parse(token, secret string) (*jwt.Token, error) { 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 + return nil, err } else if !parsed.Valid { - return errors.New("token is invalid") + return nil, errors.New("token is invalid") + } else { + return parsed, nil } - - return nil } diff --git a/conf/default_remote_config.json b/conf/default_remote_config.json index b2d480c..8d95f14 100644 --- a/conf/default_remote_config.json +++ b/conf/default_remote_config.json @@ -17,9 +17,13 @@ "ip": "0.0.0.0" } }, - "secretKey": "secret key", - "grpcSetting": {}, - "serverSetting": {}, + "grpcSetting": { + "enableOriginalProtoErrors": false, + "proxyGrpcErrorDetails": false + }, + "serverSetting": { + "maxRequestBodySizeBytes": 0 + }, "accountingSetting": { "enable": false, "setting": [ @@ -40,5 +44,27 @@ "ip": "127.0.0.1", "port": "6379" } + }, + "tokenVerification": { + "enable": false + }, + "authenticateSetting": { + "timeout": "1m", + "enableCash": true + }, + "secretSetting": { + "admin": "secret", + "application": "secret" + }, + "journalSetting": { + "journal": { + "rotateTimeoutMs": 86400000, + "enableRemoteTransfer": true, + "enable": false, + "compress": true, + "filename": "/var/log/isp-gate-service/runtime.log", + "maxSizeMb": 512, + "bufferSize": 4096 + } } } \ No newline at end of file diff --git a/conf/remote_config.go b/conf/remote_config.go index c333601..0e6192c 100644 --- a/conf/remote_config.go +++ b/conf/remote_config.go @@ -20,14 +20,34 @@ const ( type ( RemoteConfig struct { - SecretKey string `schema:"Секрет"` - ServerSetting ServerSetting `schema:"Настройка сервера"` - GrpcSetting GrpcSetting `schema:"Настройка grpc соединения"` - Metrics structure.MetricConfiguration `schema:"Настройка метрик"` - Journal rx.Config `schema:"Настройка логирования"` - JournalingMethodsPatterns []string `schema:"Список методов для логирования,список строк вида: 'module/group/method'(* - для частичного совпадения). При обработке запроса, если вызываемый метод совпадает со строкой из списка, тела запроса и ответа записываются в лог"` - Redis structure.RedisConfiguration `schema:"Настройка Redis" valid:"required~Required"` - AccountingSetting Accounting `schema:"Настройка учета запросов"` + TokenVerification TokenVerification `schema:"Настройка веритификации токенов"` + SecretSetting SecretSetting `schema:"Настройка секретов"` + ServerSetting ServerSetting `schema:"Настройка сервера"` + GrpcSetting GrpcSetting `schema:"Настройка grpc соединения"` + Metrics structure.MetricConfiguration `schema:"Настройка метрик"` + JournalSetting Journal `schema:"Настройка журалирования"` + Redis structure.RedisConfiguration `schema:"Настройка Redis" valid:"required~Required"` + AccountingSetting Accounting `schema:"Настройка учета запросов"` + AuthenticateSetting Authenticate `schema:"Настройка авторизации" valid:"required~Required"` + } + + Authenticate struct { + EnableCash bool `schema:"Включает сохранение информации о авторизации токена"` + Timeout string `schema:"Время жизни информации в кеше"` + } + + Journal struct { + Journal rx.Config `schema:"Настройка конфигурации"` + MethodsPatterns []string `schema:"Список методов для логирования,список строк вида: 'module/group/method'(* - для частичного совпадения). При обработке запроса, если вызываемый метод совпадает со строкой из списка, тела запроса и ответа записываются в лог"` + } + + TokenVerification struct { + Enable bool `schema:"Включает проверку application-токена"` + } + + SecretSetting struct { + Admin string `schema:"Секрет admin-токена"` + Application string `schema:"Секрет application-токена"` } Accounting struct { @@ -79,3 +99,10 @@ func (cfg GrpcSetting) GetTransferFileBufferSize() int64 { } return cfg.MultipartDataTransferBufferSizeBytes } + +func (cfg ServerSetting) GetMaxRequestBodySize() int64 { + if cfg.MaxRequestBodySizeBytes <= 0 { + return defaultMaxRequestBodySize + } + return cfg.MaxRequestBodySizeBytes +} diff --git a/handler/handler.go b/handler/handler.go index a533fd6..b0501c3 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -39,7 +39,7 @@ func CompleteRequest(ctx *fasthttp.RequestCtx) { } requestBody, responseBody, err := resp.Get() - if config.GetRemote().(*conf.RemoteConfig).Journal.Enable { + if config.GetRemote().(*conf.RemoteConfig).JournalSetting.Journal.Enable { if matcher.JournalMethods.Match(uri) { if err != nil { if err := journal.Client.Error(uri, requestBody, responseBody, err); err != nil { @@ -60,17 +60,19 @@ func (handlerHelper) AuthenticateApproveProxy(ctx *fasthttp.RequestCtx) domain.P applicationId, err := authenticate.Do(ctx) if err != nil { status := codes.Unknown + details := make([]interface{}, 0) switch e := err.(type) { case authenticate.ErrorDescription: status = e.ConvertToGrpcStatus() + details = e.Details() } - utils.WriteError(ctx, "unauthorized", status, nil) + utils.WriteError(ctx, "unauthorized", status, details) return domain.Create().SetError(err) } if approver := accounting.GetAccounting(applicationId); approver != nil && !approver.TakeAccount(path) { err := errors.New("accounting error") - utils.WriteError(ctx, "forbidden", codes.PermissionDenied, nil) + utils.WriteError(ctx, "forbidden", codes.ResourceExhausted, nil) return domain.Create().SetError(err) } diff --git a/log_code/code.go b/log_code/code.go index ac76df8..74c6895 100644 --- a/log_code/code.go +++ b/log_code/code.go @@ -15,6 +15,8 @@ const ( ErrorClientJournal = 608 ErrorClientRedis = 609 - ErrorAuthenticate = 612 + ErrorAuthenticate = 612 + FatalConfigApproveSetting = 613 + ErrorConfigAuth = 614 ) diff --git a/main.go b/main.go index 347143a..b057860 100644 --- a/main.go +++ b/main.go @@ -9,6 +9,7 @@ import ( "github.com/integration-system/isp-lib/structure" log "github.com/integration-system/isp-log" "isp-gate-service/accounting" + "isp-gate-service/authenticate" "isp-gate-service/conf" "isp-gate-service/journal" "isp-gate-service/log_code" @@ -58,16 +59,16 @@ func onLocalConfigLoad(cfg *conf.Configuration) { func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) { localCfg := config.Get().(*conf.Configuration) - journal.Client.ReceiveConfiguration(remoteConfig.Journal, localCfg.ModuleName) - redis.Client.ReceiveConfiguration(remoteConfig.Redis) - server.Http.Init(remoteConfig.ServerSetting.MaxRequestBodySizeBytes) - accounting.ReceiveConfiguration(remoteConfig.AccountingSetting) + journal.Client.ReceiveConfiguration(remoteConfig.JournalSetting.Journal, localCfg.ModuleName) + matcher.JournalMethods = matcher.NewAtLeastOneMatcher(remoteConfig.JournalSetting.MethodsPatterns) - matcher.JournalMethods = matcher.NewAtLeastOneMatcher(remoteConfig.JournalingMethodsPatterns) + redis.Client.ReceiveConfiguration(remoteConfig.Redis) + server.Http.Init(remoteConfig.ServerSetting.GetMaxRequestBodySize()) + accounting.ReceiveConfiguration(remoteConfig.AccountingSetting) + authenticate.ReceiveConfiguration(remoteConfig.AuthenticateSetting) metric.InitCollectors(remoteConfig.Metrics, oldRemoteConfig.Metrics) metric.InitHttpServer(remoteConfig.Metrics) - //metric.InitStatusChecker("router-grpc", helper.GetRoutersAndStatus) service.Metrics.Init() } diff --git a/service/veritification/cacheable_verify.go b/service/veritification/cacheable_verify.go new file mode 100644 index 0000000..f46a95d --- /dev/null +++ b/service/veritification/cacheable_verify.go @@ -0,0 +1,52 @@ +package veritification + +import ( + "sync" + "time" +) + +type ( + cacheableVerify struct { + cache map[string]cacheInfo + timeout time.Duration + rv *runtimeVerify + lock sync.RWMutex + } + + cacheInfo struct { + created time.Time + identity map[string]string + } +) + +func (cv *cacheableVerify) ApplicationToken(token string) (map[string]string, error) { + cv.lock.RLock() + cache, ok := cv.cache[token] + cv.lock.RUnlock() + if ok { + if time.Now().Sub(cache.created) > cv.timeout { + return cache.identity, nil + } + } + + cv.lock.Lock() + defer cv.lock.Unlock() + if cache, ok = cv.cache[token]; ok { + if time.Now().Sub(cache.created) > cv.timeout { + return cache.identity, nil + } else { + delete(cv.cache, token) + } + } + if identity, err := cv.rv.ApplicationToken(token); err != nil { + return nil, err + } else { + cv.cache[token] = cacheInfo{created: time.Now(), identity: identity} + resp := identity + return resp, nil + } +} + +func (cv *cacheableVerify) Identity(identity map[string]string, uri string) (map[string]string, bool, error) { + return cv.rv.Identity(identity, uri) +} diff --git a/authenticate/verification.go b/service/veritification/runtime_verify.go similarity index 73% rename from authenticate/verification.go rename to service/veritification/runtime_verify.go index 8bc58c3..53ac36a 100644 --- a/authenticate/verification.go +++ b/service/veritification/runtime_verify.go @@ -1,4 +1,4 @@ -package authenticate +package veritification import ( "fmt" @@ -11,20 +11,18 @@ import ( rdClient "isp-gate-service/redis" ) -const ( - systemIdentity = "1" - domainIdentity = "2" - serviceIdentity = "3" - applicationIdentity = "4" +const permittedToCallInfo = "0" - permittedToCallInfo = "permittedToCallInfo" -) +var headerKeyByRedisIdentity = map[string]string{ + "1": utils.SystemIdHeader, + "2": utils.DomainIdHeader, + "3": utils.ServiceIdHeader, + "4": utils.ApplicationIdHeader, +} -var verification verificationHelper +type runtimeVerify struct{} -type verificationHelper struct{} - -func (v verificationHelper) appToken(token string) (map[string]string, error) { +func (v *runtimeVerify) ApplicationToken(token string) (map[string]string, error) { instanceUuid := config.Get().(*conf.Configuration).InstanceUuid key := fmt.Sprintf("%s|%s", token, instanceUuid) @@ -46,15 +44,20 @@ func (v verificationHelper) appToken(token string) (map[string]string, error) { } else if stringStringMapCmd, ok := resp[1].(*rd.StringStringMapCmd); !ok { return nil, nil } else { - return stringStringMapCmd.Val(), nil + identityMap := make(map[string]string) + for i, value := range stringStringMapCmd.Val() { + identityMap[headerKeyByRedisIdentity[i]] = value + } + return identityMap, nil } } } -func (v *verificationHelper) keys(t map[string]string, uri string) (map[string]string, error) { +func (v *runtimeVerify) Identity(t map[string]string, uri string) (map[string]string, bool, error) { 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]) + permittedToCall := false if resp, err := rdClient.Client.Get().Pipelined(func(p rd.Pipeliner) error { if cmd := p.Select(int(redis.ApplicationPermissionDb)); v.notEmptyError(cmd.Err()) { @@ -79,35 +82,35 @@ func (v *verificationHelper) keys(t map[string]string, uri string) (map[string]s } return nil }); v.notEmptyError(err) { - return t, err + return t, false, err } else { // It is not permitted to call this methodParts if msg, err := v.findStringCmd(resp, 1); err != nil { - return t, err - } else { - t[permittedToCallInfo] = msg + return t, false, err + } else if msg == permittedToCallInfo { + permittedToCall = true } // ===== CHECK USER TOKEN ===== if msg, err := v.findStringCmd(resp, 3); err != nil { - return t, err + return t, false, err } else { t[utils.UserIdHeader] = msg } // ===== CHECK DEVICE TOKEN ===== if msg, err := v.findStringCmd(resp, 5); err != nil { - return t, err + return t, false, err } else { t[utils.DeviceIdHeader] = msg } } - return t, nil + return t, permittedToCall, nil } -func (v *verificationHelper) notEmptyError(err error) bool { +func (v *runtimeVerify) notEmptyError(err error) bool { return err != nil && err != rd.Nil } -func (v *verificationHelper) findStringCmd(cmders []rd.Cmder, arrayKey int) (string, error) { +func (v *runtimeVerify) findStringCmd(cmders []rd.Cmder, arrayKey int) (string, error) { if len(cmders) > arrayKey { cmd := cmders[arrayKey] if cmd != nil { diff --git a/service/veritification/verify.go b/service/veritification/verify.go new file mode 100644 index 0000000..53f9d14 --- /dev/null +++ b/service/veritification/verify.go @@ -0,0 +1,24 @@ +package veritification + +import ( + "time" +) + +var Default = NewRuntimeVerify() + +type Verify interface { + ApplicationToken(string) (map[string]string, error) + Identity(map[string]string, string) (map[string]string, bool, error) +} + +func NewRuntimeVerify() Verify { + return &runtimeVerify{} +} + +func NewCacheableVerify(timeout time.Duration) Verify { + return &cacheableVerify{ + cache: make(map[string]cacheInfo), + timeout: timeout, + rv: &runtimeVerify{}, + } +} From 0e3c14d099f7158d1807da475a7424fa0d0c1244 Mon Sep 17 00:00:00 2001 From: ykomissarov Date: Fri, 15 Nov 2019 13:27:34 +0300 Subject: [PATCH 2/2] ref --- .version | 2 +- CHANGELOG.md | 4 +++ accounting/accounting.go | 12 +++---- accounting/accounting_test.go | 10 +++--- authenticate/authenticate.go | 63 +++++++++++++++++---------------- authenticate/token.go | 29 +++++++-------- conf/default_remote_config.json | 41 ++++++--------------- conf/remote_config.go | 38 +++++++++----------- handler/handler.go | 18 +++++----- log_code/code.go | 8 ++--- main.go | 11 +++--- routing/routing.go | 8 ++--- 12 files changed, 112 insertions(+), 132 deletions(-) diff --git a/.version b/.version index afaf360..9084fa2 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -1.0.0 \ No newline at end of file +1.1.0 diff --git a/CHANGELOG.md b/CHANGELOG.md index e69de29..a29424f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -0,0 +1,4 @@ +## 1.1.0 +* add token verification via JWT +* add accounting for applications +* add optional cache for application tokens diff --git a/accounting/accounting.go b/accounting/accounting.go index 1f2a5a3..b7a1727 100644 --- a/accounting/accounting.go +++ b/accounting/accounting.go @@ -2,14 +2,14 @@ package accounting import ( log "github.com/integration-system/isp-log" + "github.com/integration-system/isp-log/stdcodes" "isp-gate-service/accounting/state" "isp-gate-service/conf" - "isp-gate-service/log_code" "isp-gate-service/service/matcher" "sync" ) -var accountingByApplicationId = make(map[int64]*accounting) +var accountingByApplicationId = make(map[int32]*accounting) type accounting struct { mx sync.Mutex @@ -18,12 +18,12 @@ type accounting struct { } func ReceiveConfiguration(conf conf.Accounting) { - newAccountingByApplicationId := make(map[int64]*accounting) + newAccountingByApplicationId := make(map[int32]*accounting) if conf.Enable { for _, s := range conf.Setting { limitState, patternArray, err := state.InitLimitState(s.Limits) if err != nil { - log.Fatal(log_code.FatalConfigApproveSetting, err) + log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) } newAccountingByApplicationId[s.ApplicationId] = &accounting{ @@ -36,11 +36,11 @@ func ReceiveConfiguration(conf conf.Accounting) { accountingByApplicationId = newAccountingByApplicationId } -func GetAccounting(appId int64) *accounting { +func GetAccounting(appId int32) *accounting { return accountingByApplicationId[appId] } -func (app *accounting) TakeAccount(method string) bool { +func (app *accounting) Check(method string) bool { patternArray := app.matcher.Match(method) stateStorage := make([]state.LimitState, len(patternArray)) for i, pattern := range patternArray { diff --git a/accounting/accounting_test.go b/accounting/accounting_test.go index 819527d..6ee1b6d 100644 --- a/accounting/accounting_test.go +++ b/accounting/accounting_test.go @@ -24,7 +24,7 @@ var ( } reqExample = []struct { - appId int64 + appId int32 path []string }{ 0: {appId: 1, path: []string{ @@ -55,7 +55,7 @@ func TestApprove(t *testing.T) { expected := true req := reqExample[0] for _, path := range req.path { - a.Equal(expected, GetAccounting(req.appId).TakeAccount(path)) + a.Equal(expected, GetAccounting(req.appId).Check(path)) expected = !expected time.Sleep(150 * time.Millisecond) } @@ -63,19 +63,19 @@ func TestApprove(t *testing.T) { //expected == true req = reqExample[1] for _, path := range req.path { - a.Equal(expected, GetAccounting(req.appId).TakeAccount(path)) + a.Equal(expected, GetAccounting(req.appId).Check(path)) expected = !expected } req = reqExample[2] expectedArray := []bool{true, true, true, true, true, false} for key, path := range req.path { - a.Equal(expectedArray[key], GetAccounting(req.appId).TakeAccount(path)) + a.Equal(expectedArray[key], GetAccounting(req.appId).Check(path)) } //expected == true req = reqExample[3] for _, path := range req.path { - a.Equal(expected, GetAccounting(req.appId).TakeAccount(path)) + a.Equal(expected, GetAccounting(req.appId).Check(path)) } } diff --git a/authenticate/authenticate.go b/authenticate/authenticate.go index f03145b..eb6aa2e 100644 --- a/authenticate/authenticate.go +++ b/authenticate/authenticate.go @@ -4,6 +4,8 @@ import ( "github.com/integration-system/isp-lib/config" "github.com/integration-system/isp-lib/utils" log "github.com/integration-system/isp-log" + "github.com/integration-system/isp-log/stdcodes" + "github.com/pkg/errors" "github.com/valyala/fasthttp" "google.golang.org/grpc/codes" "isp-gate-service/conf" @@ -11,7 +13,6 @@ import ( "isp-gate-service/routing" "isp-gate-service/service/veritification" "strconv" - "strings" "time" ) @@ -25,10 +26,10 @@ type authenticate struct { verify veritification.Verify } -func ReceiveConfiguration(conf conf.Authenticate) { +func ReceiveConfiguration(conf conf.Cache) { if conf.EnableCash { - if timeout, err := time.ParseDuration(conf.Timeout); err != nil { - log.Fatalf(log_code.ErrorConfigAuth, "invalid timeout '%s'", timeout) + if timeout, err := time.ParseDuration(conf.EvictTimeout); err != nil { + log.Fatalf(stdcodes.ModuleInvalidRemoteConfig, "invalid timeout '%s'", timeout) } else { auth.verify = veritification.NewCacheableVerify(timeout) } @@ -37,17 +38,11 @@ func ReceiveConfiguration(conf conf.Authenticate) { } } -func Do(ctx *fasthttp.RequestCtx) (int64, error) { +func Do(ctx *fasthttp.RequestCtx) (int32, error) { path := ctx.Path() - uri := strings.Replace(strings.ToLower(string(path)), "/", "", -1) //todo await routing - path = getPathWithoutPrefix(path) + pathStr := getPathWithoutPrefix(path) - var ( - err error - appId int - ) - - if _, ok := routing.AddressMap[string(path)]; !ok { + if _, ok := routing.AllMethods[pathStr]; !ok { return 0, createError(codes.Unimplemented) } @@ -56,11 +51,16 @@ func Do(ctx *fasthttp.RequestCtx) (int64, error) { } appToken := ctx.Request.Header.Peek(utils.ApplicationTokenHeader) + + var ( + err error + appId int32 = -1 + ) if len(appToken) == 0 { return 0, createError(codes.Unauthenticated) - } else if config.GetRemote().(*conf.RemoteConfig).TokenVerification.Enable { - if appId, err = validateToken.Application(string(appToken)); err != nil { - return 0, createError(codes.Unauthenticated, "application token parse") + } else if config.GetRemote().(*conf.RemoteConfig).Secrets.VerifyAppToken { + if appId, err = verifyToken.Application(string(appToken)); err != nil || appId == 0 { + return 0, createError(codes.Unauthenticated, "invalid token") } } @@ -70,14 +70,23 @@ func Do(ctx *fasthttp.RequestCtx) (int64, error) { return 0, createError(codes.Internal) } if len(verifiableKeys) != 4 { - return 0, createError(codes.Unauthenticated, "application token value") + return 0, createError(codes.Unauthenticated, "unknown token") + } + + applicationId, err := strconv.Atoi(verifiableKeys[utils.ApplicationIdHeader]) + if err != nil { + log.Error(log_code.ErrorAuthenticate, errors.WithMessagef(err, "parse appId from redis")) + return 0, createError(codes.Internal) + } + if appId != -1 && int32(applicationId) != appId { + return 0, createError(codes.Unauthenticated, "unknown application identity") } verifiableKeys[utils.DeviceTokenHeader] = string(ctx.Request.Header.Peek(utils.DeviceTokenHeader)) verifiableKeys[utils.UserTokenHeader] = string(ctx.Request.Header.Peek(utils.UserTokenHeader)) permittedToCall := false - verifiableKeys, permittedToCall, err = auth.verify.Identity(verifiableKeys, uri) + verifiableKeys, permittedToCall, err = auth.verify.Identity(verifiableKeys, pathStr) if err != nil { log.Error(log_code.ErrorAuthenticate, err) return 0, createError(codes.Internal) @@ -86,38 +95,32 @@ func Do(ctx *fasthttp.RequestCtx) (int64, error) { return 0, createError(codes.PermissionDenied) } - applicationId, err := strconv.Atoi(verifiableKeys[utils.ApplicationIdHeader]) - if err != nil || (appId != 0 && applicationId != appId) { - log.Error(log_code.ErrorAuthenticate, err) - return 0, createError(codes.Internal) - } - for key, value := range verifiableKeys { if value != "" { ctx.Request.Header.Set(key, value) } } - if _, ok := routing.InnerAddressMap[string(path)]; ok { + if _, ok := routing.InnerMethods[pathStr]; ok { adminToken := ctx.Request.Header.Peek("x-auth-admin") //todo const key - if validateToken.Admin(string(adminToken)) != nil { + if verifyToken.Admin(string(adminToken)) != nil { return 0, createError(codes.PermissionDenied) } } - return int64(applicationId), nil + return appId, nil } -func getPathWithoutPrefix(path []byte) []byte { +func getPathWithoutPrefix(path []byte) string { firstFound := false for i, value := range path { if value == '/' { if firstFound { - return path[i+1:] + return string(path[i+1:]) } else { firstFound = true } } } - return []byte{} + return "" } diff --git a/authenticate/token.go b/authenticate/token.go index bda69bc..2db7c0f 100644 --- a/authenticate/token.go +++ b/authenticate/token.go @@ -7,34 +7,35 @@ import ( "isp-gate-service/conf" ) -var validateToken token +var verifyToken token + +type appClaims struct { + *jwt.StandardClaims + AppId int32 +} type token struct{} func (t token) Admin(token string) error { - secret := config.GetRemote().(*conf.RemoteConfig).SecretSetting.Admin - _, err := t.parse(token, secret) + secret := config.GetRemote().(*conf.RemoteConfig).Secrets.Admin + _, err := t.parse(token, secret, jwt.MapClaims{}) return err } -func (t token) Application(token string) (int, error) { - secret := config.GetRemote().(*conf.RemoteConfig).SecretSetting.Application +func (t token) Application(token string) (int32, error) { + secret := config.GetRemote().(*conf.RemoteConfig).Secrets.Application - if parsed, err := t.parse(token, secret); err != nil { + if parsed, err := t.parse(token, secret, &appClaims{StandardClaims: &jwt.StandardClaims{}}); err != nil { return 0, err - } else if claims, ok := parsed.Claims.(jwt.MapClaims); !ok { - return 0, errors.New("token is invalid") - } else if appId, ok := claims["appId"]; !ok { - return 0, errors.New("token is invalid") - } else if applicationId, ok := appId.(float64); !ok { + } else if claims, ok := parsed.Claims.(*appClaims); !ok { return 0, errors.New("token is invalid") } else { - return int(applicationId), nil + return claims.AppId, nil } } -func (token) parse(token, secret string) (*jwt.Token, error) { - if parsed, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) { +func (token) parse(token, secret string, claims jwt.Claims) (*jwt.Token, error) { + if parsed, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, errors.Errorf("unexpected signing method: %v", token.Header["alg"]) } diff --git a/conf/default_remote_config.json b/conf/default_remote_config.json index 8d95f14..849c096 100644 --- a/conf/default_remote_config.json +++ b/conf/default_remote_config.json @@ -1,13 +1,4 @@ { - "journal": { - "enableRemoteTransfer": true, - "enable": false, - "compress": true, - "filename": "/var/log/isp-gate-service/runtime.log", - "maxSizeMb": 512, - "bufferSize": 4096, - "rotateTimeoutMs": 86400000 - }, "metrics": { "gc": true, "memory": true, @@ -26,18 +17,7 @@ }, "accountingSetting": { "enable": false, - "setting": [ - { - "limits": [ - { - "pattern": "/healthcheck/module/group/method", - "timeout": "1s", - "maxCount": 1000 - } - ], - "applicationId": 1 - } - ] + "setting": [] }, "redis": { "address": { @@ -45,16 +25,14 @@ "port": "6379" } }, - "tokenVerification": { - "enable": false + "authCacheSetting": { + "evictTimeout": "1m", + "enableCash": false }, - "authenticateSetting": { - "timeout": "1m", - "enableCash": true - }, - "secretSetting": { + "secrets": { "admin": "secret", - "application": "secret" + "application": "SECRET_ACCESS_KEY", + "verifyAppToken": false }, "journalSetting": { "journal": { @@ -65,6 +43,7 @@ "filename": "/var/log/isp-gate-service/runtime.log", "maxSizeMb": 512, "bufferSize": 4096 - } + }, + "methodsPatterns": [] } -} \ No newline at end of file +} diff --git a/conf/remote_config.go b/conf/remote_config.go index 0e6192c..c00f8f2 100644 --- a/conf/remote_config.go +++ b/conf/remote_config.go @@ -20,20 +20,19 @@ const ( type ( RemoteConfig struct { - TokenVerification TokenVerification `schema:"Настройка веритификации токенов"` - SecretSetting SecretSetting `schema:"Настройка секретов"` - ServerSetting ServerSetting `schema:"Настройка сервера"` - GrpcSetting GrpcSetting `schema:"Настройка grpc соединения"` - Metrics structure.MetricConfiguration `schema:"Настройка метрик"` - JournalSetting Journal `schema:"Настройка журалирования"` - Redis structure.RedisConfiguration `schema:"Настройка Redis" valid:"required~Required"` - AccountingSetting Accounting `schema:"Настройка учета запросов"` - AuthenticateSetting Authenticate `schema:"Настройка авторизации" valid:"required~Required"` + Secrets SecretSetting `schema:"Настройка секретов"` + ServerSetting HttpSetting `schema:"Настройка сервера"` + GrpcSetting GrpcSetting `schema:"Настройка grpc соединения"` + Metrics structure.MetricConfiguration `schema:"Настройка метрик"` + JournalSetting Journal `schema:"Настройка журалирования"` + Redis structure.RedisConfiguration `schema:"Настройка Redis" valid:"required~Required"` + AccountingSetting Accounting `schema:"Настройка учета запросов"` + AuthCacheSetting Cache `schema:"Настройка кеширования данных аутентификации приложений" valid:"required~Required"` } - Authenticate struct { - EnableCash bool `schema:"Включает сохранение информации о авторизации токена"` - Timeout string `schema:"Время жизни информации в кеше"` + Cache struct { + EnableCash bool `schema:"Кеширование,включает кеширования для токена приложения"` + EvictTimeout string `schema:"Время жизни записи в кеше"` } Journal struct { @@ -41,13 +40,10 @@ type ( MethodsPatterns []string `schema:"Список методов для логирования,список строк вида: 'module/group/method'(* - для частичного совпадения). При обработке запроса, если вызываемый метод совпадает со строкой из списка, тела запроса и ответа записываются в лог"` } - TokenVerification struct { - Enable bool `schema:"Включает проверку application-токена"` - } - SecretSetting struct { - Admin string `schema:"Секрет admin-токена"` - Application string `schema:"Секрет application-токена"` + Admin string `schema:"Секрет для проверки токена администратора"` + Application string `schema:"Секрет для проверки токена приложений"` + VerifyAppToken bool `schema:"Проверка подписи токена приложений"` } Accounting struct { @@ -56,7 +52,7 @@ type ( } AccountingSetting struct { - ApplicationId int64 `valid:"required~Required" schema:"Идентификатор приложения"` + ApplicationId int32 `valid:"required~Required" schema:"Идентификатор приложения"` Limits []LimitSetting `schema:"Настройка ограничений на запросы"` } @@ -66,7 +62,7 @@ type ( Timeout string `schema:"Время жизни одного запроса"` } - ServerSetting struct { + HttpSetting struct { MaxRequestBodySizeBytes int64 `schema:"Максимальный размер тела запроса,в байтайх, по умолчанию: 512 MB"` } @@ -100,7 +96,7 @@ func (cfg GrpcSetting) GetTransferFileBufferSize() int64 { return cfg.MultipartDataTransferBufferSizeBytes } -func (cfg ServerSetting) GetMaxRequestBodySize() int64 { +func (cfg HttpSetting) GetMaxRequestBodySize() int64 { if cfg.MaxRequestBodySizeBytes <= 0 { return defaultMaxRequestBodySize } diff --git a/handler/handler.go b/handler/handler.go index b0501c3..16cf58d 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -57,6 +57,13 @@ func CompleteRequest(ctx *fasthttp.RequestCtx) { func (handlerHelper) AuthenticateApproveProxy(ctx *fasthttp.RequestCtx) domain.ProxyResponse { path := string(ctx.Path()) + p := proxy.Find(path) + if p == nil { + err := errors.Errorf("unknown path %s", path) + utils.WriteError(ctx, "not found", codes.NotFound, nil) + return domain.Create().SetError(err) + } + applicationId, err := authenticate.Do(ctx) if err != nil { status := codes.Unknown @@ -70,20 +77,13 @@ func (handlerHelper) AuthenticateApproveProxy(ctx *fasthttp.RequestCtx) domain.P return domain.Create().SetError(err) } - if approver := accounting.GetAccounting(applicationId); approver != nil && !approver.TakeAccount(path) { + if approver := accounting.GetAccounting(applicationId); approver != nil && !approver.Check(path) { err := errors.New("accounting error") utils.WriteError(ctx, "forbidden", codes.ResourceExhausted, nil) return domain.Create().SetError(err) } - p := proxy.Find(path) - if p != nil { - return p.ProxyRequest(ctx) - } else { - err := errors.Errorf("unknown path %s", path) - utils.WriteError(ctx, "not found", codes.NotFound, nil) - return domain.Create().SetError(err) - } + return p.ProxyRequest(ctx) } func (handlerHelper) SetMetricStatus(statusCode int) string { diff --git a/log_code/code.go b/log_code/code.go index 74c6895..b2bfac8 100644 --- a/log_code/code.go +++ b/log_code/code.go @@ -8,15 +8,11 @@ const ( WarnHttpServerShutdown = 602 ErrorHttpServerListen = 603 - FatalLocalConfig = 610 - ErrorClientGrpc = 606 - ErrorClientHttp = 611 + ErrorClientGrpc = 606 + ErrorClientHttp = 611 ErrorClientJournal = 608 ErrorClientRedis = 609 ErrorAuthenticate = 612 - - FatalConfigApproveSetting = 613 - ErrorConfigAuth = 614 ) diff --git a/main.go b/main.go index b057860..a984f4d 100644 --- a/main.go +++ b/main.go @@ -8,11 +8,11 @@ import ( "github.com/integration-system/isp-lib/metric" "github.com/integration-system/isp-lib/structure" log "github.com/integration-system/isp-log" + "github.com/integration-system/isp-log/stdcodes" "isp-gate-service/accounting" "isp-gate-service/authenticate" "isp-gate-service/conf" "isp-gate-service/journal" - "isp-gate-service/log_code" "isp-gate-service/proxy" "isp-gate-service/redis" "isp-gate-service/routing" @@ -41,7 +41,7 @@ func main() { for _, location := range cfg.Locations { if p, err := proxy.Init(location); err != nil { - log.Fatal(log_code.FatalLocalConfig, err) + log.Fatal(stdcodes.ModuleInvalidLocalConfig, err) } else if location.TargetModule != "" { bs.RequireModule(location.TargetModule, p.Consumer, false) } @@ -63,13 +63,14 @@ func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) { matcher.JournalMethods = matcher.NewAtLeastOneMatcher(remoteConfig.JournalSetting.MethodsPatterns) redis.Client.ReceiveConfiguration(remoteConfig.Redis) - server.Http.Init(remoteConfig.ServerSetting.GetMaxRequestBodySize()) accounting.ReceiveConfiguration(remoteConfig.AccountingSetting) - authenticate.ReceiveConfiguration(remoteConfig.AuthenticateSetting) + authenticate.ReceiveConfiguration(remoteConfig.AuthCacheSetting) metric.InitCollectors(remoteConfig.Metrics, oldRemoteConfig.Metrics) metric.InitHttpServer(remoteConfig.Metrics) service.Metrics.Init() + + server.Http.Init(remoteConfig.ServerSetting.GetMaxRequestBodySize()) } func socketConfiguration(cfg interface{}) structure.SocketConfiguration { @@ -86,9 +87,9 @@ func socketConfiguration(cfg interface{}) structure.SocketConfiguration { } func onShutdown(_ context.Context, _ os.Signal) { + server.Http.Close() proxy.Close() redis.Client.Close() - server.Http.Close() } func handleRouteUpdate(configs structure.RoutingConfig) bool { diff --git a/routing/routing.go b/routing/routing.go index 19a2c81..b4b6c2d 100644 --- a/routing/routing.go +++ b/routing/routing.go @@ -5,8 +5,8 @@ import ( ) var ( - InnerAddressMap = make(map[string]bool) - AddressMap = make(map[string]bool) + InnerMethods = make(map[string]bool) + AllMethods = make(map[string]bool) ) func InitRoutes(configs structure.RoutingConfig) { @@ -23,6 +23,6 @@ func InitRoutes(configs structure.RoutingConfig) { } } } - AddressMap = newAddressMap - InnerAddressMap = newInnerAddressMap + AllMethods = newAddressMap + InnerMethods = newInnerAddressMap }