This commit is contained in:
ykomissarov committed 2019-11-15 13:27:34 +03:00
1 parent 23ede62f24
commit 0e3c14d099
12 files changed
+112 -132

No files matched your search

+1 -1
View File
@@ -1 +1 @@
1.0.0
1.1.0
+4
View File
@@ -0,0 +1,4 @@
## 1.1.0
* add token verification via JWT
* add accounting for applications
* add optional cache for application tokens
+6 -6
View File
@@ -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 {
+5 -5
View File
@@ -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))
}
}
+33 -30
View File
@@ -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 ""
}
+15 -14
View File
@@ -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"])
}
+10 -31
View File
@@ -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": []
}
}
}
+17 -21
View File
@@ -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
}
+9 -9
View File
@@ -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 {
+2 -6
View File
@@ -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
)
+6 -5
View File
@@ -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 {
+4 -4
View File
@@ -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
}