MSP-625 reimplement authenticate
This commit is contained in:
1 parent
538e9a7aab
commit
668cbb37d2
7 files changed
+33
-504
No files matched your search
@@ -1,188 +0,0 @@
|
||||
package authenticate
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/integration-system/isp-lib/v2/config"
|
||||
"github.com/integration-system/isp-lib/v2/utils"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"github.com/pkg/errors"
|
||||
"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"
|
||||
)
|
||||
|
||||
const (
|
||||
// TODO move to isp-lib
|
||||
AdminTokenHeader = "x-auth-admin"
|
||||
|
||||
awaitLengthVerifiableHeaders = 4
|
||||
)
|
||||
|
||||
var notExpectedHeaders = []string{
|
||||
utils.SystemIdHeader,
|
||||
utils.DomainIdHeader,
|
||||
utils.ServiceIdHeader,
|
||||
utils.ApplicationIdHeader,
|
||||
utils.UserIdHeader,
|
||||
utils.DeviceIdHeader,
|
||||
}
|
||||
|
||||
var verify = veritification.NewRuntimeVerify()
|
||||
|
||||
type verifiable struct {
|
||||
appId int32
|
||||
adminId int64
|
||||
ctx *fasthttp.RequestCtx
|
||||
path string
|
||||
headers map[string]string
|
||||
}
|
||||
|
||||
func Do(ctx *fasthttp.RequestCtx, path string) (int32, int64, error) {
|
||||
for _, notExpectedHeader := range notExpectedHeaders {
|
||||
ctx.Request.Header.Del(notExpectedHeader)
|
||||
}
|
||||
|
||||
verifiable := newVerifiable(ctx, path)
|
||||
err := verifiable.verifyAppToken()
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
err = verifiable.verifyUserToken()
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
verifiable.setHeaders()
|
||||
|
||||
err = verifiable.checkInnerMethods()
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
err = verifiable.checkUserMethods()
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
return verifiable.appId, verifiable.adminId, nil
|
||||
}
|
||||
|
||||
func newVerifiable(ctx *fasthttp.RequestCtx, path string) *verifiable {
|
||||
return &verifiable{
|
||||
ctx: ctx,
|
||||
path: path,
|
||||
appId: -1,
|
||||
adminId: -1,
|
||||
headers: make(map[string]string),
|
||||
}
|
||||
}
|
||||
|
||||
func (v *verifiable) verifyAppToken() error {
|
||||
appToken := v.getParam(utils.ApplicationTokenHeader)
|
||||
var err error
|
||||
|
||||
if len(appToken) == 0 {
|
||||
return createError("unauthorized", codes.Unauthenticated, "application token required")
|
||||
} else if config.GetRemote().(*conf.RemoteConfig).TokensSetting.ApplicationVerify {
|
||||
if v.appId, err = verifyToken.Application(string(appToken)); err != nil || v.appId == 0 {
|
||||
return createError("unauthorized", codes.Unauthenticated, "received invalid application token")
|
||||
}
|
||||
}
|
||||
|
||||
verifiableHeaders, err := verify.ApplicationToken(string(appToken))
|
||||
if err != nil {
|
||||
log.Error(log_code.ErrorAuthenticate, err)
|
||||
return createError("internal Server error", codes.Internal)
|
||||
}
|
||||
if len(verifiableHeaders) != awaitLengthVerifiableHeaders {
|
||||
return createError("unauthorized", codes.Unauthenticated, "received unexpected identities")
|
||||
}
|
||||
|
||||
applicationId, err := strconv.ParseInt(verifiableHeaders[utils.ApplicationIdHeader], 10, 32) //nolint
|
||||
if err != nil {
|
||||
log.Error(log_code.ErrorAuthenticate, errors.WithMessagef(err, "parse appId from redis"))
|
||||
return createError("internal Server error", codes.Internal)
|
||||
}
|
||||
//nolint
|
||||
if v.appId != -1 && int32(applicationId) != v.appId {
|
||||
return createError("unauthorized", codes.Unauthenticated, "received unexpected application identity")
|
||||
}
|
||||
|
||||
v.appId = int32(applicationId)
|
||||
v.headers = verifiableHeaders
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *verifiable) verifyUserToken() error {
|
||||
userToken := string(v.getParam(utils.UserTokenHeader))
|
||||
if userToken != "" {
|
||||
userId, err := verifyToken.User(userToken)
|
||||
if err != nil {
|
||||
return createError("unauthorized", codes.Unauthenticated, "received invalid user token")
|
||||
}
|
||||
v.headers[utils.UserIdHeader] = userId
|
||||
}
|
||||
v.headers[utils.UserTokenHeader] = userToken
|
||||
|
||||
v.headers[utils.DeviceTokenHeader] = string(v.getParam(utils.DeviceTokenHeader))
|
||||
|
||||
var err error
|
||||
v.headers, err = verify.Identity(v.headers, v.path)
|
||||
if err != nil {
|
||||
switch err {
|
||||
case veritification.ErrorInvalidUserId:
|
||||
return createError("unauthorized", codes.Unauthenticated, err.Error())
|
||||
case veritification.ErrorPermittedToCallUser, veritification.ErrorPermittedToCallApplication:
|
||||
return createError("forbidden", codes.PermissionDenied, err.Error())
|
||||
default:
|
||||
return createError("internal server error", codes.Internal)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *verifiable) setHeaders() {
|
||||
for key, value := range v.headers {
|
||||
if value != "" {
|
||||
v.ctx.Request.Header.Set(key, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (v *verifiable) checkInnerMethods() error {
|
||||
_, ok := routing.InnerMethods[v.path]
|
||||
if ok {
|
||||
adminToken := string(v.getParam(AdminTokenHeader))
|
||||
if adminToken == "" {
|
||||
return createError("unauthorized", codes.Unauthenticated, "admin token required")
|
||||
}
|
||||
adminId, err := verifyToken.Admin(adminToken)
|
||||
if err != nil {
|
||||
return createError("unauthorized", codes.Unauthenticated, "received invalid admin token")
|
||||
}
|
||||
v.adminId = adminId
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *verifiable) checkUserMethods() error {
|
||||
if v.headers[utils.UserIdHeader] == "" {
|
||||
if _, ok := routing.AuthUserMethods[v.path]; ok {
|
||||
return createError("unauthorized", codes.Unauthenticated, "user token required")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *verifiable) getParam(key string) []byte {
|
||||
val := v.ctx.Request.Header.Peek(key)
|
||||
if len(val) != 0 {
|
||||
return val
|
||||
}
|
||||
return v.ctx.Request.URI().QueryArgs().Peek(key)
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package authenticate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"google.golang.org/grpc/codes"
|
||||
)
|
||||
|
||||
func createError(msg string, status codes.Code, details ...interface{}) error {
|
||||
return ErrorDescription{message: msg, grpcStatus: status, details: details}
|
||||
}
|
||||
|
||||
type ErrorDescription struct {
|
||||
message string
|
||||
grpcStatus codes.Code
|
||||
details []interface{}
|
||||
}
|
||||
|
||||
func (e ErrorDescription) Error() string {
|
||||
return fmt.Sprintf("code: %v, message: %s, details: %v", e.grpcStatus, e.message, e.details)
|
||||
}
|
||||
|
||||
func (e ErrorDescription) Message() string {
|
||||
return e.message
|
||||
}
|
||||
|
||||
func (e ErrorDescription) ConvertToGrpcStatus() codes.Code {
|
||||
return e.grpcStatus
|
||||
}
|
||||
|
||||
func (e ErrorDescription) Details() []interface{} {
|
||||
return e.details
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
package authenticate
|
||||
|
||||
import (
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"github.com/integration-system/isp-lib/v2/config"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/spf13/cast"
|
||||
"isp-gate-service/conf"
|
||||
)
|
||||
|
||||
var (
|
||||
errInvalidToken = errors.New("invalid token")
|
||||
verifyToken token
|
||||
)
|
||||
|
||||
type appClaims struct {
|
||||
*jwt.StandardClaims
|
||||
AppId int32
|
||||
}
|
||||
|
||||
type userClaims struct {
|
||||
*jwt.StandardClaims
|
||||
UserId int64
|
||||
}
|
||||
|
||||
type adminClaims struct {
|
||||
*jwt.StandardClaims
|
||||
Id int64
|
||||
}
|
||||
|
||||
type token struct{}
|
||||
|
||||
func (t token) Admin(token string) (int64, error) {
|
||||
secret := config.GetRemote().(*conf.RemoteConfig).TokensSetting.AdminSecret
|
||||
parsed, err := t.parse(token, secret, &adminClaims{StandardClaims: &jwt.StandardClaims{}})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
claims, ok := parsed.Claims.(*adminClaims)
|
||||
if !ok {
|
||||
return 0, errInvalidToken
|
||||
}
|
||||
return claims.Id, nil
|
||||
}
|
||||
|
||||
func (t token) Application(token string) (int32, error) {
|
||||
secret := config.GetRemote().(*conf.RemoteConfig).TokensSetting.ApplicationSecret
|
||||
|
||||
parsed, err := t.parse(token, secret, &appClaims{StandardClaims: &jwt.StandardClaims{}})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
claims, ok := parsed.Claims.(*appClaims)
|
||||
if !ok {
|
||||
return 0, errInvalidToken
|
||||
}
|
||||
return claims.AppId, nil
|
||||
}
|
||||
|
||||
func (t token) User(token string) (string, error) {
|
||||
secret := config.GetRemote().(*conf.RemoteConfig).TokensSetting.UserSecret
|
||||
|
||||
parsed, err := t.parse(token, secret, &userClaims{StandardClaims: &jwt.StandardClaims{}})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
claims, ok := parsed.Claims.(*userClaims)
|
||||
if !ok {
|
||||
return "", errInvalidToken
|
||||
}
|
||||
|
||||
return cast.ToString(claims.UserId), nil
|
||||
}
|
||||
|
||||
func (token) parse(token, secret string, claims jwt.Claims) (*jwt.Token, error) {
|
||||
parsed, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
|
||||
_, ok := token.Method.(*jwt.SigningMethodHMAC)
|
||||
if !ok {
|
||||
return nil, errors.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(secret), nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !parsed.Valid {
|
||||
return nil, errInvalidToken
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
"isp-gate-service/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
adminTokenHeader = "x-auth-admin"
|
||||
)
|
||||
|
||||
type AdminAuthenticate interface {
|
||||
Authenticate(token string) (int, error)
|
||||
}
|
||||
|
||||
func Authenticate(adminAuthenticate AdminAuthenticate) Middleware {
|
||||
return func(next Handler) Handler {
|
||||
return HandlerFunc(func(ctx *Context) error {
|
||||
ctx.AppId = 1 // todo application
|
||||
|
||||
adminToken := ctx.Request.Header.Get(adminTokenHeader)
|
||||
adminId, err := adminAuthenticate.Authenticate(adminToken)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(domain.ErrAuthenticate, "admin athenticate: %v", err)
|
||||
}
|
||||
ctx.AdminId = adminId
|
||||
|
||||
ctx.authenticated = true
|
||||
|
||||
return next.Handle(ctx)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
rd "github.com/integration-system/isp-lib/v2/redis"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-gate-service/log_code"
|
||||
)
|
||||
|
||||
var (
|
||||
Client = rd.NewRxClient(
|
||||
rd.WithInitHandler(func(c *rd.Client, err error) {
|
||||
if err != nil {
|
||||
log.Fatal(log_code.ErrorClientRedis, err)
|
||||
}
|
||||
}))
|
||||
)
|
||||
@@ -1,168 +0,0 @@
|
||||
package veritification
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
rd "github.com/go-redis/redis/v8"
|
||||
"github.com/integration-system/isp-lib/v2/config"
|
||||
"github.com/integration-system/isp-lib/v2/redis"
|
||||
"github.com/integration-system/isp-lib/v2/utils"
|
||||
"github.com/pkg/errors"
|
||||
"isp-gate-service/conf"
|
||||
rdClient "isp-gate-service/redis"
|
||||
)
|
||||
|
||||
const (
|
||||
permittedToCallInfo = "0"
|
||||
|
||||
appIdArrayKey = 1
|
||||
userTokenArrayKey = 3
|
||||
userIdArrayKey = 5
|
||||
deviceTokenArrayKey = 7
|
||||
)
|
||||
|
||||
var (
|
||||
errNoRedisCmd = errors.New("no redis cmd")
|
||||
errUnexpectedCmd = errors.New("expected StringCmd")
|
||||
headerKeyByRedisIdentity = map[string]string{
|
||||
"1": utils.SystemIdHeader,
|
||||
"2": utils.DomainIdHeader,
|
||||
"3": utils.ServiceIdHeader,
|
||||
"4": utils.ApplicationIdHeader,
|
||||
}
|
||||
)
|
||||
|
||||
type runtimeVerify struct{}
|
||||
|
||||
func (v *runtimeVerify) ApplicationToken(token string) (map[string]string, error) {
|
||||
instanceUuid := config.Get().(*conf.Configuration).InstanceUuid
|
||||
key := makeDbKey(token, instanceUuid)
|
||||
|
||||
resp, err := rdClient.Client.UseDb(redis.ApplicationTokenDb, func(p rd.Pipeliner) error {
|
||||
if cmd := p.HGetAll(context.Background(), key); v.isError(cmd.Err()) {
|
||||
return cmd.Err()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(resp) < 2 || resp[1].Err() == rd.Nil {
|
||||
return nil, nil
|
||||
} else if resp[1].Err() != nil {
|
||||
return nil, err
|
||||
} else if stringStringMapCmd, ok := resp[1].(*rd.StringStringMapCmd); !ok {
|
||||
return nil, errUnexpectedCmd
|
||||
} else {
|
||||
vals := stringStringMapCmd.Val()
|
||||
identityMap := make(map[string]string, len(vals))
|
||||
for i, value := range vals {
|
||||
identityMap[headerKeyByRedisIdentity[i]] = value
|
||||
}
|
||||
return identityMap, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (v *runtimeVerify) Identity(t map[string]string, uri string) (map[string]string, error) {
|
||||
secondDbKey := makeDbKey(t[utils.ApplicationIdHeader], uri)
|
||||
thirdDbKey := makeDbKey(t[utils.UserTokenHeader], t[utils.DomainIdHeader])
|
||||
fourthDbKey := makeDbKey(t[utils.UserIdHeader], uri)
|
||||
fifthDbKey := makeDbKey(t[utils.DeviceTokenHeader], t[utils.DomainIdHeader])
|
||||
|
||||
resp, err := rdClient.Client.Pipelined(context.Background(), func(p rd.Pipeliner) error {
|
||||
if _, err := p.Select(context.Background(), int(redis.ApplicationPermissionDb)).Result(); v.isError(err) {
|
||||
return err
|
||||
}
|
||||
if _, err := p.Get(context.Background(), secondDbKey).Result(); v.isError(err) {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := p.Select(context.Background(), int(redis.UserTokenDb)).Result(); v.isError(err) {
|
||||
return err
|
||||
}
|
||||
if _, err := p.Get(context.Background(), thirdDbKey).Result(); v.isError(err) {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := p.Select(context.Background(), int(redis.UserPermissionDb)).Result(); v.isError(err) {
|
||||
return err
|
||||
}
|
||||
if _, err := p.Get(context.Background(), fourthDbKey).Result(); v.isError(err) {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := p.Select(context.Background(), int(redis.DeviceTokenDb)).Result(); v.isError(err) {
|
||||
return err
|
||||
}
|
||||
if _, err := p.Get(context.Background(), fifthDbKey).Result(); v.isError(err) {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if v.isError(err) {
|
||||
return t, err
|
||||
}
|
||||
// ===== NOT PERMITTED BY APPLICATION ID =====
|
||||
msg, err := v.findStringCmd(resp, appIdArrayKey)
|
||||
if err != nil {
|
||||
return t, err
|
||||
}
|
||||
if msg == permittedToCallInfo {
|
||||
return t, ErrorPermittedToCallApplication
|
||||
}
|
||||
// ===== CHECK USER TOKEN =====
|
||||
msg, err = v.findStringCmd(resp, userTokenArrayKey)
|
||||
if err != nil {
|
||||
return t, err
|
||||
}
|
||||
userIdentity, found := t[utils.UserIdHeader]
|
||||
if found && msg != userIdentity {
|
||||
return t, ErrorInvalidUserId
|
||||
}
|
||||
// ===== NOT PERMITTED BY USER ID =====
|
||||
msg, err = v.findStringCmd(resp, userIdArrayKey)
|
||||
if err != nil {
|
||||
return t, err
|
||||
}
|
||||
if msg == permittedToCallInfo {
|
||||
return t, ErrorPermittedToCallUser
|
||||
}
|
||||
// ===== CHECK DEVICE TOKEN =====
|
||||
msg, err = v.findStringCmd(resp, deviceTokenArrayKey)
|
||||
if err != nil {
|
||||
return t, err
|
||||
}
|
||||
t[utils.DeviceIdHeader] = msg
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (v *runtimeVerify) isError(err error) bool {
|
||||
return err != nil && err != rd.Nil
|
||||
}
|
||||
|
||||
func (v *runtimeVerify) findStringCmd(cmders []rd.Cmder, arrayKey int) (string, error) {
|
||||
if len(cmders) <= arrayKey {
|
||||
return "", errNoRedisCmd
|
||||
}
|
||||
|
||||
cmd := cmders[arrayKey]
|
||||
if cmd == nil {
|
||||
return "", errNoRedisCmd
|
||||
}
|
||||
|
||||
if v.isError(cmd.Err()) {
|
||||
return "", cmd.Err()
|
||||
}
|
||||
|
||||
if stringCmd, ok := cmd.(*rd.StringCmd); !ok {
|
||||
return "", errUnexpectedCmd
|
||||
} else {
|
||||
return stringCmd.Val(), nil
|
||||
}
|
||||
}
|
||||
|
||||
func makeDbKey(key, val string) string {
|
||||
return key + "|" + val
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package veritification
|
||||
|
||||
type Verify interface {
|
||||
ApplicationToken(string) (map[string]string, error)
|
||||
Identity(map[string]string, string) (map[string]string, error)
|
||||
}
|
||||
|
||||
func NewRuntimeVerify() Verify {
|
||||
return &runtimeVerify{}
|
||||
}
|
||||
Reference in new issue
Block a user