add(jwt verify)

This commit is contained in:
DeniskaRediska committed 2019-11-13 17:32:42 +03:00
1 parent fc80638b76
commit 23ede62f24
11 files changed
+259 -77

No files matched your search

+43 -23
View File
@@ -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)
}
}
+7 -2
View File
@@ -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
}
+28 -8
View File
@@ -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
}
+29 -3
View File
@@ -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
}
}
}
+35 -8
View File
@@ -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
}
+5 -3
View File
@@ -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)
}
+3 -1
View File
@@ -15,6 +15,8 @@ const (
ErrorClientJournal = 608
ErrorClientRedis = 609
ErrorAuthenticate = 612
ErrorAuthenticate = 612
FatalConfigApproveSetting = 613
ErrorConfigAuth = 614
)
+7 -6
View File
@@ -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()
}
@@ -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)
}
@@ -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 {
+24
View File
@@ -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{},
}
}