From 23ede62f24427cc1f432746082e89891256b40b1 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Wed, 13 Nov 2019 17:32:42 +0300 Subject: [PATCH] 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{}, + } +}