diff --git a/.version b/.version index 4e379d2..bcab45a 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -0.0.2 +0.0.3 diff --git a/Gopkg.lock b/Gopkg.lock index 5e982f8..ddd7699 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -1,14 +1,6 @@ # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. -[[projects]] - digest = "1:e92f5581902c345eb4ceffdcd4a854fb8f73cf436d47d837d1ec98ef1fe0a214" - name = "github.com/StackExchange/wmi" - packages = ["."] - pruneopts = "UT" - revision = "5d049714c4a64225c3c79a7cf7d02f7fb5b96338" - version = "1.0.0" - [[projects]] digest = "1:320e7ead93de9fd2b0e59b50fd92a4d50c1f8ab455d96bc2eb083267453a9709" name = "github.com/asaskevich/govalidator" @@ -34,15 +26,20 @@ version = "v1.4.7" [[projects]] - digest = "1:440028f55cb322d8cb5b9d5ebec298a00b7d74690a658fe6b1c0c0b44341bfae" - name = "github.com/go-ole/go-ole" + digest = "1:b46f50677ef33284ebde2b285a42b707ff9e1de1f37328d91869859c929ebbd2" + name = "github.com/go-redis/redis" packages = [ ".", - "oleutil", + "internal", + "internal/consistenthash", + "internal/hashtag", + "internal/pool", + "internal/proto", + "internal/util", ] pruneopts = "UT" - revision = "97b6244175ae18ea6eef668034fd6565847501c9" - version = "v1.2.4" + revision = "7f69d5e32072d151eb6936cbe2306413e8117488" + version = "v6.15.6" [[projects]] digest = "1:07f4fafe81587b642166199f41c3edcca12929fcfcc0261b00be5dea2f968f44" @@ -150,7 +147,8 @@ version = "v1.3.0" [[projects]] - digest = "1:07a84c67d3c719dec447bf309303edda3b208234fee91fff5c38f466ee6665d1" + branch = "master" + digest = "1:5d6745d93914f036ecf9c22e20ec2a6885864acad54bec463e59cfde770dd7ee" name = "github.com/integration-system/isp-lib" packages = [ "backend", @@ -161,19 +159,22 @@ "logger", "metric", "proto/stubs", + "redis", "streaming", "structure", "utils", ] pruneopts = "UT" - revision = "b110f4b47bc34145bda99c67560a780013d12f55" - version = "v1.6.3" + revision = "f72fc522399b23b49e43d8bcc279a54654ea2419" [[projects]] branch = "master" - digest = "1:ba98dc95f3f2eb551d124f9ed6a6a405ea95a6b2ab70450b988306e885caa4fe" + digest = "1:1789fb6e57949a6e4cacb74023cd30efb04b09dc6111d6ef3718241ebb23ebe9" name = "github.com/integration-system/isp-log" - packages = ["."] + packages = [ + ".", + "stdcodes", + ] pruneopts = "UT" revision = "a22bf2e0b56a9ef47db4a98756e39f700a99b688" @@ -312,17 +313,6 @@ pruneopts = "UT" revision = "cac0b30c2563378d434b5af411844adff8e32960" -[[projects]] - digest = "1:ab1672baf07ee80c988e369e5633bcac459342e8e00d0c38a799056395fe9dba" - name = "github.com/shirou/gopsutil" - packages = [ - "cpu", - "internal/common", - ] - pruneopts = "UT" - revision = "1c09419d4b1c4c19e06d9f48b9406bda27d32acd" - version = "v2.19.9" - [[projects]] digest = "1:04457f9f6f3ffc5fea48e71d62f2ca256637dee0a04d710288e27e05c8b41976" name = "github.com/sirupsen/logrus" @@ -392,7 +382,7 @@ [[projects]] branch = "master" - digest = "1:5788c649931a43dc8a21b07a4b51028238b1c2715baadef36c104572ba642be0" + digest = "1:e743d2809ba5299bfe842a8a724172f9ac4e89ee281b46720ac65a688ac398a1" name = "github.com/valyala/fasthttp" packages = [ ".", @@ -400,7 +390,7 @@ "stackless", ] pruneopts = "UT" - revision = "c3d82ca3a430260ff1795abfeac9e8396ed6f6fe" + revision = "18c619fb0432fa6b21cb134d35118e6b09d9d9ce" [[projects]] digest = "1:39a425f98fb19427061a693fe6bf0683c9bddec4b25b17067e34fdb465e39cb9" @@ -432,18 +422,18 @@ "trace", ] pruneopts = "UT" - revision = "da9a3fd4c5820e74b24a6cb7fb438dc9b0dd377c" + revision = "ec77196f6094c3492a8b61f2c11cf937f78992ae" [[projects]] branch = "master" - digest = "1:44480e76e73bb8d3104753f3618943ff331f2225c867c69af330e3e7f89b2e35" + digest = "1:3fa58f7377e1d95d496db43dd3281ddcea4185eb46c6394f89fec1cfa4ec3244" name = "golang.org/x/sys" packages = [ "unix", "windows", ] pruneopts = "UT" - revision = "727590c5006e77ca5247972f47e877f4929fc985" + revision = "742c48ecaeb7c624c475e02f3eb0827ebb4970d4" [[projects]] digest = "1:8d8faad6b12a3a4c819a3f9618cb6ee1fa1cfc33253abeeea8b55336721e3405" @@ -535,7 +525,7 @@ analyzer-name = "dep" analyzer-version = 1 input-imports = [ - "github.com/buaazp/fasthttprouter", + "github.com/go-redis/redis", "github.com/golang/protobuf/proto", "github.com/golang/protobuf/ptypes/struct", "github.com/integration-system/isp-journal/rx", @@ -546,6 +536,7 @@ "github.com/integration-system/isp-lib/http", "github.com/integration-system/isp-lib/metric", "github.com/integration-system/isp-lib/proto/stubs", + "github.com/integration-system/isp-lib/redis", "github.com/integration-system/isp-lib/streaming", "github.com/integration-system/isp-lib/structure", "github.com/integration-system/isp-lib/utils", @@ -555,7 +546,6 @@ "github.com/rcrowley/go-metrics", "github.com/valyala/fasthttp", "golang.org/x/net/context", - "google.golang.org/genproto/googleapis/rpc/errdetails", "google.golang.org/grpc", "google.golang.org/grpc/codes", "google.golang.org/grpc/metadata", diff --git a/Gopkg.toml b/Gopkg.toml index 3734909..655c622 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -32,6 +32,10 @@ name = "github.com/valyala/fasthttp" branch = "master" +[[override]] + name = "github.com/integration-system/isp-lib" + branch = "master" + [prune] go-tests = true unused-packages = true diff --git a/authenticate/authenticate.go b/authenticate/authenticate.go new file mode 100644 index 0000000..0a07a88 --- /dev/null +++ b/authenticate/authenticate.go @@ -0,0 +1,53 @@ +package authenticate + +import ( + "github.com/integration-system/isp-lib/utils" + "github.com/pkg/errors" + "github.com/valyala/fasthttp" + "isp-gate-service/redis" + "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{ + utils.SystemIdHeader, utils.DomainIdHeader, utils.ServiceIdHeader, utils.ApplicationIdHeader, + } { + ctx.Request.Header.Del(notExpectedHeader) + } + + appToken := ctx.Request.Header.Peek(utils.ApplicationTokenHeader) + if len(appToken) == 0 { + return errors.Errorf("%s not found", utils.ApplicationTokenHeader) + } + 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) + if err != nil { + return err + } + delete(tokens, redis.Uri) + for key, value := range tokens { + if value != "" { + ctx.Request.Header.Set(redisKeyHeaderKeyMap[key], value) + } + } + return nil +} diff --git a/conf/default_remote_config.json b/conf/default_remote_config.json index 559493e..f159051 100644 --- a/conf/default_remote_config.json +++ b/conf/default_remote_config.json @@ -18,5 +18,13 @@ "maxSizeMb": 512, "bufferSize": 4096, "rotateTimeoutMs": 86400000 + }, + "redis": { + "password": "password", + "defaultDB": 0, + "address": { + "ip": "127.0.0.1", + "port": "6379" + } } } diff --git a/conf/remote_config.go b/conf/remote_config.go index 7aba941..72aa513 100644 --- a/conf/remote_config.go +++ b/conf/remote_config.go @@ -28,6 +28,7 @@ type RemoteConfig struct { Metrics structure.MetricConfiguration `schema:"Настройка метрик"` Journal rx.Config `schema:"Настройка логирования"` JournalingMethodsPatterns []string `schema:"Список методов для логирования,список строк вида: 'module/group/method'(* - для частичного совпадения). При обработке запроса, если вызываемый метод совпадает со строкой из списка, тела запроса и ответа записываются в лог"` + Redis structure.RedisConfiguration `schema:"Настрока Redis" valid:"required~Required"` } func (cfg RemoteConfig) GetSyncInvokeTimeout() time.Duration { diff --git a/handler/handler.go b/handler/handler.go index 218e9dc..1faa734 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -6,12 +6,26 @@ import ( "github.com/integration-system/isp-lib/structure" "github.com/valyala/fasthttp" "google.golang.org/grpc/codes" + "isp-gate-service/authenticate" "isp-gate-service/proxy" ) 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}, + } + ctx.Response.Header.SetContentType("application/json; charset=utf-8") + ctx.SetStatusCode(http.CodeToHttpStatus(statusCode)) + message, _ := json.Marshal(response) + _, _ = ctx.Write(message) + return + } + p := proxy.Find(path) if p != nil { p.ProxyRequest(ctx) diff --git a/main.go b/main.go index 0f6146a..5ac16bc 100644 --- a/main.go +++ b/main.go @@ -12,6 +12,7 @@ import ( "isp-gate-service/journal" "isp-gate-service/log_code" "isp-gate-service/proxy" + "isp-gate-service/redis" "isp-gate-service/server" "isp-gate-service/service" "os" @@ -54,10 +55,11 @@ 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.MaxRequestBodySizeBytes) service.JournalMethodsMatcher = service.NewCacheableMethodMatcher(remoteConfig.JournalingMethodsPatterns) - server.Http.Init(remoteConfig.MaxRequestBodySizeBytes) metric.InitCollectors(remoteConfig.Metrics, oldRemoteConfig.Metrics) metric.InitHttpServer(remoteConfig.Metrics) //metric.InitStatusChecker("router-grpc", helper.GetRoutersAndStatus) diff --git a/proxy/http/client.go b/proxy/http/client.go index 31c406c..dd152b1 100644 --- a/proxy/http/client.go +++ b/proxy/http/client.go @@ -33,58 +33,16 @@ func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) { req := &ctx.Request res := &ctx.Response - if clientIP, _, err := net.SplitHostPort(ctx.RemoteAddr().String()); err == nil { - req.Header.Add("X-Forwarded-For", clientIP) - } - - resHeaders := make(map[string]string) - res.Header.VisitAll(func(k, v []byte) { - key := string(k) - value := string(v) - if val, ok := resHeaders[key]; ok { - resHeaders[key] = val + "," + value - } - resHeaders[key] = value - }) - - for _, h := range hopHeaders { - // if h == "Te" && hv == "trailers" { - // continue - // } - req.Header.Del(h) + if addr, _, err := net.SplitHostPort(ctx.RemoteAddr().String()); err == nil { + req.Header.Add("X-Forwarded-For", addr) } if err := p.client.Do(req, res); err != nil { log.Error(log_code.ErrorClientHttp, err) return } - - for _, h := range hopHeaders { - res.Header.Del(h) - } - for k, v := range resHeaders { - res.Header.Set(k, v) - } } func (p *httpProxy) Close() { p.client = nil - p = nil -} - -// Hop-by-hop headers. These are removed when sent to the backend. -// As of RFC 7230, hop-by-hop headers are required to appear in the -// Connection header field. These are the headers defined by the -// obsoleted RFC 2616 (section 13.5.1) and are used for backward -// compatibility. -var hopHeaders = []string{ - "Connection", - "Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google - "Keep-Alive", - "Proxy-Authenticate", - "Proxy-Authorization", - "Te", // canonicalized version of "TE" - "Trailer", // not Trailers per URL above; https://www.rfc-editor.org/errata_search.php?eid=4522 - "Transfer-Encoding", - "Upgrade", } diff --git a/redis/client.go b/redis/client.go new file mode 100644 index 0000000..fe1e09c --- /dev/null +++ b/redis/client.go @@ -0,0 +1,97 @@ +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" +) + +var Client = &redisClient{cli: rd.NewRxClient()} + +type redisClient struct { + cli *rd.RxClient +} + +func (c *redisClient) ReceiveConfiguration(configuration structure.RedisConfiguration) { + c.cli.ReceiveConfiguration(configuration) +} + +func (c *redisClient) GetTokens(appToken string) (map[string]string, error) { + 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) 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) +} diff --git a/redis/domain.go b/redis/domain.go new file mode 100644 index 0000000..b56a9ab --- /dev/null +++ b/redis/domain.go @@ -0,0 +1,15 @@ +package redis + +const ( + SystemIdentity = "1" + DomainIdentity = "2" + ServiceIdentity = "3" + ApplicationIdentity = "4" + + DeviceIdentity = "5" + UserIdentity = "6" + + DeviceToken = "7" + UserToken = "8" + Uri = "9" +)