This commit is contained in:
DeniskaRediska committed 2019-10-24 14:37:22 +03:00
1 parent f3934e038e
commit 4fdf7c0ca2
19 files changed
+457 -379

No files matched your search

+1 -1
View File
@@ -1 +1 @@
0.0.4
0.0.5
+35 -30
View File
@@ -2,51 +2,56 @@ package authenticate
import (
"github.com/integration-system/isp-lib/utils"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"isp-gate-service/redis"
"google.golang.org/grpc/codes"
"strings"
)
var redisKeyHeaderKeyMap = map[string]string{
redis.SystemIdentity: utils.SystemIdHeader,
redis.DomainIdentity: utils.DomainIdHeader,
redis.ServiceIdentity: utils.ServiceIdHeader,
redis.ApplicationIdentity: utils.ApplicationIdHeader,
redis.DeviceIdentity: utils.DeviceIdHeader,
redis.UserIdentity: utils.UserIdHeader,
redis.DeviceToken: utils.DeviceTokenHeader,
redis.UserToken: utils.UserTokenHeader,
}
func Compete(ctx *fasthttp.RequestCtx) error {
for _, notExpectedHeader := range []string{
var (
verifiableKeyHeaderKeyMap = map[string]string{
SystemIdentity: utils.SystemIdHeader,
DomainIdentity: utils.DomainIdHeader,
ServiceIdentity: utils.ServiceIdHeader,
ApplicationIdentity: utils.ApplicationIdHeader,
DeviceIdentity: utils.DeviceIdHeader,
UserIdentity: utils.UserIdHeader,
DeviceToken: utils.DeviceTokenHeader,
UserToken: utils.UserTokenHeader,
}
notExpectedHeaders = []string{
utils.SystemIdHeader, utils.DomainIdHeader, utils.ServiceIdHeader, utils.ApplicationIdHeader,
} {
}
)
func Do(ctx *fasthttp.RequestCtx) error {
for _, notExpectedHeader := range notExpectedHeaders {
ctx.Request.Header.Del(notExpectedHeader)
}
appToken := ctx.Request.Header.Peek(utils.ApplicationTokenHeader)
if len(appToken) == 0 {
return errors.Errorf("%s not found", utils.ApplicationTokenHeader)
return Error.Create(codes.Unauthenticated)
}
tokens, err := redis.Client.GetTokens(string(appToken))
if err != nil || len(tokens) != 4 {
return errors.Errorf("redis error %v", err)
}
tokens[redis.Uri] = strings.Replace(strings.ToLower(string(ctx.Path())), "/", "", -1)
tokens[redis.DeviceToken] = string(ctx.Request.Header.Peek(utils.DeviceTokenHeader))
tokens[redis.UserToken] = string(ctx.Request.Header.Peek(utils.UserTokenHeader))
tokens, err = redis.Client.CheckTokens(tokens)
verifiableKeys, err := verification.appToken(string(appToken))
if err != nil {
return err
}
delete(tokens, redis.Uri)
for key, value := range tokens {
if len(verifiableKeys) != 4 {
return Error.Create(codes.Unauthenticated)
}
uri := strings.Replace(strings.ToLower(string(ctx.Path())), "/", "", -1)
verifiableKeys[DeviceToken] = string(ctx.Request.Header.Peek(utils.DeviceTokenHeader))
verifiableKeys[UserToken] = string(ctx.Request.Header.Peek(utils.UserTokenHeader))
verifiableKeys, err = verification.keys(verifiableKeys, uri)
if err != nil {
return err
}
for key, value := range verifiableKeys {
if value != "" {
ctx.Request.Header.Set(redisKeyHeaderKeyMap[key], value)
ctx.Request.Header.Set(verifiableKeyHeaderKeyMap[key], value)
}
}
return nil
+27
View File
@@ -0,0 +1,27 @@
package authenticate
import (
"fmt"
"google.golang.org/grpc/codes"
)
var Error errorHelper
func (errorHelper) Create(status codes.Code) ErrorDescription {
return ErrorDescription{grpcStatus: status}
}
type (
errorHelper struct{}
ErrorDescription struct {
grpcStatus codes.Code
}
)
func (e ErrorDescription) Error() string {
return fmt.Sprintf("%v", e)
}
func (e ErrorDescription) ConvertToGrpcStatus() codes.Code {
return e.grpcStatus
}
+120
View File
@@ -0,0 +1,120 @@
package authenticate
import (
"fmt"
rd "github.com/go-redis/redis"
"github.com/integration-system/isp-lib/config"
"github.com/integration-system/isp-lib/redis"
"google.golang.org/grpc/codes"
"isp-gate-service/conf"
rdClient "isp-gate-service/redis"
)
const (
SystemIdentity = "1"
DomainIdentity = "2"
ServiceIdentity = "3"
ApplicationIdentity = "4"
DeviceIdentity = "5"
UserIdentity = "6"
DeviceToken = "7"
UserToken = "8"
)
var verification verificationHelper
type verificationHelper struct{}
func (v verificationHelper) appToken(token string) (map[string]string, error) {
instanceUuid := config.Get().(*conf.Configuration).InstanceUuid
key := fmt.Sprintf("%s|%s", token, instanceUuid)
if resp, err := rdClient.Client.Get().Pipelined(func(p rd.Pipeliner) error {
if cmd := p.Select(int(redis.ApplicationTokenDb)); v.notEmptyError(cmd.Err()) {
return cmd.Err()
}
if cmd := p.HGetAll(key); v.notEmptyError(cmd.Err()) {
return cmd.Err()
}
return nil
}); err != nil {
return nil, Error.Create(codes.Internal)
} else {
if len(resp) < 2 || resp[1].Err() == rd.Nil {
return nil, nil
} else if resp[1].Err() != nil {
return nil, Error.Create(codes.Unauthenticated)
} else if stringStringMapCmd, ok := resp[1].(*rd.StringStringMapCmd); !ok {
return nil, nil
} else {
return stringStringMapCmd.Val(), nil
}
}
}
func (v *verificationHelper) keys(t map[string]string, uri string) (map[string]string, error) {
secondDbKey := fmt.Sprintf("%s|%s", t[ApplicationIdentity], uri)
thirdDbKey := fmt.Sprintf("%s|%s", t[UserToken], t[DomainIdentity])
fifthDbKey := fmt.Sprintf("%s|%s", t[DeviceToken], t[DomainIdentity])
if resp, err := rdClient.Client.Get().Pipelined(func(p rd.Pipeliner) error {
if cmd := p.Select(int(redis.ApplicationPermissionDb)); v.notEmptyError(cmd.Err()) {
return cmd.Err()
}
if cmd := p.Get(secondDbKey); v.notEmptyError(cmd.Err()) {
return cmd.Err()
}
if cmd := p.Select(int(redis.UserTokenDb)); v.notEmptyError(cmd.Err()) {
return cmd.Err()
}
if cmd := p.Get(thirdDbKey); v.notEmptyError(cmd.Err()) {
return cmd.Err()
}
if cmd := p.Select(int(redis.DeviceTokenDb)); v.notEmptyError(cmd.Err()) {
return cmd.Err()
}
if cmd := p.Get(fifthDbKey); v.notEmptyError(cmd.Err()) {
return cmd.Err()
}
return nil
}); err != nil && err != rd.Nil {
return t, Error.Create(codes.Internal)
} else {
// It is not permitted to call this methodParts
if v.fineCmd(resp, 1) {
if intCmd, ok := resp[1].(*rd.IntCmd); ok && intCmd.Val() == 0 {
return t, Error.Create(codes.PermissionDenied)
}
}
// ===== CHECK USER TOKEN =====
if v.fineCmd(resp, 3) {
if stringCmd, ok := resp[3].(*rd.StringCmd); ok {
t[UserIdentity] = stringCmd.Val()
}
}
// ===== CHECK DEVICE TOKEN =====
if v.fineCmd(resp, 5) {
if stringCmd, ok := resp[5].(*rd.StringCmd); ok {
t[DeviceIdentity] = stringCmd.Val()
}
}
}
return t, nil
}
func (v *verificationHelper) notEmptyError(err error) bool {
return err != nil && err != rd.Nil
}
func (v *verificationHelper) fineCmd(cmders []rd.Cmder, arrayKey int) bool {
if len(cmders) > arrayKey+1 {
cmder := cmders[arrayKey]
return cmder != nil && (cmder.Err() == nil || cmder.Err() == rd.Nil)
} else {
return false
}
}
+8 -21
View File
@@ -1,28 +1,23 @@
package handler
import (
"encoding/json"
"github.com/integration-system/isp-lib/http"
"github.com/integration-system/isp-lib/structure"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"isp-gate-service/authenticate"
"isp-gate-service/proxy"
"isp-gate-service/utils"
)
func Complete(ctx *fasthttp.RequestCtx) {
path := string(ctx.Path())
if err := authenticate.Compete(ctx); err != nil {
statusCode := codes.Unauthenticated
response := structure.GrpcError{
ErrorMessage: "unauthenticated", ErrorCode: statusCode.String(),
Details: []interface{}{err},
if err := authenticate.Do(ctx); err != nil {
status := codes.Unknown
switch e := err.(type) {
case authenticate.ErrorDescription:
status = e.ConvertToGrpcStatus()
}
ctx.Response.Header.SetContentType("application/json; charset=utf-8")
ctx.SetStatusCode(http.CodeToHttpStatus(statusCode))
message, _ := json.Marshal(response)
_, _ = ctx.Write(message)
utils.SendError("authenticate error", status, nil, ctx)
return
}
@@ -30,14 +25,6 @@ func Complete(ctx *fasthttp.RequestCtx) {
if p != nil {
p.ProxyRequest(ctx)
} else {
statusCode := codes.NotFound
response := structure.GrpcError{
ErrorMessage: "unknown path", ErrorCode: statusCode.String(),
Details: []interface{}{map[string]string{"path": path}},
}
ctx.Response.Header.SetContentType("application/json; charset=utf-8")
ctx.SetStatusCode(http.CodeToHttpStatus(statusCode))
message, _ := json.Marshal(response)
_, _ = ctx.Write(message)
utils.SendError("unknown path", codes.NotFound, []interface{}{map[string]string{"path": path}}, ctx)
}
}
+4 -4
View File
@@ -1,8 +1,6 @@
package log_code
const (
InfoOnLocalConfigLoad = 601
WarnRequestHandler = 604 //metadata: {"typeData":"", "method":""}
WarnConvertErrorDataMarshalResponse = 605
ErrorGrpcClientDialing = 606
@@ -11,10 +9,12 @@ const (
ErrorClientJournal = 903
WarnCreateRestServerHttpSrvShutdown = 602
ErrorCreateRestServerHttpSrvListenAndServe = 603
WarnHttpServerShutdown = 602
ErrorHttpServerListen = 603
ErrorLocalConfig = 904
ErrorClientGrpc = 905
ErrorClientHttp = 906
ErrorClientRedis = 907
)
+3 -1
View File
@@ -48,7 +48,7 @@ func main() {
}
func onLocalConfigLoad(cfg *conf.Configuration) {
log.Infof(log_code.InfoOnLocalConfigLoad, "Outer http address is %s", cfg.HttpOuterAddress.GetAddress())
}
func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) {
@@ -81,6 +81,8 @@ func socketConfiguration(cfg interface{}) structure.SocketConfiguration {
func onShutdown(_ context.Context, _ os.Signal) {
proxy.Close()
redis.Client.Close()
server.Http.Close()
}
func makeDeclaration(localConfig interface{}) bootstrap.ModuleInfo {
+8 -4
View File
@@ -6,9 +6,12 @@ import (
log "github.com/integration-system/isp-log"
"github.com/valyala/fasthttp"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"isp-gate-service/conf"
"isp-gate-service/log_code"
"isp-gate-service/proxy/grpc/handlers"
"isp-gate-service/service"
"isp-gate-service/utils"
"net/http"
"time"
)
@@ -31,16 +34,17 @@ func NewProxy() *grpcProxy {
}
func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx) {
if p.client == nil {
log.Error(log_code.ErrorClientGrpc, "client undefined")
if p.client.InternalGrpcClient == nil {
msg := "client undefined"
log.Error(log_code.ErrorClientGrpc, msg)
utils.SendError(msg, codes.Internal, nil, ctx)
return
}
currentTime := time.Now()
uri := string(ctx.RequestURI())
SetHandler(ctx).Complete(ctx, uri, p.client)
handlers.Handler.Get(ctx).Complete(ctx, uri, p.client)
executionTime := time.Since(currentTime) / 1e6
service.Metrics.UpdateStatusCounter(ctx.Response.StatusCode())
+98 -27
View File
@@ -1,17 +1,27 @@
package handlers
import (
"github.com/golang/protobuf/proto"
structpb "github.com/golang/protobuf/ptypes/struct"
"github.com/integration-system/isp-lib/backend"
"github.com/integration-system/isp-lib/config"
http2 "github.com/integration-system/isp-lib/http"
isp "github.com/integration-system/isp-lib/proto/stubs"
s "github.com/integration-system/isp-lib/streaming"
"github.com/integration-system/isp-lib/structure"
"github.com/integration-system/isp-lib/utils"
log "github.com/integration-system/isp-log"
jsoniter "github.com/json-iterator/go"
"github.com/valyala/fasthttp"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"io"
"isp-gate-service/conf"
"isp-gate-service/log_code"
"isp-gate-service/proxy/grpc/utils"
"mime/multipart"
u "isp-gate-service/utils"
"net/http"
"strings"
"time"
)
@@ -25,6 +35,79 @@ const (
errorMsgInvalidArg = "Not able to read request body"
)
var (
json = jsoniter.ConfigFastest
)
func convertError(err error) ([]byte, int) {
s, ok := status.FromError(err)
if ok {
cfg := config.GetRemote().(*conf.RemoteConfig)
if cfg.EnableOriginalProtoErrors {
if body, err := proto.Marshal(s.Proto()); err != nil {
return []byte(utils.ServiceError), http.StatusServiceUnavailable
} else {
return body, http2.CodeToHttpStatus(s.Code())
}
} else {
details := s.Details()
newDetails := make([]interface{}, len(details))
for i, detail := range details {
switch typeOfDetail := detail.(type) {
case *structpb.Struct:
newDetails[i] = utils.ConvertGrpcStructToInterface(
&structpb.Value{Kind: &structpb.Value_StructValue{StructValue: typeOfDetail}},
)
case *isp.Message:
newDetails[i] = utils.ConvertGrpcStructToInterface(
backend.ResolveBody(typeOfDetail),
)
default:
newDetails[i] = typeOfDetail
}
}
var respBody interface{}
if cfg.ProxyGrpcErrorDetails && len(newDetails) > 0 {
respBody = newDetails[0]
} else {
respBody = structure.GrpcError{ErrorMessage: s.Message(), ErrorCode: s.Code().String(), Details: newDetails}
}
if errorData, err := json.Marshal(respBody); err != nil {
log.Warn(log_code.WarnConvertErrorDataMarshalResponse, err)
return []byte(utils.ServiceError), http.StatusServiceUnavailable
} else {
return errorData, http2.CodeToHttpStatus(s.Code())
}
}
} else {
return []byte(utils.ServiceError), http.StatusServiceUnavailable
}
}
func getResponse(msg *isp.Message, err error) ([]byte, int, error) {
if err != nil {
errorBody, errorStatus := convertError(err)
return errorBody, errorStatus, nil
}
bytes := msg.GetBytesBody()
if bytes != nil {
return bytes, http.StatusOK, nil
}
result := backend.ResolveBody(msg)
data := utils.ConvertGrpcStructToInterface(result)
byteResponse, err := json.Marshal(data)
return byteResponse, http.StatusOK, err
}
func logHandlerError(typeData, method string, err error) {
log.WithMetadata(map[string]interface{}{
log_code.MdTypeData: typeData,
log_code.MdMethod: method,
}).Warn(log_code.WarnRequestHandler, err)
}
func openStream(headers *fasthttp.RequestHeader, method string, timeout time.Duration, client *backend.RxGrpcClient) (
isp.BackendService_RequestStreamClient, context.CancelFunc, error) {
@@ -32,7 +115,7 @@ func openStream(headers *fasthttp.RequestHeader, method string, timeout time.Dur
if err != nil {
return nil, nil, err
}
md, _ := utils.MakeMetadata(headers, method)
md, _ := makeMetadata(headers, method)
ctx := metadata.NewOutgoingContext(context.Background(), md)
ctx, cancel := context.WithTimeout(ctx, timeout)
stream, err := cli.RequestStream(ctx)
@@ -42,35 +125,23 @@ func openStream(headers *fasthttp.RequestHeader, method string, timeout time.Dur
return stream, cancel, nil
}
func transferFile(f multipart.File, stream isp.BackendService_RequestStreamClient,
buffer []byte, ctx *fasthttp.RequestCtx) (bool, bool) {
ok := true
eof := false
for {
n, err := f.Read(buffer)
if n > 0 {
err = stream.Send(&isp.Message{Body: &isp.Message_BytesBody{buffer[:n]}})
if ok, eof = checkError(err, ctx); !ok || eof {
break
}
func makeMetadata(r *fasthttp.RequestHeader, method string) (metadata.MD, string) {
method = strings.TrimPrefix(method, "/api/")
md := metadata.Pairs(utils.ProxyMethodNameHeader, method)
r.VisitAll(func(key, v []byte) {
lowerHeader := strings.ToLower(string(key))
if len(v) > 0 && strings.HasPrefix(lowerHeader, "x-") {
md = metadata.Join(md, metadata.Pairs(lowerHeader, string(v)))
}
if err != nil {
if ok, eof = checkError(err, ctx); ok && eof {
err = stream.Send(s.FileEnd())
ok, eof = checkError(err, ctx)
}
break
}
}
return ok, eof
})
return md, method
}
func checkError(err error, ctx *fasthttp.RequestCtx) (bool, bool) {
if err != nil {
if err != io.EOF {
utils.LogRequestHandlerError(log_code.TypeData.GetFile, "", err)
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
logHandlerError(log_code.TypeData.GetFile, "", err)
u.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
return false, false
}
return true, true
@@ -1,34 +1,39 @@
package grpc
package handlers
import (
"github.com/integration-system/isp-lib/backend"
u "github.com/integration-system/isp-lib/utils"
"github.com/valyala/fasthttp"
"isp-gate-service/proxy/grpc/handlers"
"isp-gate-service/proxy/grpc/utils"
"isp-gate-service/utils"
"mime"
)
type Handler interface {
Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient)
}
var Handler handlerHelper
func SetHandler(ctx *fasthttp.RequestCtx) Handler {
isMultipart := isMultipart(ctx)
type (
handlerHelper struct{}
handler interface {
Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient)
}
)
func (h handlerHelper) Get(ctx *fasthttp.RequestCtx) handler {
isMultipart := h.isMultipart(ctx)
isExpectFile := string(ctx.Request.Header.Peek(u.ExpectFileHeader)) == "true"
if isMultipart {
ctx.Response.Header.SetContentType(utils.JsonContentType)
return handlers.SendMultipartData
return sendMultipartData
} else if isExpectFile {
return handlers.GetFile
return getFile
} else {
ctx.Response.Header.SetContentType(utils.JsonContentType)
return handlers.Json
return handleJson
}
}
func isMultipart(ctx *fasthttp.RequestCtx) bool {
func (h handlerHelper) isMultipart(ctx *fasthttp.RequestCtx) bool {
if !ctx.IsPost() {
return false
}
+35 -12
View File
@@ -7,26 +7,27 @@ import (
s "github.com/integration-system/isp-lib/streaming"
u "github.com/integration-system/isp-lib/utils"
log "github.com/integration-system/isp-log"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"io"
"isp-gate-service/conf"
"isp-gate-service/log_code"
"isp-gate-service/proxy/grpc/utils"
"isp-gate-service/utils"
"strconv"
)
var GetFile getFile
var getFile getFileDesc
type getFile struct{}
type getFileDesc struct{}
func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) {
func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) {
cfg := config.GetRemote().(*conf.RemoteConfig)
timeout := cfg.GetStreamInvokeTimeout()
req, err := utils.ReadJsonBody(ctx)
req, err := g.readJsonBody(ctx)
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.GetFile, method, err)
logHandlerError(log_code.TypeData.GetFile, method, err)
utils.SendError(err.Error(), codes.InvalidArgument, nil, ctx)
return
}
@@ -38,7 +39,7 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
}
}()
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.GetFile, method, err)
logHandlerError(log_code.TypeData.GetFile, method, err)
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
return
}
@@ -47,7 +48,7 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
value := u.ConvertInterfaceToGrpcStruct(req)
err := stream.Send(backend.WrapBody(value))
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.GetFile, method, err)
logHandlerError(log_code.TypeData.GetFile, method, err)
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
return
}
@@ -55,7 +56,7 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
msg, err := stream.Recv()
if err != nil {
bytes, status, err := utils.GetResponse(nil, err)
bytes, status, err := getResponse(nil, err)
if err == nil {
ctx.SetStatusCode(status)
ctx.SetBody(bytes)
@@ -65,7 +66,7 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
bf := s.BeginFile{}
err = bf.FromMessage(msg)
if err != nil {
bytes, status, err := utils.GetResponse(nil, err)
bytes, status, err := getResponse(nil, err)
if err == nil {
ctx.SetStatusCode(status)
ctx.SetBody(bytes)
@@ -87,7 +88,7 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
break
}
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.GetFile, method, err)
logHandlerError(log_code.TypeData.GetFile, method, err)
break
}
bytes := msg.GetBytesBody()
@@ -100,8 +101,30 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
}
_, err = ctx.Write(bytes)
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.GetFile, method, err)
logHandlerError(log_code.TypeData.GetFile, method, err)
break
}
}
}
func (getFileDesc) readJsonBody(ctx *fasthttp.RequestCtx) (interface{}, error) {
requestBody := ctx.Request.Body()
var body interface{}
if len(requestBody) == 0 {
requestBody = []byte("{}")
}
if requestBody[0] == '{' {
body = make(map[string]interface{})
} else if requestBody[0] == '[' {
body = make([]interface{}, 0)
} else {
return nil, errors.New("Invalid json format. Expected object or array")
}
err := json.Unmarshal(requestBody, &body)
if err != nil {
return nil, errors.New("Not able to read request body")
}
return body, err
}
+8 -8
View File
@@ -12,16 +12,16 @@ import (
"isp-gate-service/conf"
"isp-gate-service/journal"
"isp-gate-service/log_code"
"isp-gate-service/proxy/grpc/utils"
"isp-gate-service/service"
"isp-gate-service/utils"
"time"
)
var Json handleJson
var handleJson handleJsonDesc
type handleJson struct{}
type handleJsonDesc struct{}
func (p handleJson) Complete(c *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) {
func (p handleJsonDesc) Complete(c *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) {
//body, err := utils.ReadJsonBody(c)
body := c.Request.Body()
/*if err != nil {
@@ -30,7 +30,7 @@ func (p handleJson) Complete(c *fasthttp.RequestCtx, method string, client *back
return
}*/
md, methodName := utils.MakeMetadata(&c.Request.Header, method)
md, methodName := makeMetadata(&c.Request.Header, method)
ctx := metadata.NewOutgoingContext(context.Background(), md)
cfg := config.GetRemote().(*conf.RemoteConfig)
ctx, cancel := context.WithTimeout(ctx, cfg.GetSyncInvokeTimeout())
@@ -38,7 +38,7 @@ func (p handleJson) Complete(c *fasthttp.RequestCtx, method string, client *back
cli, err := client.Conn()
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.JsonContent, methodName, err)
logHandlerError(log_code.TypeData.JsonContent, methodName, err)
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, c)
return
}
@@ -53,7 +53,7 @@ func (p handleJson) Complete(c *fasthttp.RequestCtx, method string, client *back
)
service.Metrics.UpdateRouterResponseTime(time.Since(currentTime) / 1e6)
if data, status, err := utils.GetResponse(response, invokerErr); err == nil {
if data, status, err := getResponse(response, invokerErr); err == nil {
c.SetStatusCode(status)
_, _ = c.Write(data)
if cfg.Journal.Enable && service.JournalMethodsMatcher.Match(methodName) {
@@ -68,7 +68,7 @@ func (p handleJson) Complete(c *fasthttp.RequestCtx, method string, client *back
}
}
} else {
utils.LogRequestHandlerError(log_code.TypeData.JsonContent, methodName, err)
logHandlerError(log_code.TypeData.JsonContent, methodName, err)
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, c)
}
}
@@ -3,20 +3,22 @@ package handlers
import (
"github.com/integration-system/isp-lib/backend"
"github.com/integration-system/isp-lib/config"
isp "github.com/integration-system/isp-lib/proto/stubs"
s "github.com/integration-system/isp-lib/streaming"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"isp-gate-service/conf"
"isp-gate-service/log_code"
"isp-gate-service/proxy/grpc/utils"
"isp-gate-service/utils"
"mime/multipart"
"strings"
)
var SendMultipartData sendMultipartData
var sendMultipartData sendMultipartDataDesc
type sendMultipartData struct{}
type sendMultipartDataDesc struct{}
func (sendMultipartData) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) {
func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) {
cfg := config.GetRemote().(*conf.RemoteConfig)
timeout := cfg.GetStreamInvokeTimeout()
bufferSize := cfg.GetTransferFileBufferSize()
@@ -28,7 +30,7 @@ func (sendMultipartData) Complete(ctx *fasthttp.RequestCtx, method string, clien
}
}()
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.SendMultipart, method, err)
logHandlerError(log_code.TypeData.SendMultipart, method, err)
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
return
}
@@ -41,7 +43,7 @@ func (sendMultipartData) Complete(ctx *fasthttp.RequestCtx, method string, clien
}()
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.SendMultipart, method, err)
logHandlerError(log_code.TypeData.SendMultipart, method, err)
utils.SendError(errorMsgInvalidArg, codes.InvalidArgument, []interface{}{err.Error()}, ctx)
return
}
@@ -83,9 +85,9 @@ func (sendMultipartData) Complete(ctx *fasthttp.RequestCtx, method string, clien
if ok, eof = checkError(err, ctx); !ok || eof {
break
}
if ok, eof = transferFile(f, stream, buffer, ctx); ok {
if ok, eof = h.transferFile(f, stream, buffer, ctx); ok {
msg, err := stream.Recv()
v, _, err := utils.GetResponse(msg, err)
v, _, err := getResponse(msg, err)
if err == nil {
response = append(response, string(v))
}
@@ -99,14 +101,38 @@ func (sendMultipartData) Complete(ctx *fasthttp.RequestCtx, method string, clien
err = stream.CloseSend()
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.SendMultipart, method, err)
logHandlerError(log_code.TypeData.SendMultipart, method, err)
}
if ok {
arrayBody := strings.Join(response, ",")
_, err = ctx.WriteString("[" + arrayBody + "]")
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.SendMultipart, method, err)
logHandlerError(log_code.TypeData.SendMultipart, method, err)
}
}
}
func (sendMultipartDataDesc) transferFile(f multipart.File, stream isp.BackendService_RequestStreamClient,
buffer []byte, ctx *fasthttp.RequestCtx) (bool, bool) {
ok := true
eof := false
for {
n, err := f.Read(buffer)
if n > 0 {
err = stream.Send(&isp.Message{Body: &isp.Message_BytesBody{buffer[:n]}})
if ok, eof = checkError(err, ctx); !ok || eof {
break
}
}
if err != nil {
if ok, eof = checkError(err, ctx); ok && eof {
err = stream.Send(s.FileEnd())
ok, eof = checkError(err, ctx)
}
break
}
}
return ok, eof
}
-149
View File
@@ -1,149 +0,0 @@
package utils
import (
"github.com/golang/protobuf/proto"
"github.com/integration-system/isp-lib/config"
"github.com/integration-system/isp-lib/structure"
log "github.com/integration-system/isp-log"
"google.golang.org/grpc/codes"
"isp-gate-service/conf"
"isp-gate-service/log_code"
"net/http"
"strings"
"github.com/golang/protobuf/ptypes/struct"
"github.com/integration-system/isp-lib/backend"
http2 "github.com/integration-system/isp-lib/http"
"github.com/integration-system/isp-lib/proto/stubs"
"github.com/integration-system/isp-lib/utils"
"github.com/json-iterator/go"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
const (
JsonContentType = "application/json; charset=utf-8"
)
var (
json = jsoniter.ConfigFastest
)
func ReadJsonBody(ctx *fasthttp.RequestCtx) (interface{}, error) {
requestBody := ctx.Request.Body()
var body interface{}
if len(requestBody) == 0 {
requestBody = []byte("{}")
}
if requestBody[0] == '{' {
body = make(map[string]interface{})
} else if requestBody[0] == '[' {
body = make([]interface{}, 0)
} else {
return nil, errors.New("Invalid json format. Expected object or array")
}
err := json.Unmarshal(requestBody, &body)
if err != nil {
return nil, errors.New("Not able to read request body")
}
return body, err
}
func GetResponse(msg *isp.Message, err error) ([]byte, int, error) {
if err != nil {
errorBody, errorStatus := convertError(err)
return errorBody, errorStatus, nil
}
bytes := msg.GetBytesBody()
if bytes != nil {
return bytes, http.StatusOK, nil
}
result := backend.ResolveBody(msg)
data := utils.ConvertGrpcStructToInterface(result)
byteResponse, err := json.Marshal(data)
return byteResponse, http.StatusOK, err
}
func MakeMetadata(r *fasthttp.RequestHeader, method string) (metadata.MD, string) {
method = strings.TrimPrefix(method, "/api/")
md := metadata.Pairs(utils.ProxyMethodNameHeader, method)
r.VisitAll(func(key, v []byte) {
lowerHeader := strings.ToLower(string(key))
if len(v) > 0 && strings.HasPrefix(lowerHeader, "x-") {
md = metadata.Join(md, metadata.Pairs(lowerHeader, string(v)))
}
})
return md, method
}
func LogRequestHandlerError(typeData, method string, err error) {
log.WithMetadata(map[string]interface{}{
log_code.MdTypeData: typeData,
log_code.MdMethod: method,
}).Warn(log_code.WarnRequestHandler, err)
}
func SendError(errorMessage string, errorCode codes.Code, details []interface{}, ctx *fasthttp.RequestCtx) {
grpcCode := errorCode.String()
structureError := structure.GrpcError{
ErrorMessage: errorMessage,
ErrorCode: grpcCode,
Details: details,
}
ctx.SetStatusCode(http2.CodeToHttpStatus(errorCode))
msg, _ := json.Marshal(structureError)
_, _ = ctx.Write(msg)
}
func convertError(err error) ([]byte, int) {
s, ok := status.FromError(err)
if ok {
cfg := config.GetRemote().(*conf.RemoteConfig)
if cfg.EnableOriginalProtoErrors {
if body, err := proto.Marshal(s.Proto()); err != nil {
return []byte(utils.ServiceError), http.StatusServiceUnavailable
} else {
return body, http2.CodeToHttpStatus(s.Code())
}
} else {
details := s.Details()
newDetails := make([]interface{}, len(details))
for i, detail := range details {
switch typeOfDetail := detail.(type) {
case *structpb.Struct:
newDetails[i] = utils.ConvertGrpcStructToInterface(
&structpb.Value{Kind: &structpb.Value_StructValue{StructValue: typeOfDetail}},
)
case *isp.Message:
newDetails[i] = utils.ConvertGrpcStructToInterface(
backend.ResolveBody(typeOfDetail),
)
default:
newDetails[i] = typeOfDetail
}
}
var respBody interface{}
if cfg.ProxyGrpcErrorDetails && len(newDetails) > 0 {
respBody = newDetails[0]
} else {
respBody = structure.GrpcError{ErrorMessage: s.Message(), ErrorCode: s.Code().String(), Details: newDetails}
}
if errorData, err := json.Marshal(respBody); err != nil {
log.Warn(log_code.WarnConvertErrorDataMarshalResponse, err)
return []byte(utils.ServiceError), http.StatusServiceUnavailable
} else {
return errorData, http2.CodeToHttpStatus(s.Code())
}
}
} else {
return []byte(utils.ServiceError), http.StatusServiceUnavailable
}
}
+5 -1
View File
@@ -4,7 +4,9 @@ import (
"github.com/integration-system/isp-lib/structure"
log "github.com/integration-system/isp-log"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"isp-gate-service/log_code"
"isp-gate-service/utils"
"net"
"strings"
)
@@ -31,7 +33,9 @@ func (p *httpProxy) Consumer(addressList []structure.AddressConfiguration) bool
func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) {
if p.client == nil {
log.Error(log_code.ErrorClientHttp, "client undefined")
msg := "client undefined"
log.Error(log_code.ErrorClientHttp, msg)
utils.SendError(msg, codes.Internal, nil, ctx)
return
}
+14 -82
View File
@@ -1,16 +1,20 @@
package redis
import (
"fmt"
"github.com/go-redis/redis"
"github.com/integration-system/isp-lib/config"
rd "github.com/integration-system/isp-lib/redis"
"github.com/integration-system/isp-lib/structure"
"github.com/pkg/errors"
"isp-gate-service/conf"
log "github.com/integration-system/isp-log"
"isp-gate-service/log_code"
)
var Client = &redisClient{cli: rd.NewRxClient()}
var Client = &redisClient{
cli: rd.NewRxClient(
rd.WithInitHandler(func(c *rd.Client, err error) {
if err != nil {
log.Fatal(log_code.ErrorClientRedis, err)
}
})),
}
type redisClient struct {
cli *rd.RxClient
@@ -20,82 +24,10 @@ func (c *redisClient) ReceiveConfiguration(configuration structure.RedisConfigur
c.cli.ReceiveConfiguration(configuration)
}
func (c *redisClient) GetTokens(appToken string) (map[string]string, error) {
if c.cli == nil {
return nil, errors.New("client undefined")
}
instanceUuid := config.Get().(*conf.Configuration).InstanceUuid
key := fmt.Sprintf("%s|%s", appToken, instanceUuid)
if resp, err := c.cli.Pipelined(func(p redis.Pipeliner) error {
if cmd := p.Select(int(rd.ApplicationTokenDb)); cmd.Err() != nil {
return cmd.Err()
}
p.HGetAll(key)
return nil
}); err != nil {
return nil, err
} else {
if len(resp) < 2 || resp[1].Err() == redis.Nil {
return nil, nil
} else if resp[1].Err() != nil {
return nil, err
} else if stringStringMapCmd, ok := resp[1].(*redis.StringStringMapCmd); !ok {
return nil, nil
} else {
return stringStringMapCmd.Val(), nil
}
}
func (c *redisClient) Get() *rd.RxClient {
return c.cli
}
func (c *redisClient) CheckTokens(t map[string]string) (map[string]string, error) {
secondDbKey := fmt.Sprintf("%s|%s", t[ApplicationIdentity], t[Uri])
thirdDbKey := fmt.Sprintf("%s|%s", t[UserToken], t[DomainIdentity])
fifthDbKey := fmt.Sprintf("%s|%s", t[DeviceToken], t[DomainIdentity])
if resp, err := c.cli.Pipelined(func(p redis.Pipeliner) error {
if cmd := p.Select(int(rd.ApplicationPermissionDb)); cmd.Err() != nil && cmd.Err() != redis.Nil {
return cmd.Err()
}
p.Get(secondDbKey)
if cmd := p.Select(int(rd.UserTokenDb)); cmd.Err() != nil && cmd.Err() != redis.Nil {
return cmd.Err()
}
p.Get(thirdDbKey)
if cmd := p.Select(int(rd.DeviceTokenDb)); cmd.Err() != nil && cmd.Err() != redis.Nil {
return cmd.Err()
}
p.Get(fifthDbKey)
return nil
}); err != nil && err != redis.Nil {
return t, err
} else {
// It is not permitted to call this methodParts
if fineCmd(resp, 1) {
if intCmd, ok := resp[1].(*redis.IntCmd); ok && intCmd.Val() == 0 {
return t, errors.New("invalid token")
}
}
// ===== CHECK USER TOKEN =====
if fineCmd(resp, 3) {
if stringCmd, ok := resp[3].(*redis.StringCmd); ok {
t[UserIdentity] = stringCmd.Val()
}
}
// ===== CHECK DEVICE TOKEN =====
if fineCmd(resp, 5) {
if stringCmd, ok := resp[5].(*redis.StringCmd); ok {
t[DeviceIdentity] = stringCmd.Val()
}
}
}
return t, nil
}
func fineCmd(cmders []redis.Cmder, arrayKey int) bool {
return len(cmders) > arrayKey+1 && cmders[arrayKey] != nil &&
(cmders[arrayKey].Err() == nil || cmders[arrayKey].Err() == redis.Nil)
func (c *redisClient) Close() {
_ = c.cli.Close()
}
-15
View File
@@ -1,15 +0,0 @@
package redis
const (
SystemIdentity = "1"
DomainIdentity = "2"
ServiceIdentity = "3"
ApplicationIdentity = "4"
DeviceIdentity = "5"
UserIdentity = "6"
DeviceToken = "7"
UserToken = "8"
Uri = "9"
)
+10 -2
View File
@@ -22,7 +22,7 @@ func (s *httpSrv) Init(MaxRequestBodySize int64) {
s.mx.Lock()
if s.srv != nil {
if err := s.srv.Shutdown(); err != nil {
log.Warn(log_code.WarnCreateRestServerHttpSrvShutdown, err)
log.Warn(log_code.WarnHttpServerShutdown, err)
}
}
maxRequestBodySize := MaxRequestBodySize
@@ -36,8 +36,16 @@ func (s *httpSrv) Init(MaxRequestBodySize int64) {
}
go func() {
if err := s.srv.ListenAndServe(restAddress); err != nil {
log.Error(log_code.ErrorCreateRestServerHttpSrvListenAndServe, err)
log.Error(log_code.ErrorHttpServerListen, err)
}
}()
s.mx.Unlock()
}
func (s *httpSrv) Close() {
if s.srv != nil {
if err := s.srv.Shutdown(); err != nil {
log.Warn(log_code.WarnHttpServerShutdown, err)
}
}
}
+28
View File
@@ -0,0 +1,28 @@
package utils
import (
"encoding/json"
"github.com/integration-system/isp-lib/http"
"github.com/integration-system/isp-lib/structure"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
)
const (
JsonContentType = "application/json; charset=utf-8"
)
func SendError(errorMessage string, errorCode codes.Code, details []interface{}, ctx *fasthttp.RequestCtx) {
grpcCode := errorCode.String()
structureError := structure.GrpcError{
ErrorMessage: errorMessage,
ErrorCode: grpcCode,
Details: details,
}
ctx.SetContentType(JsonContentType)
ctx.SetStatusCode(http.CodeToHttpStatus(errorCode))
msg, _ := json.Marshal(structureError)
_, _ = ctx.Write(msg)
}