From 2b91caece0557cc605575641bbdda4287c8ebb1b Mon Sep 17 00:00:00 2001 From: txix Date: Mon, 22 Jan 2024 17:22:41 +0300 Subject: [PATCH] 2024-01-22 17:22:41: merge [master:56d3e06e49d7a75f142424293788a4f3b6245430]; --- .gitignore | 76 ++++++ .gitlab-ci.yml | 30 +++ .golangci.yml | 55 ++++ .version | 1 + CHANGELOG.md | 106 ++++++++ Dockerfile.dit | 18 ++ assembly/assembly.go | 183 +++++++++++++ assembly/locator.go | 127 +++++++++ cache/cache.go | 53 ++++ cache/cache_test.go | 47 ++++ conf/config.yml | 24 ++ conf/config_kkd.yml | 30 +++ conf/default_remote_config.json | 16 ++ conf/local.go | 19 ++ conf/remote.go | 77 ++++++ conf/remote_test.go | 13 + domain/admin.go | 7 + domain/auth.go | 8 + domain/cache.go | 9 + domain/system.go | 29 +++ domain/throttling.go | 11 + go.mod | 77 ++++++ go.sum | 239 +++++++++++++++++ httperrors/errors.go | 41 +++ main.go | 37 +++ middleware/admin_authenticate.go | 48 ++++ middleware/admin_authorize.go | 60 +++++ middleware/authenticate.go | 49 ++++ middleware/authorize.go | 49 ++++ middleware/daily_limit.go | 39 +++ middleware/entrypoint.go | 34 +++ middleware/error_handler.go | 35 +++ middleware/logger.go | 121 +++++++++ middleware/middleware.go | 24 ++ middleware/request_id.go | 31 +++ middleware/throttling.go | 41 +++ proxy/const.go | 5 + proxy/grpc.go | 160 ++++++++++++ proxy/http.go | 115 ++++++++ proxy/ws.go | 71 +++++ repository/admin.go | 47 ++++ repository/authentication_cache.go | 49 ++++ repository/authorization_cache.go | 37 +++ repository/daily_limit.go | 42 +++ repository/system.go | 48 ++++ repository/throttling.go | 37 +++ repository/unused/redis_auth_cache.go | 75 ++++++ repository/unused/redis_authz_cache.go | 66 +++++ request/context.go | 119 +++++++++ routes/routes.go | 49 ++++ service/admin.go | 57 ++++ service/authentication.go | 55 ++++ service/authorization.go | 51 ++++ service/daily_limit.go | 43 +++ service/throttling.go | 47 ++++ tests/acceptance_test.go | 348 +++++++++++++++++++++++++ tests/bench/bench.go | 143 ++++++++++ tests/bench/body.json | 3 + tests/bench/run.sh | 2 + tests/redis.go | 25 ++ 60 files changed, 3558 insertions(+) create mode 100644 .gitignore create mode 100644 .gitlab-ci.yml create mode 100644 .golangci.yml create mode 100644 .version create mode 100644 CHANGELOG.md create mode 100644 Dockerfile.dit create mode 100644 assembly/assembly.go create mode 100644 assembly/locator.go create mode 100644 cache/cache.go create mode 100644 cache/cache_test.go create mode 100644 conf/config.yml create mode 100644 conf/config_kkd.yml create mode 100644 conf/default_remote_config.json create mode 100644 conf/local.go create mode 100644 conf/remote.go create mode 100644 conf/remote_test.go create mode 100644 domain/admin.go create mode 100644 domain/auth.go create mode 100644 domain/cache.go create mode 100644 domain/system.go create mode 100644 domain/throttling.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 httperrors/errors.go create mode 100644 main.go create mode 100644 middleware/admin_authenticate.go create mode 100644 middleware/admin_authorize.go create mode 100644 middleware/authenticate.go create mode 100644 middleware/authorize.go create mode 100644 middleware/daily_limit.go create mode 100644 middleware/entrypoint.go create mode 100644 middleware/error_handler.go create mode 100644 middleware/logger.go create mode 100644 middleware/middleware.go create mode 100644 middleware/request_id.go create mode 100644 middleware/throttling.go create mode 100644 proxy/const.go create mode 100644 proxy/grpc.go create mode 100644 proxy/http.go create mode 100644 proxy/ws.go create mode 100644 repository/admin.go create mode 100644 repository/authentication_cache.go create mode 100644 repository/authorization_cache.go create mode 100644 repository/daily_limit.go create mode 100644 repository/system.go create mode 100644 repository/throttling.go create mode 100644 repository/unused/redis_auth_cache.go create mode 100644 repository/unused/redis_authz_cache.go create mode 100644 request/context.go create mode 100644 routes/routes.go create mode 100644 service/admin.go create mode 100644 service/authentication.go create mode 100644 service/authorization.go create mode 100644 service/daily_limit.go create mode 100644 service/throttling.go create mode 100644 tests/acceptance_test.go create mode 100644 tests/bench/bench.go create mode 100644 tests/bench/body.json create mode 100644 tests/bench/run.sh create mode 100644 tests/redis.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..73fbb5a --- /dev/null +++ b/.gitignore @@ -0,0 +1,76 @@ +# Created by .ignore support plugin (hsz.mobi) +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +/.idea/ +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/dictionaries +*.iml +convert_service +convert-service + +# Sensitive or high-churn files: +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml + +# Gradle: +.idea/**/gradle.xml +.idea/**/libraries + +# CMake +cmake-build-debug/ +cmake-build-release/ + +# Mongo Explorer plugin: +.idea/**/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties +### Go template +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +/node_modules/ +/vendor/ +google/ +package.json +yarn.lock + +conf/config_dev.yml diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..35a7790 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,30 @@ +docker-build: + image: docker:latest + stage: build + services: + - docker:dind + before_script: + - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY + script: + - set + - docker build -f Dockerfile.dit --force-rm --build-arg="version=$CI_COMMIT_SHORT_SHA" --build-arg="app_name=$CI_PROJECT_NAME" --pull -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" . + - | + if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then + tag="" + echo "Running on default branch '$CI_DEFAULT_BRANCH': tag = ':latest'" + #docker pull "$CI_REGISTRY_IMAGE${tag}" + #docker tag "$CI_REGISTRY_IMAGE${tag}" "$CI_REGISTRY_IMAGE:pre" + #docker rmi "$CI_REGISTRY_IMAGE${tag}" + #docker push "$CI_REGISTRY_IMAGE:pre" + #docker rmi -f "$CI_REGISTRY_IMAGE:pre" + docker tag "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" "$CI_REGISTRY_IMAGE${tag}" + docker rmi "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" + docker push "$CI_REGISTRY_IMAGE${tag}" + docker rmi -f "$CI_REGISTRY_IMAGE${tag}" + else + tag=":$CI_COMMIT_BRANCH" + echo "Running on branch '$CI_COMMIT_BRANCH': tag = $tag" + fi + after_script: + - docker logout $CI_REGISTRY + diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..3a4cf10 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,55 @@ +run: + timeout: 2m + +linters: + disable-all: true + enable: + - asciicheck + - bodyclose + - deadcode + - dogsled + - errcheck + - funlen + - goconst + - gocritic + - gocyclo + - gofmt + - gomnd + - goprintffuncname + - gosimple + - govet + - nakedret + - nestif + - prealloc + - rowserrcheck + - staticcheck + - structcheck + - typecheck + - unconvert + - unparam + - unused + - varcheck + - gosec + - misspell + - whitespace + - exhaustive #смотрит на соответствие между элементами enum и swich кейсами + - exportloopref #for _,p := []int{1, 2, 3} { s.Bar(&p) /* If s stores the pointer, it will be bug.*/ } + - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. +linters-settings: + funlen: + lines: 80 + lll: + line-length: 150 + cyclop: + max-complexity: 15 #по умолчанию 10 мало + revive: + rules: + - name: var-naming #отключаем Id -> ID + disabled: true + stylecheck: + checks: #отключаем Id -> ID + - "-ST1000" + - "-ST1016" + - "-ST1020" + - "-ST1021" + - "-ST1022" diff --git a/.version b/.version new file mode 100644 index 0000000..ac14c3d --- /dev/null +++ b/.version @@ -0,0 +1 @@ +5.1.1 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..fd4a266 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,106 @@ +### v5.1.1 +* добавлен параметр `withPrefix` в локальном конфиге для `location`, чтобы не обрезать путь при проксировании запроса +### v5.1.0 +* обновлены зависимости (увеличены лимиты по семплированию логов, добавлена возможность конфигурировать семплирование) +### v5.0.0 +* добавлена авторизация ендпоинтов администратора +### v4.3.0 +* обновлены зависимости +### v4.2.1 +* исправлено поведение `skipBodyLoggingEndpointPrefixes` +### v4.2.0 +* новый параметр в remote_config: `skipBodyLoggingEndpointPrefixes`. Массив re. Если они есть в пути, то запрос не будет логироваться +### v4.1.2 +* исправлена опция логирования тела запроса (при настройке ws могла отключаться) +### v4.1.1 +* исправлена маршрутизация запросов +### v4.1.0 +* обновлены зависимости +* добавлена поддержка проксирования WebSocket `ws` +### v4.0.0 +* реализована аутентификация токена администратора через msp-admin-service +### v3.0.3 +* исправлено тело ответа grpc ошибок валидации +* обновлены зависимости +### v3.0.2 +* добавлен charset=utf-8 в заголовок ответа для grpc +### v3.0.1 +* исправлено проксирование http с GET параметрами +* исправлено логирование пути при проксировании HTTP +### v3.0.0 +* реализация новой схемы аутентификации/авторизации +### v2.8.3 +* use isp-kit logger instead local logger +* use log string instead log any (common log type) +* add replace grpc (isp-lib and isp-kit conflict) +### v2.8.2 +* add file rotation +### v2.8.1 +* add xml format support for new logger +### v2.8.0 +* add new logger +* remove journal +* add identities to requests log +### v2.7.6 +* updated dependencies +* migrated to common local config +### v2.7.5 +* updated dependencies +### v2.7.4 +* updated isp-lib +* updated isp-lib-test +### v2.7.3 +* updated isp-lib +* updated isp-event-lib +## 2.7.2 +* fix accounting +## 2.7.1 +* fix default local config +## 2.7.0 +* add support Redis Sentinel +* update grpc client +* code cleanup +## 2.6.3 +* fix search from locations +* fix proxying URI in http and ws +## 2.6.2 +* fix panic if journal enable and error logging +* add content-type, content-length header to response +* close journal +* journal module is not more required +* add missing journaling +## 2.6.0 +* migrate to go mod +## 2.5.4 +* fix auth cache +## 2.5.3 +* fix grpc multipart error response +## 2.5.2 +* fix init http +## 2.5.1 +* fix code response when doesn't match user id +* fix config reload +## 2.5.0 +* add skip for check exist method +* add handler for user methods +* fix user id replacing +## 2.4.0 +* add access checkout by user id +## 2.3.0 +* add support for tokens in get params +## 2.2.0 +* add websocket proxy +## 2.1.0 +* fix proxy path +* add skip authenticate +* add snapshot version +## 2.0.0 +* add integration with isp-config-service 2.0 +## 1.3.0 +* add unload requests +## 1.2.0 +* add snapshot account +## 1.1.0 +* add token verification via JWT +* add accounting for applications +* add optional cache for application tokens diff --git a/Dockerfile.dit b/Dockerfile.dit new file mode 100644 index 0000000..7c20a05 --- /dev/null +++ b/Dockerfile.dit @@ -0,0 +1,18 @@ +FROM dockerhub.mos.ru/golang:1.19-alpine3.16 as builder +WORKDIR /build +ARG version +ENV version_env=$version +ARG app_name +ENV app_name_env=$app_name +COPY . . +ENV GOPROXY=https://repo-mirror.mos.ru/repository/go-public +RUN go build -ldflags="-X 'main.version=$version_env'" -o /main . + +FROM dockerhub.mos.ru/alpine:3.16.0 +WORKDIR /app +ARG app_name +ENV app_name_env=$app_name +COPY --from=builder main /app/$app_name_env +COPY /conf/*.yml /app/ +COPY /conf/default_remote_config.json* /app/default_remote_config.json +ENTRYPOINT /app/$app_name_env diff --git a/assembly/assembly.go b/assembly/assembly.go new file mode 100644 index 0000000..52119b4 --- /dev/null +++ b/assembly/assembly.go @@ -0,0 +1,183 @@ +package assembly + +import ( + "context" + + "github.com/redis/go-redis/v9" + "isp-gate-service/conf" + "isp-gate-service/routes" + + "github.com/integration-system/isp-kit/app" + "github.com/integration-system/isp-kit/bootstrap" + "github.com/integration-system/isp-kit/cluster" + "github.com/integration-system/isp-kit/grpc/client" + "github.com/integration-system/isp-kit/http" + "github.com/integration-system/isp-kit/lb" + "github.com/integration-system/isp-kit/log" + "github.com/pkg/errors" +) + +type Assembly struct { + boot *bootstrap.Bootstrap + server *http.Server + logger *log.Adapter + routes *routes.Routes + redisCli redis.UniversalClient + systemCli *client.Client + adminCli *client.Client + + locations []conf.Location + grpcClientByModuleName map[string]*client.Client + httpHostManagerByModuleName map[string]*lb.RoundRobin +} + +func New(boot *bootstrap.Bootstrap) (*Assembly, error) { + server := http.NewServer(boot.App.Logger()) + + localConfig := conf.Local{} + err := boot.App.Config().Read(&localConfig) + if err != nil { + return nil, errors.WithMessage(err, "read local config") + } + + grpcClientByModuleName := make(map[string]*client.Client) + httpHostManagerByModuleName := make(map[string]*lb.RoundRobin) + for _, location := range localConfig.Locations { + switch location.Protocol { + case conf.GrpcProtocol: + cli, err := client.Default() + if err != nil { + return nil, errors.WithMessage(err, "new grpc client") + } + grpcClientByModuleName[location.TargetModule] = cli + case conf.HttpProtocol, conf.WsProtocol: + rb := lb.NewRoundRobin(nil) + httpHostManagerByModuleName[location.TargetModule] = rb + default: + return nil, errors.Errorf("unexpected location protocol: %s", location.Protocol) + } + } + + systemCli, err := client.Default() + if err != nil { + return nil, errors.WithMessage(err, "create system cli") + } + + adminCli, err := client.Default() + if err != nil { + return nil, errors.WithMessage(err, "create admin cli") + } + + return &Assembly{ + boot: boot, + server: server, + logger: boot.App.Logger(), + routes: routes.NewRoutes(), + locations: localConfig.Locations, + grpcClientByModuleName: grpcClientByModuleName, + httpHostManagerByModuleName: httpHostManagerByModuleName, + systemCli: systemCli, + adminCli: adminCli, + }, nil +} + +func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error { + var ( + newCfg conf.Remote + prevCfg conf.Remote + ) + err := a.boot.RemoteConfig.Upgrade(remoteConfig, &newCfg, &prevCfg) + if err != nil { + a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade remote config")) + } + err = newCfg.Validate() + if err != nil { + a.logger.Fatal(ctx, errors.WithMessage(err, "invalid remote config")) + } + + a.logger.SetLevel(newCfg.Logging.LogLevel) + + var newRedisCli redis.UniversalClient + if newCfg.Redis != nil { + newRedisCli = a.redisClient(*newCfg.Redis) + } + + locator := NewLocator(a.logger, a.grpcClientByModuleName, a.httpHostManagerByModuleName, a.routes, a.systemCli, a.adminCli) + + handler, err := locator.Handler(newCfg, a.locations, newRedisCli) + if err != nil { + return errors.WithMessage(err, "locator handler") + } + + a.server.Upgrade(handler) + + if a.redisCli != nil { + _ = a.redisCli.Close() + a.redisCli = newRedisCli + } + + return nil +} + +func (a *Assembly) Runners() []app.Runner { + eventHandler := cluster.NewEventHandler(). + RoutesReceiver(a.routes). + RemoteConfigReceiver(a) + + for moduleName, upgrader := range a.grpcClientByModuleName { + eventHandler.RequireModule(moduleName, upgrader) + } + for moduleName, upgrader := range a.httpHostManagerByModuleName { + eventHandler.RequireModule(moduleName, upgrader) + } + + eventHandler.RequireModule("isp-system-service", a.systemCli) + eventHandler.RequireModule("msp-admin-service", a.adminCli) + + return []app.Runner{ + app.RunnerFunc(func(ctx context.Context) error { + return a.server.ListenAndServe(a.boot.BindingAddress) + }), + app.RunnerFunc(func(ctx context.Context) error { + return a.boot.ClusterCli.Run(ctx, eventHandler) + }), + } +} + +func (a *Assembly) Closers() []app.Closer { + closers := []app.Closer{ + a.boot.ClusterCli, + app.CloserFunc(func() error { + return a.server.Shutdown(context.Background()) + }), + } + for _, cliCloser := range a.grpcClientByModuleName { + closers = append(closers, cliCloser) + } + closers = append(closers, a.systemCli, a.adminCli, app.CloserFunc(func() error { + if a.redisCli != nil { + return a.redisCli.Close() + } + return nil + })) + + return closers +} + +func (a *Assembly) redisClient(config conf.Redis) redis.UniversalClient { + if config.Sentinel != nil { + return redis.NewFailoverClient(&redis.FailoverOptions{ + MasterName: config.Sentinel.MasterName, + SentinelAddrs: config.Sentinel.Addresses, + SentinelUsername: config.Sentinel.Username, + SentinelPassword: config.Sentinel.Password, + Username: config.Username, + Password: config.Password, + }) + } + return redis.NewClient(&redis.Options{ + Addr: config.Address, + Username: config.Username, + Password: config.Password, + }) +} diff --git a/assembly/locator.go b/assembly/locator.go new file mode 100644 index 0000000..e0381ff --- /dev/null +++ b/assembly/locator.go @@ -0,0 +1,127 @@ +package assembly + +import ( + "net/http" + "time" + + mux2 "github.com/gorilla/mux" + "github.com/redis/go-redis/v9" + "isp-gate-service/conf" + "isp-gate-service/middleware" + "isp-gate-service/proxy" + "isp-gate-service/repository" + "isp-gate-service/routes" + "isp-gate-service/service" + + "github.com/integration-system/isp-kit/grpc/client" + "github.com/integration-system/isp-kit/lb" + "github.com/integration-system/isp-kit/log" + "github.com/pkg/errors" +) + +type Locator struct { + logger log.Logger + grpcClientByModuleName map[string]*client.Client + httpHostManagerByModuleName map[string]*lb.RoundRobin + routes *routes.Routes + systemCli *client.Client + adminCli *client.Client +} + +func NewLocator( + logger log.Logger, + grpcClientByModuleName map[string]*client.Client, + httpHostManagerByModuleName map[string]*lb.RoundRobin, + routes *routes.Routes, + systemCli *client.Client, + adminCli *client.Client, +) Locator { + return Locator{ + logger: logger, + grpcClientByModuleName: grpcClientByModuleName, + httpHostManagerByModuleName: httpHostManagerByModuleName, + routes: routes, + systemCli: systemCli, + adminCli: adminCli, + } +} + +func (l Locator) Handler(config conf.Remote, locations []conf.Location, redisCli redis.UniversalClient) (http.Handler, error) { + systemRepo := repository.NewSystem(l.systemCli) + adminRepo := repository.NewAdmin(l.adminCli) + + authenticationCache := repository.NewAuthenticationCache(time.Duration(config.Caching.AuthenticationDataInSec) * time.Second) + authentication := service.NewAuthentication(authenticationCache, systemRepo) + + adminService := service.NewAdmin( + repository.NewAuthorizationCache(time.Duration(config.Caching.AuthorizationDataInSec)*time.Second), + adminRepo, + ) + + authorization := service.NewAuthorization( + repository.NewAuthorizationCache(time.Duration(config.Caching.AuthorizationDataInSec)*time.Second), + systemRepo, + ) + + dailyLimitRepo := repository.NewDailyLimit(redisCli) + dailyLimitService := service.NewDailyLimit(dailyLimitRepo, config.DailyLimits) + + throttlingRepo := repository.NewThrottling(redisCli) + throttlingService := service.NewThrottling(throttlingRepo, config.Throttling) + + mux := mux2.NewRouter() + for _, location := range locations { + var proxyFunc middleware.Handler + enableBodyLog := config.Logging.BodyLogEnable + + switch location.Protocol { + case conf.GrpcProtocol: + cli := l.grpcClientByModuleName[location.TargetModule] + proxyFunc = proxy.NewGrpc(cli, location.SkipAuth, time.Duration(config.Http.ProxyTimeoutInSec)*time.Second) + case conf.HttpProtocol: + hostManager := l.httpHostManagerByModuleName[location.TargetModule] + proxyFunc = proxy.NewHttp(hostManager, location.SkipAuth, time.Duration(config.Http.ProxyTimeoutInSec)*time.Second) + case conf.WsProtocol: + hostManager := l.httpHostManagerByModuleName[location.TargetModule] + proxyFunc = proxy.NewWs(hostManager, location.SkipAuth) + enableBodyLog = false + default: + return nil, errors.Errorf("not supported protocol %s", location.Protocol) + } + + handler := middleware.Chain( + proxyFunc, + middleware.RequestId(), + middleware.Logger(l.logger, config.Logging.RequestLogEnable, enableBodyLog, + config.Logging.SkipBodyLoggingEndpointPrefixes), + middleware.ErrorHandler(l.logger), + middleware.Authenticate(authentication), + middleware.AdminAuthenticate(adminService), + middleware.Authorize(authorization, l.logger), + middleware.AdminAuthorize(l.routes, adminService), + middleware.Throttling(throttlingService), + middleware.DailyLimit(dailyLimitService), + ) + if location.SkipAuth { + handler = middleware.Chain( + proxyFunc, + middleware.RequestId(), + middleware.Logger(l.logger, config.Logging.RequestLogEnable, enableBodyLog, + config.Logging.SkipBodyLoggingEndpointPrefixes), + middleware.ErrorHandler(l.logger), + ) + } + entrypoint := middleware.Entrypoint( + config.Http.MaxRequestBodySizeInMb*1024*1024, //nolint:gomnd + handler, + l.logger, + middleware.EntryPointConfig{ + WithPrefix: location.WithPrefix, + PathPrefix: location.PathPrefix, + }, + ) + mux.PathPrefix(location.PathPrefix).Handler(entrypoint) + } + + return mux, nil +} diff --git a/cache/cache.go b/cache/cache.go new file mode 100644 index 0000000..feb6565 --- /dev/null +++ b/cache/cache.go @@ -0,0 +1,53 @@ +package cache + +import ( + "sync" + "time" +) + +type Item struct { + data []byte + expiredAt time.Time +} + +type Cache struct { + store map[string]Item + lock *sync.RWMutex +} + +func New() *Cache { + return &Cache{ + store: map[string]Item{}, + lock: &sync.RWMutex{}, + } +} + +func (c *Cache) Get(key string) ([]byte, bool) { + c.lock.RLock() + defer c.lock.RUnlock() + + item, ok := c.store[key] + if !ok { + return nil, false + } + + if c.now().After(item.expiredAt) { + return nil, false + } + + return item.data, true +} + +func (c *Cache) Set(key string, data []byte, lifeTime time.Duration) { + c.lock.Lock() + defer c.lock.Unlock() + + c.store[key] = Item{ + data: data, + expiredAt: c.now().Add(lifeTime), + } +} + +func (c *Cache) now() time.Time { + return time.Now() +} diff --git a/cache/cache_test.go b/cache/cache_test.go new file mode 100644 index 0000000..fc373dc --- /dev/null +++ b/cache/cache_test.go @@ -0,0 +1,47 @@ +package cache_test + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" + "isp-gate-service/cache" +) + +func TestGetBasic(t *testing.T) { + require := require.New(t) + + cache := cache.New() + cache.Set("key", []byte("data"), 24*time.Hour) + + data, ok := cache.Get("key") + require.True(ok) + require.EqualValues("data", data) + + _, ok = cache.Get("key2") + require.False(ok) +} + +func TestGetExpired(t *testing.T) { + require := require.New(t) + + cache := cache.New() + cache.Set("key", []byte("data"), 500*time.Millisecond) + + time.Sleep(1 * time.Second) + + data, ok := cache.Get("key") + require.False(ok) + require.Nil(data) +} + +func TestNilValue(t *testing.T) { + require := require.New(t) + + cache := cache.New() + cache.Set("key", nil, 24*time.Hour) + + data, ok := cache.Get("key") + require.True(ok) + require.Nil(data) +} diff --git a/conf/config.yml b/conf/config.yml new file mode 100644 index 0000000..2ce41fd --- /dev/null +++ b/conf/config.yml @@ -0,0 +1,24 @@ +configServiceAddress: + ip: 127.0.0.1 + port: 9001 +grpcOuterAddress: + #ip: 127.0.0.1 + port: 9003 +grpcInnerAddress: + ip: 0.0.0.0 + port: 9003 +moduleName: isp-gate-service + +infraServerPort: 9553 + +logfile: + path: /var/log/isp-gate-service/runtime.log + maxSizeMb: 512 + maxBackups: 4 + compress: true + + +locations: + - pathPrefix: /api + protocol: grpc + targetModule: router \ No newline at end of file diff --git a/conf/config_kkd.yml b/conf/config_kkd.yml new file mode 100644 index 0000000..e2f51b4 --- /dev/null +++ b/conf/config_kkd.yml @@ -0,0 +1,30 @@ +configServiceAddress: + ip: 127.0.0.1 + port: 9001 +grpcOuterAddress: + #ip: 127.0.0.1 + port: 9003 +grpcInnerAddress: + ip: 0.0.0.0 + port: 9003 +moduleName: isp-gate-service + +infraServerPort: 9553 + +logfile: + path: /var/log/isp-gate-service/runtime.log + maxSizeMb: 512 + maxBackups: 4 + compress: true + +locations: + - pathPrefix: /ws/kkd-configuration-service + protocol: ws + targetModule: kkd-configuration-service + - pathPrefix: /api/kkd-configuration-service + protocol: http + targetModule: kkd-configuration-service + - pathPrefix: /api + protocol: grpc + skipAuth: false + targetModule: router diff --git a/conf/default_remote_config.json b/conf/default_remote_config.json new file mode 100644 index 0000000..8860eb2 --- /dev/null +++ b/conf/default_remote_config.json @@ -0,0 +1,16 @@ +{ + "logging": { + "logLevel": "debug", + "requestLogEnable": true, + "bodyLogEnable": false, + "skipBodyLoggingEndpointPrefixes": [] + }, + "caching": { + "authenticationDataInSec": 60, + "authorizationDataInSec": 60 + }, + "http": { + "maxRequestBodySizeInMb": 64, + "proxyTimeoutInSec": 60 + } +} diff --git a/conf/local.go b/conf/local.go new file mode 100644 index 0000000..5ca0822 --- /dev/null +++ b/conf/local.go @@ -0,0 +1,19 @@ +package conf + +const ( + HttpProtocol = "http" + GrpcProtocol = "grpc" + WsProtocol = "ws" +) + +type Local struct { + Locations []Location +} + +type Location struct { + WithPrefix bool + SkipAuth bool + PathPrefix string `validate:"required"` + Protocol string `validate:"required,oneof=http grpc ws"` + TargetModule string `validate:"required"` +} diff --git a/conf/remote.go b/conf/remote.go new file mode 100644 index 0000000..8f53109 --- /dev/null +++ b/conf/remote.go @@ -0,0 +1,77 @@ +package conf + +import ( + "reflect" + + "github.com/integration-system/isp-kit/log" + "github.com/integration-system/isp-kit/rc/schema" + "github.com/integration-system/jsonschema" + "github.com/pkg/errors" +) + +func init() { + schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Schema) { + t.Type = "string" + t.Enum = []interface{}{"debug", "info", "warn", "error", "fatal"} + }) +} + +type Remote struct { + Redis *Redis `schema:"Настройки Redis,обязательно, если используется механизм суточных ограничений или ограничений пропускной способности"` + Http Http `schema:"Настройки HTTP"` + Logging Logging `schema:"Настройки логирования"` + Caching Caching `schema:"Настройки кеширования"` + DailyLimits []DailyLimit `schema:"Настройки суточных ограничений,сбрасываются раз в сутки в 00:00"` + Throttling []Throttling `schema:"Настройки пропускной способности"` +} + +type Http struct { + MaxRequestBodySizeInMb int64 `validate:"required" schema:"Максимальная длинна тела запроса,в мегабайтах"` + ProxyTimeoutInSec int `validate:"required" schema:"Таймаут на проксирование,в секундах"` +} + +type Logging struct { + LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования,логирование запросов осуществляется на уровне debug"` + RequestLogEnable bool `schema:"Включить логирование запросов"` + BodyLogEnable bool `schema:"Включить логирование тел запросов и ответов,должно быть включено логирование запросов"` + SkipBodyLoggingEndpointPrefixes []string `schema:"регулярные выражения для отключения логирования"` +} + +type Caching struct { + AuthenticationDataInSec int `validate:"required" schema:"Время кеширования данных аутентификации,в секундах"` + AuthorizationDataInSec int `validate:"required" schema:"Время кеширования данных авторизации,в секундах"` +} + +type DailyLimit struct { + ApplicationId int `validate:"required" schema:"ID приложения"` + RequestsPerDay int64 `validate:"required" schema:"Запросов в сутки"` +} + +type Throttling struct { + ApplicationId int `validate:"required" schema:"ID приложения"` + RequestsPerSeconds int `validate:"required,min=1,max=1000" schema:"Запросов в секунду,не конфликтует с суточными ограничениями, алгоритм не работает на значениях больше 1000"` +} + +type Redis struct { + Address string `schema:"Адрес,обязателено, если sentinel не указан"` + Username string `schema:"Имя пользовтаеля"` + Password string `schema:"Пароль"` + Sentinel *RedisSentinel `schema:"Настройки sentinel,обязательно, если address не указан"` +} + +type RedisSentinel struct { + Addresses []string `validate:"required" schema:"Адреса нод в кластере"` + MasterName string `validate:"required" schema:"Имя мастера"` + Username string `schema:"Имя пользовтаеля в sentinel"` + Password string `schema:"Пароль в sentinel"` +} + +func (r Remote) Validate() error { + if (len(r.Throttling) > 0 || len(r.DailyLimits) > 0) && r.Redis == nil { + return errors.New("redis is required if dailyLimits or throttling were specified") + } + if r.Redis != nil && r.Redis.Sentinel == nil && r.Redis.Address == "" { + return errors.New("invalid redis config. sentinel or address are required") + } + return nil +} diff --git a/conf/remote_test.go b/conf/remote_test.go new file mode 100644 index 0000000..d939041 --- /dev/null +++ b/conf/remote_test.go @@ -0,0 +1,13 @@ +package conf_test + +import ( + "testing" + + "github.com/integration-system/isp-kit/test/rct" + "isp-gate-service/conf" +) + +func TestDefaultRemoteConfig(t *testing.T) { + t.Parallel() + rct.Test(t, "default_remote_config.json", conf.Remote{}) +} diff --git a/domain/admin.go b/domain/admin.go new file mode 100644 index 0000000..cbcd737 --- /dev/null +++ b/domain/admin.go @@ -0,0 +1,7 @@ +package domain + +type AdminAuthenticateResponse struct { + Authenticated bool + ErrorReason string + AdminId int +} diff --git a/domain/auth.go b/domain/auth.go new file mode 100644 index 0000000..1813906 --- /dev/null +++ b/domain/auth.go @@ -0,0 +1,8 @@ +package domain + +type AuthData struct { + SystemId int + DomainId int + ServiceId int + ApplicationId int +} diff --git a/domain/cache.go b/domain/cache.go new file mode 100644 index 0000000..9436b4f --- /dev/null +++ b/domain/cache.go @@ -0,0 +1,9 @@ +package domain + +import ( + "github.com/pkg/errors" +) + +var ( + ErrAuthenticationCacheMiss = errors.New("authentication not found in cache") +) diff --git a/domain/system.go b/domain/system.go new file mode 100644 index 0000000..9efeb27 --- /dev/null +++ b/domain/system.go @@ -0,0 +1,29 @@ +package domain + +type AuthenticateRequest struct { + Token string +} + +type AuthenticateResponse struct { + Authenticated bool + ErrorReason string + AuthData *AuthData +} + +type AuthorizeRequest struct { + ApplicationId int + Endpoint string +} + +type AuthorizeResponse struct { + Authorized bool +} + +type AdminAuthorizeRequest struct { + AdminId int + Permission string +} + +type AdminAuthorizeResponse struct { + Authorized bool +} diff --git a/domain/throttling.go b/domain/throttling.go new file mode 100644 index 0000000..6272732 --- /dev/null +++ b/domain/throttling.go @@ -0,0 +1,11 @@ +package domain + +import ( + "time" +) + +type RateLimitResult struct { + Allow bool + Remaining int + RetryAfter time.Duration +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..ea58c8b --- /dev/null +++ b/go.mod @@ -0,0 +1,77 @@ +module isp-gate-service + +go 1.21 + +require ( + github.com/go-redis/redis_rate/v10 v10.0.1 + github.com/google/uuid v1.4.0 + github.com/gorilla/mux v1.8.1 + github.com/gorilla/websocket v1.5.1 + github.com/integration-system/isp-etp-go/v2 v2.1.3 + github.com/integration-system/isp-kit v1.27.0 + github.com/integration-system/jsonschema v1.1.0 + github.com/pkg/errors v0.9.1 + github.com/redis/go-redis/v9 v9.3.0 + github.com/stretchr/testify v1.8.4 + github.com/tomakado/websocketproxy v0.1.0 + golang.org/x/net v0.19.0 + google.golang.org/genproto/googleapis/rpc v0.0.0-20231127180814-3a041ad873d4 + google.golang.org/grpc v1.59.0 +) + +require ( + github.com/bahlo/generic-list-go v0.2.0 // indirect + github.com/beorn7/perks v1.0.1 // indirect + github.com/buger/jsonparser v1.1.1 // indirect + github.com/cenkalti/backoff/v4 v4.2.1 // indirect + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/gabriel-vasile/mimetype v1.4.2 // indirect + github.com/getsentry/sentry-go v0.25.0 // indirect + github.com/go-logr/logr v1.3.0 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/golang/protobuf v1.5.3 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.1 // indirect + github.com/hashicorp/errwrap v1.1.0 // indirect + github.com/hashicorp/go-multierror v1.1.1 // indirect + github.com/integration-system/bellows v1.0.1 // indirect + github.com/integration-system/validator/v10 v10.0.0-20231205122740-49807820d98b // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/julienschmidt/httprouter v1.3.0 // indirect + github.com/leodido/go-urn v1.2.4 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/prometheus/client_golang v1.17.0 // indirect + github.com/prometheus/client_model v0.5.0 // indirect + github.com/prometheus/common v0.45.0 // indirect + github.com/prometheus/procfs v0.12.0 // indirect + github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect + github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect + github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect + github.com/xeipuuv/gojsonschema v1.2.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.46.1 // indirect + go.opentelemetry.io/otel v1.21.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.21.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.21.0 // indirect + go.opentelemetry.io/otel/metric v1.21.0 // indirect + go.opentelemetry.io/otel/sdk v1.21.0 // indirect + go.opentelemetry.io/otel/trace v1.21.0 // indirect + go.opentelemetry.io/proto/otlp v1.0.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + go.uber.org/zap v1.26.0 // indirect + golang.org/x/crypto v0.16.0 // indirect + golang.org/x/sys v0.15.0 // indirect + golang.org/x/text v0.14.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20231127180814-3a041ad873d4 // indirect + google.golang.org/protobuf v1.31.0 // indirect + gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + nhooyr.io/websocket v1.8.10 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..1125550 --- /dev/null +++ b/go.sum @@ -0,0 +1,239 @@ +github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= +github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= +github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk= +github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs= +github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= +github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM= +github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= +github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= +github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= +github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= +github.com/getsentry/sentry-go v0.25.0 h1:q6Eo+hS+yoJlTO3uu/azhQadsD8V+jQn2D8VvX1eOyI= +github.com/getsentry/sentry-go v0.25.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= +github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= +github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.3.0 h1:2y3SDp0ZXuc6/cjLSZ+Q3ir+QB9T/iG5yYRXqsagWSY= +github.com/go-logr/logr v1.3.0/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= +github.com/go-redis/redis_rate/v10 v10.0.1 h1:calPxi7tVlxojKunJwQ72kwfozdy25RjA0bCj1h0MUo= +github.com/go-redis/redis_rate/v10 v10.0.1/go.mod h1:EMiuO9+cjRkR7UvdvwMO7vbgqJkltQHtwbdIQvaBKIU= +github.com/go-resty/resty/v2 v2.10.0 h1:Qla4W/+TMmv0fOeeRqzEpXPLfTUnR5HZ1+lGs+CkiCo= +github.com/go-resty/resty/v2 v2.10.0/go.mod h1:iiP/OpA0CkcL3IGt1O0+/SIItFUbkkyw5BGXiVdTu+A= +github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= +github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= +github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= +github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4= +github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= +github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= +github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY= +github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.1 h1:6UKoz5ujsI55KNpsJH3UwCq3T8kKbZwNZBNPuTTje8U= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.1/go.mod h1:YvJ2f6MplWDhfxiUC3KpyTy76kYUZA4W3pTv/wdKQ9Y= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/integration-system/bellows v1.0.1 h1:7g1lhD/6EcvsSo9iuiFqw98XGS78Sko6kUKPzfte/SY= +github.com/integration-system/bellows v1.0.1/go.mod h1:qHPg1ptN3AHHr0f/wvoicfA2LOCprOyrbXnIa5QIRe0= +github.com/integration-system/grmq v1.4.2 h1:BFO9ahqnb3SpMCt5zxaRAh1iiILkC8tqmNcxRHHpmh8= +github.com/integration-system/grmq v1.4.2/go.mod h1:DeE6Ceo/A+MuvzdPkuZzqajy0VJhOyH7rRxksQqhEYk= +github.com/integration-system/isp-etp-go/v2 v2.1.3 h1:vcHP/PE7p1G3rxqoVKrKtXzoSxFA4ryxigd+zPkAb3w= +github.com/integration-system/isp-etp-go/v2 v2.1.3/go.mod h1:ZpB+FIH3hy7md+f8ylVSQx5zwZVjczhkc45f1B2z9nw= +github.com/integration-system/isp-kit v1.27.0 h1:NgxEUBrL+1Rv4C1nyfFb5TKu9M7DO3WmTYx5Mk1Vc00= +github.com/integration-system/isp-kit v1.27.0/go.mod h1:/2CMMhgRnNehijkUcJLePZGTgTTIiotg2NiUm7rM30o= +github.com/integration-system/jsonschema v1.1.0 h1:l9jshYRkImMHfHTPWaUEhP37gX9yW5l7cRHOcIH4g8k= +github.com/integration-system/jsonschema v1.1.0/go.mod h1:vrRpWq+l1NFXffXnodH4fYWyt9sLtlx+UJ39S3b/jsA= +github.com/integration-system/validator/v10 v10.0.0-20231205122740-49807820d98b h1:/N1rgICVeP04g3+2ATmILUfD2clpHCJ9bzmwqeBw21s= +github.com/integration-system/validator/v10 v10.0.0-20231205122740-49807820d98b/go.mod h1:vLdiU06b11Kfto2J+XD6o76cIkGtwQmCBNj65fRuQl4= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U= +github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= +github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= +github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= +github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 h1:jWpvCLoY8Z/e3VKvlsiIGKtc+UG6U5vzxaoagmhXfyg= +github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0/go.mod h1:QUyp042oQthUoa9bqDv0ER0wrtXnBruoNd7aNjkbP+k= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= +github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v1.17.0 h1:rl2sfwZMtSthVU752MqfjQozy7blglC+1SOtjMAMh+Q= +github.com/prometheus/client_golang v1.17.0/go.mod h1:VeL+gMmOAxkS2IqfCq0ZmHSL+LjWfWDUmp1mBz9JgUY= +github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cYPYQjL0Qw= +github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI= +github.com/prometheus/common v0.45.0 h1:2BGz0eBc2hdMDLnO/8n0jeB3oPrt2D08CekT0lneoxM= +github.com/prometheus/common v0.45.0/go.mod h1:YJmSTw9BoKxJplESWWxlbyttQR4uaEcGyv9MZjVOJsY= +github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo= +github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo= +github.com/rabbitmq/amqp091-go v1.9.0 h1:qrQtyzB4H8BQgEuJwhmVQqVHB9O4+MNDJCCAcpc3Aoo= +github.com/rabbitmq/amqp091-go v1.9.0/go.mod h1:+jPrT9iY2eLjRaMSRHUhc3z14E/l85kv/f+6luSD3pc= +github.com/redis/go-redis/v9 v9.3.0 h1:RiVDjmig62jIWp7Kk4XVLs0hzV6pI3PyTnnL0cnn0u0= +github.com/redis/go-redis/v9 v9.3.0/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/tomakado/websocketproxy v0.1.0 h1:e037TLXDvEYYHlxHE5pqmj/DytFKm2NRn7i4wbVzIyE= +github.com/tomakado/websocketproxy v0.1.0/go.mod h1:EXg/3jcTJYZ04Hsf93RpY90FYA9lj1Sl+VM7lZI6xpM= +github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= +github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= +github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc= +github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= +github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= +github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= +go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.46.1 h1:gbhw/u49SS3gkPWiYweQNJGm/uJN5GkI/FrosxSHT7A= +go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.46.1/go.mod h1:GnOaBaFQ2we3b9AGWJpsBa7v1S5RlQzlC3O7dRMxZhM= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.46.1 h1:aFJWCqJMNjENlcleuuOkGAPH82y0yULBScfXcIEdS24= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.46.1/go.mod h1:sEGXWArGqc3tVa+ekntsN65DmVbVeW+7lTKTjZF3/Fo= +go.opentelemetry.io/otel v1.21.0 h1:hzLeKBZEL7Okw2mGzZ0cc4k/A7Fta0uoPgaJCr8fsFc= +go.opentelemetry.io/otel v1.21.0/go.mod h1:QZzNPQPm1zLX4gZK4cMi+71eaorMSGT3A4znnUvNNEo= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.21.0 h1:cl5P5/GIfFh4t6xyruOgJP5QiA1pw4fYYdv6nc6CBWw= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.21.0/go.mod h1:zgBdWWAu7oEEMC06MMKc5NLbA/1YDXV1sMpSqEeLQLg= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.21.0 h1:digkEZCJWobwBqMwC0cwCq8/wkkRy/OowZg5OArWZrM= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.21.0/go.mod h1:/OpE/y70qVkndM0TrxT4KBoN3RsFZP0QaofcfYrj76I= +go.opentelemetry.io/otel/metric v1.21.0 h1:tlYWfeo+Bocx5kLEloTjbcDwBuELRrIFxwdQ36PlJu4= +go.opentelemetry.io/otel/metric v1.21.0/go.mod h1:o1p3CA8nNHW8j5yuQLdc1eeqEaPfzug24uvsyIEJRWM= +go.opentelemetry.io/otel/sdk v1.21.0 h1:FTt8qirL1EysG6sTQRZ5TokkU8d0ugCj8htOgThZXQ8= +go.opentelemetry.io/otel/sdk v1.21.0/go.mod h1:Nna6Yv7PWTdgJHVRD9hIYywQBRx7pbox6nwBnZIxl/E= +go.opentelemetry.io/otel/trace v1.21.0 h1:WD9i5gzvoUPuXIXH24ZNBudiarZDKuekPqi/E8fpfLc= +go.opentelemetry.io/otel/trace v1.21.0/go.mod h1:LGbsEB0f9LGjN+OZaQQ26sohbOmiMR+BaslueVtS/qQ= +go.opentelemetry.io/proto/otlp v1.0.0 h1:T0TX0tmXU8a3CbNXzEKGeU5mIVOdf0oykP+u2lIVU/I= +go.opentelemetry.io/proto/otlp v1.0.0/go.mod h1:Sy6pihPLfYHkr3NkUbEhGHFhINUSI/v80hjKIs5JXpM= +go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= +go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk= +go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo= +go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.16.0 h1:mMMrFzRSCF0GvB7Ne27XVtVAaXLrPmgPC7/v0tkwHaY= +golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c= +golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE= +golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= +golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/genproto v0.0.0-20231120223509-83a465c0220f h1:Vn+VyHU5guc9KjB5KrjI2q0wCOWEOIh0OEsleqakHJg= +google.golang.org/genproto v0.0.0-20231120223509-83a465c0220f/go.mod h1:nWSwAFPb+qfNJXsoeO3Io7zf4tMSfN8EA8RlDA04GhY= +google.golang.org/genproto/googleapis/api v0.0.0-20231127180814-3a041ad873d4 h1:ZcOkrmX74HbKFYnpPY8Qsw93fC29TbJXspYKaBkSXDQ= +google.golang.org/genproto/googleapis/api v0.0.0-20231127180814-3a041ad873d4/go.mod h1:k2dtGpRrbsSyKcNPKKI5sstZkrNCZwpU/ns96JoHbGg= +google.golang.org/genproto/googleapis/rpc v0.0.0-20231127180814-3a041ad873d4 h1:DC7wcm+i+P1rN3Ff07vL+OndGg5OhNddHyTA+ocPqYE= +google.golang.org/genproto/googleapis/rpc v0.0.0-20231127180814-3a041ad873d4/go.mod h1:eJVxU6o+4G1PSczBr85xmyvSNYAKvAYgkub40YGomFM= +google.golang.org/grpc v1.59.0 h1:Z5Iec2pjwb+LEOqzpB2MR12/eKFhDPhuqW91O+4bwUk= +google.golang.org/grpc v1.59.0/go.mod h1:aUPDwccQo6OTjy7Hct4AfBPD1GptF4fyUjIkQ9YtF98= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= +google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= +gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +nhooyr.io/websocket v1.8.7/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0= +nhooyr.io/websocket v1.8.10 h1:mv4p+MnGrLDcPlBoWsvPP7XCzTYMXP9F9eIGoKbgx7Q= +nhooyr.io/websocket v1.8.10/go.mod h1:rN9OFWIUwuxg4fR5tELlYC04bXYowCP9GX47ivo2l+c= diff --git a/httperrors/errors.go b/httperrors/errors.go new file mode 100644 index 0000000..df42dbe --- /dev/null +++ b/httperrors/errors.go @@ -0,0 +1,41 @@ +package httperrors + +import ( + "net/http" + + "github.com/integration-system/isp-kit/json" +) + +type HttpError struct { + statusCode int + userMessage string + details []interface{} + err error +} + +func New(statusCode int, userMessage string, internalError error) HttpError { + return HttpError{ + statusCode: statusCode, + userMessage: userMessage, + err: internalError, + } +} + +func (e HttpError) Error() string { + return e.err.Error() +} + +func (e HttpError) WriteError(w http.ResponseWriter) error { + w.Header().Set("content-type", "application/json") + w.WriteHeader(e.statusCode) + data := map[string]interface{}{ + "errorCode": http.StatusText(e.statusCode), + "errorMessage": e.userMessage, + "details": e.details, + } + return json.NewEncoder(w).Encode(data) +} + +func (e *HttpError) WithDetails(details ...interface{}) { + e.details = details +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..1a2ebb4 --- /dev/null +++ b/main.go @@ -0,0 +1,37 @@ +package main + +import ( + "github.com/integration-system/isp-kit/bootstrap" + "github.com/integration-system/isp-kit/shutdown" + "isp-gate-service/assembly" + "isp-gate-service/conf" +) + +var ( + version = "1.0.0" +) + +func main() { + boot := bootstrap.New(version, conf.Remote{}, nil) + app := boot.App + logger := app.Logger() + + assembly, err := assembly.New(boot) + if err != nil { + logger.Fatal(app.Context(), err) + } + app.AddRunners(assembly.Runners()...) + app.AddClosers(assembly.Closers()...) + + shutdown.On(func() { + logger.Info(app.Context(), "starting shutdown") + app.Shutdown() + logger.Info(app.Context(), "shutdown completed") + }) + + err = app.Run() + if err != nil { + app.Shutdown() + logger.Fatal(app.Context(), err) + } +} diff --git a/middleware/admin_authenticate.go b/middleware/admin_authenticate.go new file mode 100644 index 0000000..40b0dd6 --- /dev/null +++ b/middleware/admin_authenticate.go @@ -0,0 +1,48 @@ +package middleware + +import ( + "context" + "net/http" + + "isp-gate-service/domain" + "isp-gate-service/httperrors" + "isp-gate-service/request" + + "github.com/pkg/errors" +) + +const ( + adminAuthHeader = "x-auth-admin" +) + +type AdminAuthenticator interface { + AdminAuthenticate(ctx context.Context, token string) (*domain.AdminAuthenticateResponse, error) +} + +func AdminAuthenticate(auth AdminAuthenticator) Middleware { + return func(next Handler) Handler { + return HandlerFunc(func(ctx *request.Context) error { + adminToken := ctx.Param(adminAuthHeader) + if adminToken == "" { + return next.Handle(ctx) + } + resp, err := auth.AdminAuthenticate(ctx.Context(), adminToken) + if err != nil { + return httperrors.New( + http.StatusUnauthorized, + "invalid admin token", + errors.WithMessage(err, "admin authenticate: authenticate"), + ) + } + if !resp.Authenticated { + return httperrors.New( + http.StatusUnauthorized, + "invalid admin token", + errors.WithMessage(errors.New(resp.ErrorReason), "admin authenticate: authenticate"), + ) + } + ctx.AuthenticateAdmin(resp.AdminId, adminToken) + return next.Handle(ctx) + }) + } +} diff --git a/middleware/admin_authorize.go b/middleware/admin_authorize.go new file mode 100644 index 0000000..4579ca8 --- /dev/null +++ b/middleware/admin_authorize.go @@ -0,0 +1,60 @@ +package middleware + +import ( + "context" + "net/http" + + "github.com/pkg/errors" + "isp-gate-service/httperrors" + "isp-gate-service/request" +) + +type AdminMethodStore interface { + IsInnerEndpoint(path string) bool + RequiredAdminPermission(path string) (string, bool) +} + +type AdminAuthorizer interface { + AdminAuthorize(ctx context.Context, adminId int, permission string) (bool, error) +} + +func AdminAuthorize(store AdminMethodStore, authorizer AdminAuthorizer) Middleware { + return func(next Handler) Handler { + return HandlerFunc(func(ctx *request.Context) error { + isInner := store.IsInnerEndpoint(ctx.Endpoint()) + if !isInner { + return next.Handle(ctx) + } + + if !ctx.IsAdminAuthenticated() { + return httperrors.New( + http.StatusForbidden, + "admin authentication required", + errors.Errorf("admin authorization: admin authentication required for '%s'", ctx.Endpoint()), + ) + } + + requiredPerm, ok := store.RequiredAdminPermission(ctx.Endpoint()) + if !ok { + return next.Handle(ctx) + } + + ok, err := authorizer.AdminAuthorize(ctx.Context(), ctx.AdminId(), requiredPerm) + if err != nil { + return errors.WithMessage(err, "admin authorization: authorize") + } + if !ok { + return httperrors.New( + http.StatusForbidden, + "endpoint is not allowed", + errors.Errorf( + "admin authorization: endpoint '%s' requires '%s' permission, but admin '%d' doesn't have it", + ctx.Endpoint(), requiredPerm, ctx.AdminId(), + ), + ) + } + + return next.Handle(ctx) + }) + } +} diff --git a/middleware/authenticate.go b/middleware/authenticate.go new file mode 100644 index 0000000..ced3821 --- /dev/null +++ b/middleware/authenticate.go @@ -0,0 +1,49 @@ +package middleware + +import ( + "context" + "net/http" + + "github.com/pkg/errors" + "isp-gate-service/domain" + "isp-gate-service/httperrors" + "isp-gate-service/request" +) + +const ( + applicationTokenHeader = "x-application-token" +) + +type Authenticator interface { + Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error) +} + +func Authenticate(authenticator Authenticator) Middleware { + return func(next Handler) Handler { + return HandlerFunc(func(ctx *request.Context) error { + token := ctx.Param(applicationTokenHeader) + if token == "" { + return httperrors.New( + http.StatusUnauthorized, + "application token required", + errors.New("authenticate: application token required"), + ) + } + + resp, err := authenticator.Authenticate(ctx.Context(), token) + if err != nil { + return errors.WithMessagef(err, "authenticate: authenticate") + } + if !resp.Authenticated { + return httperrors.New( + http.StatusUnauthorized, + "invalid application token", + errors.WithMessage(errors.New(resp.ErrorReason), "authenticate: authenticate"), + ) + } + ctx.Authenticate(request.AuthData(*resp.AuthData)) + + return next.Handle(ctx) + }) + } +} diff --git a/middleware/authorize.go b/middleware/authorize.go new file mode 100644 index 0000000..2a9c3b8 --- /dev/null +++ b/middleware/authorize.go @@ -0,0 +1,49 @@ +package middleware + +import ( + "context" + "net/http" + + "github.com/integration-system/isp-kit/log" + "github.com/pkg/errors" + "isp-gate-service/httperrors" + "isp-gate-service/request" +) + +type Authorizer interface { + Authorize(ctx context.Context, applicationId int, endpoint string) (bool, error) +} + +func Authorize(authorizer Authorizer, logger log.Logger) Middleware { + return func(next Handler) Handler { + return HandlerFunc(func(ctx *request.Context) error { + authData, err := ctx.GetAuthData() + if err != nil { + return errors.WithMessage(err, "authorize: get auth data") + } + + ok, err := authorizer.Authorize(ctx.Context(), authData.ApplicationId, ctx.Endpoint()) + if err != nil { + return errors.WithMessage(err, "authorize: authorize") + } + if !ok && ctx.IsAdminAuthenticated() { + logger.Info( + ctx.Context(), + "bypassing unauthorized request because it has admin privilege", + log.Int("applicationId", authData.ApplicationId), + log.Int("adminId", ctx.AdminId()), + ) + return next.Handle(ctx) + } + if !ok { + return httperrors.New( + http.StatusForbidden, + "endpoint is not allowed", + errors.Errorf("authorize: endpoint '%s' is not allowed for application '%d'", ctx.Endpoint(), authData.ApplicationId), + ) + } + + return next.Handle(ctx) + }) + } +} diff --git a/middleware/daily_limit.go b/middleware/daily_limit.go new file mode 100644 index 0000000..4ca063b --- /dev/null +++ b/middleware/daily_limit.go @@ -0,0 +1,39 @@ +package middleware + +import ( + "context" + "net/http" + + "github.com/pkg/errors" + "isp-gate-service/httperrors" + "isp-gate-service/request" +) + +type DailyLimitChecker interface { + IncrementAndCheck(ctx context.Context, applicationId int) (bool, error) +} + +func DailyLimit(checker DailyLimitChecker) Middleware { + return func(next Handler) Handler { + return HandlerFunc(func(ctx *request.Context) error { + authData, err := ctx.GetAuthData() + if err != nil { + return errors.WithMessage(err, "daily limit: get auth data") + } + + ok, err := checker.IncrementAndCheck(ctx.Context(), authData.ApplicationId) + if err != nil { + return errors.WithMessage(err, "daily limit: increment and check") + } + if !ok { + return httperrors.New( + http.StatusTooManyRequests, + "daily requests limit has been reached", + errors.Errorf("daily limit: daily requests limit has been reached for application '%d'", authData.ApplicationId), + ) + } + + return next.Handle(ctx) + }) + } +} diff --git a/middleware/entrypoint.go b/middleware/entrypoint.go new file mode 100644 index 0000000..91cd85c --- /dev/null +++ b/middleware/entrypoint.go @@ -0,0 +1,34 @@ +package middleware + +import ( + "fmt" + "net/http" + "strings" + + "github.com/integration-system/isp-kit/log" + "github.com/pkg/errors" + "isp-gate-service/request" +) + +type EntryPointConfig struct { + PathPrefix string + WithPrefix bool +} + +func Entrypoint(maxReqBodySize int64, next Handler, logger log.Logger, cfg EntryPointConfig) http.Handler { + return http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) { + req.Body = http.MaxBytesReader(writer, req.Body, maxReqBodySize) + + endpoint := req.URL.Path + if !cfg.WithPrefix { + prefix := fmt.Sprintf("%s/", cfg.PathPrefix) + endpoint = strings.TrimPrefix(req.URL.Path, prefix) + } + ctx := request.NewContext(req, writer, endpoint) + + err := next.Handle(ctx) + if err != nil { + logger.Error(req.Context(), errors.WithMessage(err, "uncaught error")) + } + }) +} diff --git a/middleware/error_handler.go b/middleware/error_handler.go new file mode 100644 index 0000000..09717c7 --- /dev/null +++ b/middleware/error_handler.go @@ -0,0 +1,35 @@ +package middleware + +import ( + "net/http" + + "github.com/integration-system/isp-kit/log" + "isp-gate-service/httperrors" + "isp-gate-service/request" +) + +type HttpError interface { + WriteError(w http.ResponseWriter) error +} + +func ErrorHandler(logger log.Logger) Middleware { + return func(next Handler) Handler { + return HandlerFunc(func(ctx *request.Context) error { + err := next.Handle(ctx) + if err == nil { + return nil + } + + logger.Error(ctx.Context(), err) + + httpErr, ok := err.(HttpError) + if ok { + return httpErr.WriteError(ctx.ResponseWriter()) + } + + return httperrors. + New(http.StatusInternalServerError, "internal service error", err). + WriteError(ctx.ResponseWriter()) + }) + } +} diff --git a/middleware/logger.go b/middleware/logger.go new file mode 100644 index 0000000..4642238 --- /dev/null +++ b/middleware/logger.go @@ -0,0 +1,121 @@ +package middleware + +import ( + "bufio" + "bytes" + "io" + "net" + "net/http" + "strings" + + "github.com/integration-system/isp-kit/http/endpoint/buffer" + "github.com/integration-system/isp-kit/log" + "github.com/pkg/errors" + "isp-gate-service/request" +) + +type scSource interface { + StatusCode() int +} + +type writerWrapper struct { + http.ResponseWriter + statusCode int +} + +func (w *writerWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) { + upstream, ok := w.ResponseWriter.(http.Hijacker) + if !ok { + return nil, nil, errors.New("writerWrapper: upstream writer doesn't implement Hijack") + } + return upstream.Hijack() +} + +func (w *writerWrapper) StatusCode() int { + if w.statusCode == 0 { + return http.StatusOK + } + return w.statusCode +} + +func (w *writerWrapper) WriteHeader(statusCode int) { + w.statusCode = statusCode + w.ResponseWriter.WriteHeader(statusCode) +} + +func Logger( + logger log.Logger, + enableRequestLogging bool, + enableBodyLogging bool, + skipBodyLoggingEndpointPrefixes []string, +) Middleware { + return func(next Handler) Handler { + return HandlerFunc(func(ctx *request.Context) error { + if !enableRequestLogging { + return next.Handle(ctx) + } + + r := ctx.Request() + + logBodyFromCurrenRequest := enableBodyLogging + if logBodyFromCurrenRequest { + for _, prefix := range skipBodyLoggingEndpointPrefixes { + if strings.HasPrefix(ctx.Endpoint(), prefix) { + logBodyFromCurrenRequest = false + break + } + } + } + + var scSrc scSource + var buf *buffer.Buffer + if logBodyFromCurrenRequest { + buf = buffer.Acquire(ctx.ResponseWriter()) + defer buffer.Release(buf) + + err := buf.ReadRequestBody(r.Body) + if err != nil { + return errors.WithMessage(err, "logger: read request body for logging") + } + err = r.Body.Close() + if err != nil { + return errors.WithMessage(err, "logger: close request reader") + } + r.Body = io.NopCloser(bytes.NewBuffer(buf.RequestBody())) + + scSrc = buf + ctx.SetResponseWriter(buf) + } else { + writer := &writerWrapper{ResponseWriter: ctx.ResponseWriter()} + scSrc = writer + ctx.SetResponseWriter(writer) + } + + originalPath := r.URL.Path // + // can be changed in http proxy + err := next.Handle(ctx) + + authData, _ := ctx.GetAuthData() + fields := []log.Field{ + log.String("http_method", r.Method), + log.String("remote_addr", r.RemoteAddr), + log.String("x_forwarded_for", r.Header.Get("X-Forwarded-For")), + log.Int("status_code", scSrc.StatusCode()), + log.String("path", originalPath), + log.String("endpoint", ctx.Endpoint()), + log.Int("application_id", authData.ApplicationId), + log.Int("admin_id", ctx.AdminId()), + } + + if logBodyFromCurrenRequest { + fields = append(fields, + log.ByteString("request", buf.RequestBody()), + log.ByteString("response", buf.ResponseBody()), + ) + } + logger.Debug(ctx.Context(), "log request", fields...) + + return err + }) + } +} diff --git a/middleware/middleware.go b/middleware/middleware.go new file mode 100644 index 0000000..5d60db0 --- /dev/null +++ b/middleware/middleware.go @@ -0,0 +1,24 @@ +package middleware + +import ( + "isp-gate-service/request" +) + +type Handler interface { + Handle(ctx *request.Context) error +} + +type HandlerFunc func(ctx *request.Context) error + +func (f HandlerFunc) Handle(ctx *request.Context) error { + return f(ctx) +} + +type Middleware func(next Handler) Handler + +func Chain(root Handler, middlewares ...Middleware) Handler { + for i := len(middlewares) - 1; i >= 0; i-- { + root = middlewares[i](root) + } + return root +} diff --git a/middleware/request_id.go b/middleware/request_id.go new file mode 100644 index 0000000..95ed550 --- /dev/null +++ b/middleware/request_id.go @@ -0,0 +1,31 @@ +package middleware + +import ( + "strings" + + "github.com/integration-system/isp-kit/log" + "github.com/integration-system/isp-kit/requestid" + "isp-gate-service/request" +) + +const ( + requestIdHeader = "x-request-id" +) + +func RequestId() Middleware { + return func(next Handler) Handler { + return HandlerFunc(func(ctx *request.Context) error { + requestId := strings.TrimSpace(ctx.Request().Header.Get(requestIdHeader)) + if requestId == "" { + requestId = requestid.Next() + } + + context := requestid.ToContext(ctx.Context(), requestId) + context = log.ToContext(context, log.String("requestId", requestId)) + + ctx.SetContext(context) + + return next.Handle(ctx) + }) + } +} diff --git a/middleware/throttling.go b/middleware/throttling.go new file mode 100644 index 0000000..8abd3f8 --- /dev/null +++ b/middleware/throttling.go @@ -0,0 +1,41 @@ +package middleware + +import ( + "context" + "fmt" + "net/http" + + "github.com/pkg/errors" + "isp-gate-service/domain" + "isp-gate-service/httperrors" + "isp-gate-service/request" +) + +type Throttler interface { + AllowRateLimit(ctx context.Context, applicationId int) (*domain.RateLimitResult, error) +} + +func Throttling(throttler Throttler) Middleware { + return func(next Handler) Handler { + return HandlerFunc(func(ctx *request.Context) error { + authData, err := ctx.GetAuthData() + if err != nil { + return errors.WithMessage(err, "throttling: get auth data") + } + + result, err := throttler.AllowRateLimit(ctx.Context(), authData.ApplicationId) + if err != nil { + return errors.WithMessage(err, "throttling: allow rate limit") + } + if !result.Allow { + return httperrors.New( + http.StatusTooManyRequests, + fmt.Sprintf("rate limit has been reached, try after %dms", result.RetryAfter.Milliseconds()), + errors.Errorf("throttling: rate limit has been reached for application '%d'", authData.ApplicationId), + ) + } + + return next.Handle(ctx) + }) + } +} diff --git a/proxy/const.go b/proxy/const.go new file mode 100644 index 0000000..a332011 --- /dev/null +++ b/proxy/const.go @@ -0,0 +1,5 @@ +package proxy + +const ( + xAdminIdHeader = "x-admin-id" +) diff --git a/proxy/grpc.go b/proxy/grpc.go new file mode 100644 index 0000000..1cdc406 --- /dev/null +++ b/proxy/grpc.go @@ -0,0 +1,160 @@ +package proxy + +import ( + "context" + "io" + "net/http" + "strconv" + "time" + + "isp-gate-service/httperrors" + "isp-gate-service/request" + + "github.com/integration-system/isp-kit/grpc" + "github.com/integration-system/isp-kit/grpc/client" + "github.com/integration-system/isp-kit/grpc/isp" + "github.com/integration-system/isp-kit/json" + "github.com/integration-system/isp-kit/requestid" + "github.com/pkg/errors" + _ "google.golang.org/genproto/googleapis/rpc/errdetails" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +func init() { + for httpCode, grpcCode := range codeMap { + inverseCodeMap[grpcCode] = httpCode + } +} + +var ( + codeMap = map[int]codes.Code{ + http.StatusOK: codes.OK, + http.StatusRequestTimeout: codes.Canceled, + http.StatusBadRequest: codes.InvalidArgument, + http.StatusGatewayTimeout: codes.DeadlineExceeded, + http.StatusNotFound: codes.NotFound, + http.StatusConflict: codes.AlreadyExists, + http.StatusForbidden: codes.PermissionDenied, + http.StatusUnauthorized: codes.Unauthenticated, + http.StatusTooManyRequests: codes.ResourceExhausted, + http.StatusPreconditionFailed: codes.FailedPrecondition, + http.StatusNotImplemented: codes.Unimplemented, + http.StatusInternalServerError: codes.Internal, + http.StatusServiceUnavailable: codes.Unavailable, + } + inverseCodeMap = map[codes.Code]int{} +) + +type Grpc struct { + cli *client.Client + skipAuth bool + timeout time.Duration +} + +func NewGrpc(cli *client.Client, skipAuth bool, timeout time.Duration) Grpc { + return Grpc{ + cli: cli, + skipAuth: skipAuth, + timeout: timeout, + } +} + +func (p Grpc) Handle(ctx *request.Context) error { + body, err := io.ReadAll(ctx.Request().Body) + if err != nil { + return errors.WithMessage(err, "grpc: read body") + } + + md := metadata.MD{ + grpc.ProxyMethodNameHeader: {ctx.Endpoint()}, + grpc.RequestIdHeader: {requestid.FromContext(ctx.Context())}, + } + if !p.skipAuth { + authData, err := ctx.GetAuthData() + if err != nil { + return errors.WithMessage(err, "get auth data") + } + md[grpc.SystemIdHeader] = []string{strconv.Itoa(authData.SystemId)} + md[grpc.DomainIdHeader] = []string{strconv.Itoa(authData.DomainId)} + md[grpc.ServiceIdHeader] = []string{strconv.Itoa(authData.ServiceId)} + md[grpc.ApplicationIdHeader] = []string{strconv.Itoa(authData.ApplicationId)} + if ctx.IsAdminAuthenticated() { + md[xAdminIdHeader] = []string{strconv.Itoa(ctx.AdminId())} + } + } + requestContext := metadata.NewOutgoingContext(ctx.Context(), md) + + requestContext, cancel := context.WithTimeout(requestContext, p.timeout) + defer cancel() + result, err := p.cli.BackendClient().Request(requestContext, &isp.Message{ + Body: &isp.Message_BytesBody{BytesBody: body}, + }) + if err != nil { + return p.handleError(err, ctx.ResponseWriter()) + } + + return p.writeResponse(http.StatusOK, result.GetBytesBody(), ctx.ResponseWriter()) +} + +func (p Grpc) handleError(err error, w http.ResponseWriter) error { + status, ok := status.FromError(err) + if !ok { + return httperrors.New( + http.StatusServiceUnavailable, + "upstream is not available", + errors.WithMessage(err, "grpc proxy"), + ) + } + + statusCode := p.codeToHttpStatus(status.Code()) + for _, detail := range status.Details() { + switch typeOfDetail := detail.(type) { + case *isp.Message: + switch { + case typeOfDetail.GetBytesBody() != nil: + return p.writeResponse(statusCode, typeOfDetail.GetBytesBody(), w) + case typeOfDetail.GetListBody() != nil: + return p.writeProto(statusCode, typeOfDetail.GetListBody(), w) + case typeOfDetail.GetStructBody() != nil: + return p.writeProto(statusCode, typeOfDetail.GetStructBody(), w) + } + default: + return p.writeProto(statusCode, typeOfDetail, w) + } + } + + return httperrors.New( + statusCode, + status.Message(), + status.Err(), + ) +} + +func (p Grpc) writeProto(statusCode int, proto interface{}, w http.ResponseWriter) error { + data, err := json.Marshal(proto) + if err != nil { + return errors.WithMessage(err, "marshal grpc details to json") + } + return p.writeResponse(statusCode, data, w) +} + +func (p Grpc) writeResponse(statusCode int, data []byte, w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(statusCode) + _, err := w.Write(data) + if err != nil { + return errors.WithMessage(err, "response write") + } + return nil +} + +func (p Grpc) codeToHttpStatus(code codes.Code) int { + s, ok := inverseCodeMap[code] + if !ok { + return http.StatusInternalServerError + } + + return s +} diff --git a/proxy/http.go b/proxy/http.go new file mode 100644 index 0000000..5b5a32c --- /dev/null +++ b/proxy/http.go @@ -0,0 +1,115 @@ +package proxy + +import ( + "fmt" + "net" + "net/http" + "net/http/httputil" + "net/url" + "strconv" + "time" + + "isp-gate-service/httperrors" + "isp-gate-service/request" + + "github.com/integration-system/isp-kit/grpc" + "github.com/integration-system/isp-kit/requestid" + "github.com/pkg/errors" + "golang.org/x/net/context" +) + +// nolint:gomnd +var ( + httpTransport = &http.Transport{ + Proxy: http.ProxyFromEnvironment, + DialContext: defaultTransportDialContext(&net.Dialer{ + Timeout: 3 * time.Second, + KeepAlive: 30 * time.Second, + }), + ForceAttemptHTTP2: true, + MaxIdleConns: 512, + MaxIdleConnsPerHost: 32, + IdleConnTimeout: 60 * time.Second, + TLSHandshakeTimeout: 5 * time.Second, + ExpectContinueTimeout: 1 * time.Second, + } +) + +type HttpHostManager interface { + Next() (string, error) +} + +type Http struct { + hostManager HttpHostManager + skipAuth bool + timeout time.Duration +} + +func NewHttp(hostManager HttpHostManager, skipAuth bool, timeout time.Duration) Http { + return Http{ + hostManager: hostManager, + skipAuth: skipAuth, + timeout: timeout, + } +} + +func (p Http) Handle(ctx *request.Context) error { + host, err := p.hostManager.Next() + if err != nil { + return errors.WithMessage(err, "http: next host") + } + + rawUrl := fmt.Sprintf("http://%s", host) // secure HTTP links are reset connection + target, err := url.Parse(rawUrl) + if err != nil { + return errors.WithMessage(err, "http: parse url") + } + + request := ctx.Request() + request.URL.Path = ctx.Endpoint() + err = setHttpHeaders(ctx, request.Header, p.skipAuth) + if err != nil { + return err + } + reverseProxy := httputil.NewSingleHostReverseProxy(target) + reverseProxy.Transport = httpTransport + var resultError error + reverseProxy.ErrorHandler = func(writer http.ResponseWriter, request *http.Request, err error) { + resultError = httperrors.New( + http.StatusServiceUnavailable, + "upstream is not available", + errors.WithMessagef(err, "http proxy to %s", host), + ) + } + + context, cancel := context.WithTimeout(request.Context(), p.timeout) + defer cancel() + request = request.WithContext(context) + reverseProxy.ServeHTTP(ctx.ResponseWriter(), request) + + return resultError +} + +func setHttpHeaders(ctx *request.Context, header http.Header, skipAuth bool) error { + header.Set(grpc.RequestIdHeader, requestid.FromContext(ctx.Context())) + if !skipAuth { + authData, err := ctx.GetAuthData() + if err != nil { + return errors.WithMessage(err, "http: get auth data") + } + header.Set(grpc.SystemIdHeader, strconv.Itoa(authData.SystemId)) + header.Set(grpc.DomainIdHeader, strconv.Itoa(authData.DomainId)) + header.Set(grpc.ServiceIdHeader, strconv.Itoa(authData.ServiceId)) + header.Set(grpc.ApplicationIdHeader, strconv.Itoa(authData.ApplicationId)) + if ctx.IsAdminAuthenticated() { + header.Set(xAdminIdHeader, strconv.Itoa(ctx.AdminId())) + } else { + header.Del(xAdminIdHeader) + } + } + return nil +} + +func defaultTransportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) { + return dialer.DialContext +} diff --git a/proxy/ws.go b/proxy/ws.go new file mode 100644 index 0000000..c822a01 --- /dev/null +++ b/proxy/ws.go @@ -0,0 +1,71 @@ +package proxy + +import ( + "fmt" + "net/http" + "net/url" + "time" + + "github.com/gorilla/websocket" + "github.com/pkg/errors" + "github.com/tomakado/websocketproxy" + "isp-gate-service/httperrors" + "isp-gate-service/request" +) + +type Ws struct { + hostManager HttpHostManager + skipAuth bool +} + +func NewWs(hostManager HttpHostManager, skipAuth bool) Ws { + return Ws{ + hostManager: hostManager, + skipAuth: skipAuth, + } +} + +//nolint:gomnd +func (ws Ws) Handle(ctx *request.Context) error { + host, err := ws.hostManager.Next() + if err != nil { + return errors.WithMessage(err, "ws: next host") + } + + rawUrl := fmt.Sprintf("ws://%s", host) + target, err := url.Parse(rawUrl) + if err != nil { + return errors.WithMessage(err, "ws: parse url") + } + + request := ctx.Request() + request.URL.Path = ctx.Endpoint() + + var resultError error + proxy := websocketproxy.NewProxy(target) + proxy.Director = func(incoming *http.Request, out http.Header) { + _ = setHttpHeaders(ctx, out, ws.skipAuth) + } + proxy.Upgrader = &websocket.Upgrader{ + HandshakeTimeout: 5 * time.Second, + ReadBufferSize: 1024, + WriteBufferSize: 1024, + WriteBufferPool: nil, + Subprotocols: nil, + Error: func(w http.ResponseWriter, r *http.Request, status int, reason error) { + resultError = httperrors.New( + http.StatusServiceUnavailable, + "upstream is not available", + errors.WithMessagef(reason, "ws proxy to %s", host), + ) + }, + CheckOrigin: func(r *http.Request) bool { + return true + }, + EnableCompression: false, + } + + proxy.ServeHTTP(ctx.ResponseWriter(), ctx.Request()) + + return resultError +} diff --git a/repository/admin.go b/repository/admin.go new file mode 100644 index 0000000..231c1e6 --- /dev/null +++ b/repository/admin.go @@ -0,0 +1,47 @@ +package repository + +import ( + "context" + + "isp-gate-service/domain" + + "github.com/integration-system/isp-kit/grpc/client" + "github.com/pkg/errors" +) + +const ( + adminAuthenticate = "admin/secure/authenticate" + adminAuthorize = "admin/secure/authorize" +) + +type Admin struct { + cli *client.Client +} + +func NewAdmin(cli *client.Client) Admin { + return Admin{cli: cli} +} + +func (r Admin) Authenticate(ctx context.Context, token string) (*domain.AdminAuthenticateResponse, error) { + resp := domain.AdminAuthenticateResponse{} + err := r.cli.Invoke(adminAuthenticate). + JsonRequestBody(domain.AuthenticateRequest{Token: token}). + JsonResponseBody(&resp). + Do(ctx) + if err != nil { + return nil, errors.WithMessagef(err, "grpc client invoke %s", adminAuthenticate) + } + return &resp, nil +} + +func (r Admin) Authorize(ctx context.Context, adminId int, permission string) (bool, error) { + resp := domain.AdminAuthorizeResponse{} + err := r.cli.Invoke(adminAuthorize). + JsonRequestBody(domain.AdminAuthorizeRequest{AdminId: adminId, Permission: permission}). + JsonResponseBody(&resp). + Do(ctx) + if err != nil { + return false, errors.WithMessagef(err, "grpc client invoke: %s", adminAuthorize) + } + return resp.Authorized, nil +} diff --git a/repository/authentication_cache.go b/repository/authentication_cache.go new file mode 100644 index 0000000..20b9dca --- /dev/null +++ b/repository/authentication_cache.go @@ -0,0 +1,49 @@ +package repository + +import ( + "context" + "time" + + "github.com/integration-system/isp-kit/json" + "github.com/pkg/errors" + "isp-gate-service/cache" + "isp-gate-service/domain" +) + +type AuthenticationCache struct { + cache *cache.Cache + duration time.Duration +} + +func NewAuthenticationCache(duration time.Duration) AuthenticationCache { + return AuthenticationCache{ + duration: duration, + cache: cache.New(), + } +} + +func (r AuthenticationCache) Get(ctx context.Context, token string) (*domain.AuthData, error) { + data, ok := r.cache.Get(token) + if !ok { + return nil, domain.ErrAuthenticationCacheMiss + } + + result := domain.AuthData{} + err := json.Unmarshal(data, &result) + if err != nil { + return nil, errors.WithMessage(err, "json unmarshal auth data") + } + + return &result, nil +} + +func (r AuthenticationCache) Set(ctx context.Context, token string, data domain.AuthData) error { + value, err := json.Marshal(data) + if err != nil { + return errors.WithMessage(err, "json marshal auth data") + } + + r.cache.Set(token, value, r.duration) + + return nil +} diff --git a/repository/authorization_cache.go b/repository/authorization_cache.go new file mode 100644 index 0000000..8e70c5f --- /dev/null +++ b/repository/authorization_cache.go @@ -0,0 +1,37 @@ +package repository + +import ( + "context" + "fmt" + "time" + + "isp-gate-service/cache" +) + +type AuthorizationCache struct { + duration time.Duration + cache *cache.Cache +} + +func NewAuthorizationCache(duration time.Duration) *AuthorizationCache { + return &AuthorizationCache{ + duration: duration, + cache: cache.New(), + } +} + +func (r AuthorizationCache) Get(ctx context.Context, id int, endpoint string) (bool, error) { + key := r.key(id, endpoint) + _, ok := r.cache.Get(key) + return ok, nil +} + +func (r AuthorizationCache) SetAuthorized(ctx context.Context, id int, endpoint string) error { + key := r.key(id, endpoint) + r.cache.Set(key, nil, r.duration) + return nil +} + +func (r AuthorizationCache) key(id int, endpoint string) string { + return fmt.Sprintf("%d:%s", id, endpoint) +} diff --git a/repository/daily_limit.go b/repository/daily_limit.go new file mode 100644 index 0000000..d3ed75f --- /dev/null +++ b/repository/daily_limit.go @@ -0,0 +1,42 @@ +package repository + +import ( + "context" + "fmt" + "time" + + "github.com/pkg/errors" + "github.com/redis/go-redis/v9" +) + +type DailyLimit struct { + cli redis.UniversalClient +} + +func NewDailyLimit(cli redis.UniversalClient) DailyLimit { + return DailyLimit{ + cli: cli, + } +} + +func (r DailyLimit) Increment(ctx context.Context, applicationId int, today time.Time) (int64, error) { + key := r.key(applicationId, today) + value, err := r.cli.Incr(ctx, key).Result() + if err != nil { + return 0, errors.WithMessage(err, "incr") + } + + if value == 1 { + err := r.cli.ExpireNX(ctx, key, 24*time.Hour).Err() //nolint:gomnd + if err != nil { + return 0, errors.WithMessage(err, "expire nx") + } + } + + return value, nil +} + +func (r DailyLimit) key(applicationId int, today time.Time) string { + y, m, d := today.Date() + return fmt.Sprintf("daily_limit:%d:%d-%d-%d", applicationId, y, m, d) +} diff --git a/repository/system.go b/repository/system.go new file mode 100644 index 0000000..a3ef87c --- /dev/null +++ b/repository/system.go @@ -0,0 +1,48 @@ +package repository + +import ( + "context" + + "github.com/integration-system/isp-kit/grpc/client" + "github.com/pkg/errors" + "isp-gate-service/domain" +) + +const ( + authenticate = "system/secure/authenticate" + authorize = "system/secure/authorize" +) + +type System struct { + cli *client.Client +} + +func NewSystem(cli *client.Client) System { + return System{ + cli: cli, + } +} + +func (r System) Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error) { + resp := domain.AuthenticateResponse{} + err := r.cli.Invoke(authenticate). + JsonRequestBody(domain.AuthenticateRequest{Token: token}). + JsonResponseBody(&resp). + Do(ctx) + if err != nil { + return nil, errors.WithMessagef(err, "grpc client invoke: %s", authenticate) + } + return &resp, nil +} + +func (r System) Authorize(ctx context.Context, applicationId int, endpoint string) (bool, error) { + resp := domain.AuthorizeResponse{} + err := r.cli.Invoke(authorize). + JsonRequestBody(domain.AuthorizeRequest{ApplicationId: applicationId, Endpoint: endpoint}). + JsonResponseBody(&resp). + Do(ctx) + if err != nil { + return false, errors.WithMessagef(err, "grpc client invoke: %s", authorize) + } + return resp.Authorized, nil +} diff --git a/repository/throttling.go b/repository/throttling.go new file mode 100644 index 0000000..8e8aefb --- /dev/null +++ b/repository/throttling.go @@ -0,0 +1,37 @@ +package repository + +import ( + "context" + "fmt" + + "github.com/go-redis/redis_rate/v10" + "github.com/pkg/errors" + "github.com/redis/go-redis/v9" + "isp-gate-service/domain" +) + +type Throttling struct { + cli *redis_rate.Limiter +} + +func NewThrottling(cli redis.UniversalClient) Throttling { + return Throttling{ + cli: redis_rate.NewLimiter(cli), + } +} + +func (r Throttling) IsAllowRequestPerSecond(ctx context.Context, applicationId int, rate int) (*domain.RateLimitResult, error) { + result, err := r.cli.Allow(ctx, r.key(applicationId), redis_rate.PerSecond(rate)) + if err != nil { + return nil, errors.WithMessage(err, "redis_rate/Allow") + } + return &domain.RateLimitResult{ + Allow: result.Allowed > 0, + Remaining: result.Remaining, + RetryAfter: result.RetryAfter, + }, nil +} + +func (r Throttling) key(applicationId int) string { + return fmt.Sprintf("throttling:%d", applicationId) +} diff --git a/repository/unused/redis_auth_cache.go b/repository/unused/redis_auth_cache.go new file mode 100644 index 0000000..aa58355 --- /dev/null +++ b/repository/unused/redis_auth_cache.go @@ -0,0 +1,75 @@ +package unused + +import ( + "context" + "time" + + "github.com/integration-system/isp-kit/json" + "github.com/pkg/errors" + "github.com/redis/go-redis/v9" + "isp-gate-service/domain" +) + +type RedisAuthCache struct { + cli redis.UniversalClient + duration time.Duration + db int +} + +func NewRedisAuthCache(cli redis.UniversalClient, duration time.Duration, db int) RedisAuthCache { + return RedisAuthCache{ + cli: cli, + duration: duration, + db: db, + } +} + +func (r RedisAuthCache) Get(ctx context.Context, token string) (*domain.AuthData, error) { + results, err := r.cli.Pipelined(ctx, func(p redis.Pipeliner) error { + p.Select(ctx, r.db) + p.Get(ctx, token) + return nil + }) + if err != nil && err != redis.Nil { + return nil, errors.WithMessage(err, "pipelined") + } + + data, err := results[1].(*redis.StringCmd).Result() + if errors.Is(err, redis.Nil) { + return nil, domain.ErrAuthenticationCacheMiss + } + if err != nil { + return nil, errors.WithMessage(err, "get") + } + + result := domain.AuthData{} + err = json.Unmarshal([]byte(data), &result) + if err != nil { + return nil, errors.WithMessage(err, "json unmarshal auth data") + } + + return &result, nil +} + +func (r RedisAuthCache) Set(ctx context.Context, token string, data domain.AuthData) error { + value, err := json.Marshal(data) + if err != nil { + return errors.WithMessage(err, "json marshal auth data") + } + + results, err := r.cli.Pipelined(ctx, func(p redis.Pipeliner) error { + p.Select(ctx, r.db) + p.SetEx(ctx, token, string(value), r.duration) + return nil + }) + if err != nil { + return errors.WithMessage(err, "pipelined") + } + + err = results[1].Err() + if err != nil { + return errors.WithMessage(err, "set ex") + } + + return nil +} diff --git a/repository/unused/redis_authz_cache.go b/repository/unused/redis_authz_cache.go new file mode 100644 index 0000000..b9167ba --- /dev/null +++ b/repository/unused/redis_authz_cache.go @@ -0,0 +1,66 @@ +package unused + +import ( + "context" + "fmt" + "time" + + "github.com/pkg/errors" + "github.com/redis/go-redis/v9" +) + +type RedisAuthzCache struct { + cli redis.UniversalClient + duration time.Duration + db int +} + +func NewRedisAuthzCache(cli redis.UniversalClient, duration time.Duration, db int) *RedisAuthzCache { + return &RedisAuthzCache{ + cli: cli, + duration: duration, + db: db, + } +} + +func (r RedisAuthzCache) Get(ctx context.Context, applicationId int, endpoint string) (bool, error) { + result, err := r.cli.Pipelined(ctx, func(p redis.Pipeliner) error { + p.Select(ctx, r.db) + p.Get(ctx, r.key(applicationId, endpoint)) + return nil + }) + if err != nil && err != redis.Nil { + return false, errors.WithMessage(err, "pipelined") + } + + _, err = result[1].(*redis.StringCmd).Result() + if errors.Is(err, redis.Nil) { + return false, nil + } + if err != nil { + return false, errors.WithMessage(err, "get") + } + return true, nil +} + +func (r RedisAuthzCache) SetAuthorized(ctx context.Context, applicationId int, endpoint string) error { + result, err := r.cli.Pipelined(ctx, func(p redis.Pipeliner) error { + p.Select(ctx, r.db) + p.SetEx(ctx, r.key(applicationId, endpoint), "authorized", r.duration) + return nil + }) + if err != nil { + return errors.WithMessage(err, "pipelined") + } + + err = result[1].Err() + if err != nil { + return errors.WithMessage(err, "set ex") + } + + return nil +} + +func (r RedisAuthzCache) key(applicationId int, endpoint string) string { + return fmt.Sprintf("%d:%s", applicationId, endpoint) +} diff --git a/request/context.go b/request/context.go new file mode 100644 index 0000000..ede23ce --- /dev/null +++ b/request/context.go @@ -0,0 +1,119 @@ +package request + +import ( + "context" + "net/http" + "strings" + + "github.com/pkg/errors" +) + +var ( + ErrNotAuthenticated = errors.New("not authenticated") +) + +type AuthData struct { + SystemId int + DomainId int + ServiceId int + ApplicationId int +} + +type Context struct { + request *http.Request + responseWriter http.ResponseWriter + + endpoint string + + authenticated bool + authData *AuthData + + adminAuthenticated bool + adminId int + adminToken string + + queryParams map[string]string +} + +func NewContext(request *http.Request, response http.ResponseWriter, endpoint string) *Context { + return &Context{ + request: request, + responseWriter: response, + endpoint: endpoint, + } +} + +func (c *Context) Request() *http.Request { + return c.request +} + +func (c *Context) ResponseWriter() http.ResponseWriter { + return c.responseWriter +} + +func (c *Context) SetResponseWriter(writer http.ResponseWriter) { + c.responseWriter = writer +} + +func (c *Context) Endpoint() string { + return c.endpoint +} + +func (c *Context) Authenticate(authData AuthData) { + c.authenticated = true + c.authData = &authData +} + +func (c *Context) GetAuthData() (AuthData, error) { + if !c.authenticated { + return AuthData{}, ErrNotAuthenticated + } + return *c.authData, nil +} + +func (c *Context) IsAdminAuthenticated() bool { + return c.adminAuthenticated +} + +func (c *Context) AdminId() int { + return c.adminId +} + +func (c *Context) AdminToken() string { + return c.adminToken +} + +func (c *Context) AuthenticateAdmin(adminId int, adminToken string) { + c.adminAuthenticated = true + c.adminId = adminId + c.adminToken = adminToken +} + +func (c *Context) Context() context.Context { + return c.request.Context() +} + +func (c *Context) SetContext(ctx context.Context) { + c.request = c.request.WithContext(ctx) +} + +func (c *Context) Param(name string) string { + value := c.request.Header.Get(name) + if value != "" { + return strings.TrimSpace(value) + } + + if c.queryParams == nil { + query := c.request.URL.Query() + c.queryParams = map[string]string{} + for key, values := range query { + if len(values) == 0 { + continue + } + c.queryParams[strings.ToLower(key)] = values[0] + } + } + value = c.queryParams[strings.ToLower(name)] + + return strings.TrimSpace(value) +} diff --git a/routes/routes.go b/routes/routes.go new file mode 100644 index 0000000..809f36f --- /dev/null +++ b/routes/routes.go @@ -0,0 +1,49 @@ +package routes + +import ( + "context" + + "github.com/integration-system/isp-kit/cluster" +) + +type Routes struct { + innerEndpoints map[string]bool + requiredPermissions map[string]string +} + +func NewRoutes() *Routes { + return &Routes{ + innerEndpoints: make(map[string]bool), + requiredPermissions: make(map[string]string), + } +} + +func (s *Routes) ReceiveRoutes(ctx context.Context, routes cluster.RoutingConfig) error { + newInnerMethods := make(map[string]bool) + newRequiredPermissions := make(map[string]string) + for _, backend := range routes { + for _, v := range backend.Endpoints { + if v.Inner { + newInnerMethods[v.Path] = true + } + perm, ok := cluster.GetRequiredAdminPermission(v) + if ok { + newRequiredPermissions[v.Path] = perm + } + } + } + + s.innerEndpoints = newInnerMethods + s.requiredPermissions = newRequiredPermissions + + return nil +} + +func (s *Routes) IsInnerEndpoint(path string) bool { + return s.innerEndpoints[path] +} + +func (s *Routes) RequiredAdminPermission(path string) (string, bool) { + perm, ok := s.requiredPermissions[path] + return perm, ok +} diff --git a/service/admin.go b/service/admin.go new file mode 100644 index 0000000..9330613 --- /dev/null +++ b/service/admin.go @@ -0,0 +1,57 @@ +package service + +import ( + "context" + + "isp-gate-service/domain" + + "github.com/pkg/errors" +) + +type AdminAuth interface { + Authenticate(ctx context.Context, token string) (*domain.AdminAuthenticateResponse, error) + Authorize(ctx context.Context, adminId int, permission string) (bool, error) +} + +type Admin struct { + cache AuthorizationCache + repo AdminAuth +} + +func NewAdmin(cache AuthorizationCache, adminAuth AdminAuth) Admin { + return Admin{ + cache: cache, + repo: adminAuth, + } +} + +func (s Admin) AdminAuthenticate(ctx context.Context, token string) (*domain.AdminAuthenticateResponse, error) { + resp, err := s.repo.Authenticate(ctx, token) + if err != nil { + return nil, errors.WithMessage(err, "get admin token data from admin service") + } + return resp, nil +} + +func (s Admin) AdminAuthorize(ctx context.Context, adminId int, permission string) (bool, error) { + ok, err := s.cache.Get(ctx, adminId, permission) + if err != nil { + return false, errors.WithMessage(err, "authz cache get") + } + if ok { + return ok, nil + } + + ok, err = s.repo.Authorize(ctx, adminId, permission) + if err != nil { + return false, errors.WithMessagef(err, "authz repo authorize") + } + if ok { + err = s.cache.SetAuthorized(ctx, adminId, permission) + if err != nil { + return false, errors.WithMessagef(err, "authz cache set") + } + } + + return ok, nil +} diff --git a/service/authentication.go b/service/authentication.go new file mode 100644 index 0000000..b217f63 --- /dev/null +++ b/service/authentication.go @@ -0,0 +1,55 @@ +package service + +import ( + "context" + + "github.com/pkg/errors" + "isp-gate-service/domain" +) + +type AuthenticationCache interface { + Get(ctx context.Context, token string) (*domain.AuthData, error) + Set(ctx context.Context, token string, data domain.AuthData) error +} + +type AuthenticationRepo interface { + Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error) +} + +type Auth struct { + cache AuthenticationCache + repo AuthenticationRepo +} + +func NewAuthentication(cache AuthenticationCache, repo AuthenticationRepo) Auth { + return Auth{ + cache: cache, + repo: repo, + } +} + +func (s Auth) Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error) { + authData, err := s.cache.Get(ctx, token) + if errors.Is(err, domain.ErrAuthenticationCacheMiss) { + resp, err := s.repo.Authenticate(ctx, token) + if err != nil { + return nil, errors.WithMessage(err, "auth repo authenticate") + } + if !resp.Authenticated { + return resp, nil + } + err = s.cache.Set(ctx, token, *resp.AuthData) + if err != nil { + return nil, errors.WithMessage(err, "auth cache set") + } + return resp, nil + } + if err != nil { + return nil, errors.WithMessage(err, "auth cache get") + } + return &domain.AuthenticateResponse{ + Authenticated: true, + ErrorReason: "", + AuthData: authData, + }, nil +} diff --git a/service/authorization.go b/service/authorization.go new file mode 100644 index 0000000..29b296f --- /dev/null +++ b/service/authorization.go @@ -0,0 +1,51 @@ +package service + +import ( + "context" + + "github.com/pkg/errors" +) + +type AuthorizationCache interface { + Get(ctx context.Context, applicationId int, endpoint string) (bool, error) + SetAuthorized(ctx context.Context, applicationId int, endpoint string) error +} + +type AuthorizationRepo interface { + Authorize(ctx context.Context, applicationId int, endpoint string) (bool, error) +} + +type Authorization struct { + cache AuthorizationCache + repo AuthorizationRepo +} + +func NewAuthorization(cache AuthorizationCache, repo AuthorizationRepo) Authorization { + return Authorization{ + cache: cache, + repo: repo, + } +} + +func (s Authorization) Authorize(ctx context.Context, applicationId int, endpoint string) (bool, error) { + ok, err := s.cache.Get(ctx, applicationId, endpoint) + if err != nil { + return false, errors.WithMessage(err, "authz cache get") + } + if ok { + return ok, nil + } + + ok, err = s.repo.Authorize(ctx, applicationId, endpoint) + if err != nil { + return false, errors.WithMessagef(err, "authz repo authorize") + } + if ok { + err = s.cache.SetAuthorized(ctx, applicationId, endpoint) + if err != nil { + return false, errors.WithMessagef(err, "authz cache set") + } + } + + return ok, nil +} diff --git a/service/daily_limit.go b/service/daily_limit.go new file mode 100644 index 0000000..e7f058b --- /dev/null +++ b/service/daily_limit.go @@ -0,0 +1,43 @@ +package service + +import ( + "context" + "time" + + "github.com/pkg/errors" + "isp-gate-service/conf" +) + +type DailyLimitRepo interface { + Increment(ctx context.Context, applicationId int, today time.Time) (int64, error) +} + +type DailyLimit struct { + repo DailyLimitRepo + limits map[int]int64 +} + +func NewDailyLimit(repo DailyLimitRepo, configs []conf.DailyLimit) DailyLimit { + limits := make(map[int]int64) + for _, config := range configs { + limits[config.ApplicationId] = config.RequestsPerDay + } + return DailyLimit{ + repo: repo, + limits: limits, + } +} + +func (s DailyLimit) IncrementAndCheck(ctx context.Context, applicationId int) (bool, error) { + max, ok := s.limits[applicationId] + if !ok { + return true, nil + } + + newValue, err := s.repo.Increment(ctx, applicationId, time.Now()) + if err != nil { + return false, errors.WithMessage(err, "increment") + } + + return newValue <= max, nil +} diff --git a/service/throttling.go b/service/throttling.go new file mode 100644 index 0000000..6e586be --- /dev/null +++ b/service/throttling.go @@ -0,0 +1,47 @@ +package service + +import ( + "context" + + "github.com/pkg/errors" + "isp-gate-service/conf" + "isp-gate-service/domain" +) + +type ThrottlingRepo interface { + IsAllowRequestPerSecond(ctx context.Context, applicationId int, rate int) (*domain.RateLimitResult, error) +} + +type Throttling struct { + repo ThrottlingRepo + limits map[int]int +} + +func NewThrottling(repo ThrottlingRepo, configs []conf.Throttling) Throttling { + limits := make(map[int]int) + for _, config := range configs { + limits[config.ApplicationId] = config.RequestsPerSeconds + } + return Throttling{ + repo: repo, + limits: limits, + } +} + +func (s Throttling) AllowRateLimit(ctx context.Context, applicationId int) (*domain.RateLimitResult, error) { + rate, ok := s.limits[applicationId] + if !ok { + return &domain.RateLimitResult{ + Allow: true, + Remaining: -1, + RetryAfter: -1, + }, nil + } + + result, err := s.repo.IsAllowRequestPerSecond(ctx, applicationId, rate) + if err != nil { + return nil, errors.WithMessage(err, "is allow request per second") + } + + return result, nil +} diff --git a/tests/acceptance_test.go b/tests/acceptance_test.go new file mode 100644 index 0000000..c16da81 --- /dev/null +++ b/tests/acceptance_test.go @@ -0,0 +1,348 @@ +package tests + +import ( + "context" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "testing" + + etp "github.com/integration-system/isp-etp-go/v2" + etpcli "github.com/integration-system/isp-etp-go/v2/client" + "github.com/integration-system/isp-kit/cluster" + "github.com/integration-system/isp-kit/http/httpcli" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" + "isp-gate-service/assembly" + "isp-gate-service/conf" + "isp-gate-service/domain" + "isp-gate-service/routes" + + "github.com/google/uuid" + "github.com/integration-system/isp-kit/grpc" + "github.com/integration-system/isp-kit/grpc/client" + "github.com/integration-system/isp-kit/lb" + "github.com/integration-system/isp-kit/log" + "github.com/integration-system/isp-kit/requestid" + "github.com/integration-system/isp-kit/test" + "github.com/integration-system/isp-kit/test/grpct" + "github.com/integration-system/isp-kit/test/httpt" + "github.com/stretchr/testify/suite" + "google.golang.org/grpc/metadata" +) + +type request struct { + Id string +} + +type response struct { + Id string +} + +type HappyPathTestSuite struct { + suite.Suite +} + +func (s *HappyPathTestSuite) TestGrpcProxy() { + test, require := test.New(s.T()) + config, redisCli, systemCli, adminCli := s.commonDependencies(test) + + requestId := requestid.Next() + targetService, targetCli := grpct.NewMock(test) + targetService.Mock("endpoint", func(ctx context.Context, authData grpc.AuthData, req request) response { + systemId, err := authData.SystemId() + require.NoError(err) + domainId, err := authData.DomainId() + require.NoError(err) + serviceId, err := authData.ServiceId() + require.NoError(err) + applicationId, err := authData.ApplicationId() + require.NoError(err) + require.EqualValues(requestId, requestid.FromContext(ctx)) + require.EqualValues(1, systemId) + require.EqualValues(2, domainId) + require.EqualValues(3, serviceId) + require.EqualValues(4, applicationId) + + adminId, err := grpc.StringFromMd("x-admin-id", metadata.MD(authData)) + require.NoError(err) + require.EqualValues("1", adminId) + + return response{Id: req.Id} //nolint:gosimple + }) + targetClients := map[string]*client.Client{"target": targetCli} + logger, err := log.New(log.WithLevel(log.DebugLevel)) + require.NoError(err) + locator := assembly.NewLocator(logger, targetClients, nil, routes.NewRoutes(), systemCli, adminCli) + + locations := []conf.Location{{ + SkipAuth: false, + PathPrefix: "/api", + Protocol: "grpc", + TargetModule: "target", + }} + handler, err := locator.Handler(config, locations, redisCli) + require.NoError(err) + + srv := httptest.NewServer(handler) + cli := httpcli.New() + req := request{Id: uuid.New().String()} + resp := response{} + _, err = cli.Post(srv.URL+"/api/endpoint"). + Header("x-application-token", "token"). + Header("x-request-id", requestId). + Header("x-auth-admin", "mock-token"). + JsonRequestBody(req). + JsonResponseBody(&resp). + StatusCodeToError(). + Do(context.Background()) + require.NoError(err) + require.EqualValues(req.Id, resp.Id) +} + +func (s *HappyPathTestSuite) TestHttpProxy() { + test, require := test.New(s.T()) + config, redisCli, systemCli, adminCli := s.commonDependencies(test) + + requestId := requestid.Next() + targetService := httpt.NewMock(test) + targetService.POST("/endpoint", func(ctx context.Context, httpReq *http.Request, req request) response { + assertHeaders(require, requestId, ctx, httpReq.Header) + return response{Id: req.Id} //nolint:gosimple + }) + targetUrl, err := url.Parse(targetService.BaseURL()) + require.NoError(err) + rr := lb.NewRoundRobin([]string{targetUrl.Host}) + targetClients := map[string]*lb.RoundRobin{"target": rr} + locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes.NewRoutes(), systemCli, adminCli) + locations := []conf.Location{{ + SkipAuth: false, + PathPrefix: "/api", + Protocol: "http", + TargetModule: "target", + }} + handler, err := locator.Handler(config, locations, redisCli) + require.NoError(err) + + srv := httptest.NewServer(handler) + cli := httpcli.New() + req := request{Id: uuid.New().String()} + resp := response{} + _, err = cli.Post(srv.URL+"/api/endpoint"). + Header("x-application-token", "token"). + Header("x-request-id", requestId). + Header("x-auth-admin", "mock-token"). + JsonRequestBody(req). + JsonResponseBody(&resp). + StatusCodeToError(). + Do(context.Background()) + require.NoError(err) + require.EqualValues(req.Id, resp.Id) +} + +func (s *HappyPathTestSuite) TestWsProxy() { // nolint: funlen + test, require := test.New(s.T()) + config, redisCli, systemCli, adminCli := s.commonDependencies(test) + + requestId := requestid.Next() + wsServer := etp.NewServer(context.Background(), etp.ServerConfig{ + ConnectionReadLimit: 2048, + InsecureSkipVerify: true, + }) + wsServer.OnWithAck("hello", func(conn etp.Conn, data []byte) []byte { + headers := conn.RemoteHeader() + ctx := requestid.ToContext(context.Background(), headers.Get("x-request-id")) + assertHeaders(require, requestId, ctx, headers) + require.EqualValues("data", string(data)) + return []byte("world") + }) + wsMux := http.NewServeMux() + wsMux.Handle("/service", http.HandlerFunc(func(writer http.ResponseWriter, r *http.Request) { + wsServer.ServeHttp(writer, r) + })) + targetService := httptest.NewServer(wsMux) + targetUrl, err := url.Parse(targetService.URL) + require.NoError(err) + rr := lb.NewRoundRobin([]string{targetUrl.Host}) + targetClients := map[string]*lb.RoundRobin{"target": rr} + locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes.NewRoutes(), systemCli, adminCli) + locations := []conf.Location{{ + SkipAuth: false, + PathPrefix: "/ws", + Protocol: "ws", + TargetModule: "target", + }} + handler, err := locator.Handler(config, locations, redisCli) + require.NoError(err) + srv := httptest.NewServer(handler) + + cli := etpcli.NewClient(etpcli.Config{ + HttpHeaders: map[string][]string{ + "x-request-id": {requestId}, + }, + }) + + requestUrl, err := url.Parse(srv.URL) + require.NoError(err) + requestUrl.Path = "ws/service" + requestUrl.RawQuery = url.Values{ + "x-application-token": []string{"token"}, + "x-auth-admin": []string{"mock-token"}, + }.Encode() + err = cli.Dial(context.Background(), requestUrl.String()) + require.NoError(err) + resp, err := cli.EmitWithAck(context.Background(), "hello", []byte("data")) + require.NoError(err) + require.EqualValues("world", string(resp)) + err = cli.Close() + require.NoError(err) +} + +func (s *HappyPathTestSuite) TestAdminAuthorization() { + test, require := test.New(s.T()) + config, redisCli, systemCli, adminCli := s.commonDependencies(test) + + targetService, targetCli := grpct.NewMock(test) + targetService.Mock("endpoint", func(ctx context.Context, authData grpc.AuthData, req request) response { + return response{Id: req.Id} //nolint:gosimple + }) + targetClients := map[string]*client.Client{"target": targetCli} + logger, err := log.New(log.WithLevel(log.DebugLevel)) + require.NoError(err) + routes := routes.NewRoutes() + locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli) + + locations := []conf.Location{{ + SkipAuth: false, + PathPrefix: "/api", + Protocol: "grpc", + TargetModule: "target", + }} + handler, err := locator.Handler(config, locations, redisCli) + require.NoError(err) + + err = routes.ReceiveRoutes(context.Background(), cluster.RoutingConfig{{ + ModuleName: "target", + Endpoints: []cluster.EndpointDescriptor{{ + Path: "endpoint", + Inner: true, + Extra: cluster.RequireAdminPermission("ok_permission"), + }, { + Path: "failed_endpoint", + Inner: true, + Extra: cluster.RequireAdminPermission("failed_permission"), + }}, + }}) + require.NoError(err) + + srv := httptest.NewServer(handler) + cli := httpcli.New() + req := request{Id: uuid.New().String()} + resp := response{} + _, err = cli.Post(srv.URL+"/api/endpoint"). + Header("x-application-token", "token"). + Header("x-auth-admin", "mock-token"). + JsonRequestBody(req). + JsonResponseBody(&resp). + StatusCodeToError(). + Do(context.Background()) + require.NoError(err) + require.EqualValues(req.Id, resp.Id) + + _, err = cli.Post(srv.URL+"/api/failed_endpoint"). + Header("x-application-token", "token"). + Header("x-auth-admin", "mock-token"). + JsonRequestBody(req). + JsonResponseBody(&resp). + StatusCodeToError(). + Do(context.Background()) + errResp := httpcli.ErrorResponse{} + require.ErrorAs(err, &errResp) + require.EqualValues(http.StatusForbidden, errResp.StatusCode) +} + +func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, redis.UniversalClient, *client.Client, *client.Client) { + require := test.Assert() + redisCli := NewRedis(test) + ctx := context.Background() + + s.T().Cleanup(func() { + _, err := redisCli.Pipelined(ctx, func(p redis.Pipeliner) error { + p.Select(ctx, 0) + p.FlushDB(ctx) + p.Select(ctx, 1) + p.FlushDB(ctx) + p.Select(ctx, 2) + p.FlushDB(ctx) + return nil + }) + require.NoError(err) + }) + + config := conf.Remote{ + Redis: &conf.Redis{Address: redisCli.address}, + Http: conf.Http{MaxRequestBodySizeInMb: 1, ProxyTimeoutInSec: 15}, + Logging: conf.Logging{LogLevel: log.DebugLevel, RequestLogEnable: true, BodyLogEnable: true, + SkipBodyLoggingEndpointPrefixes: []string{"endpoint"}}, + Caching: conf.Caching{AuthorizationDataInSec: 1, AuthenticationDataInSec: 1}, + DailyLimits: []conf.DailyLimit{{ApplicationId: 1, RequestsPerDay: 100}}, + Throttling: []conf.Throttling{{ApplicationId: 1, RequestsPerSeconds: 100}}, + } + + systemService, systemCli := grpct.NewMock(test) + systemService.Mock("system/secure/authenticate", func() domain.AuthenticateResponse { + return domain.AuthenticateResponse{ + Authenticated: true, + ErrorReason: "", + AuthData: &domain.AuthData{ + SystemId: 1, + DomainId: 2, + ServiceId: 3, + ApplicationId: 4, + }, + } + }).Mock("system/secure/authorize", func() domain.AuthorizeResponse { + return domain.AuthorizeResponse{Authorized: true} + }) + + adminService, adminCli := grpct.NewMock(test) + adminService.Mock("admin/secure/authenticate", func(req domain.AdminAuthorizeRequest) domain.AdminAuthenticateResponse { + return domain.AdminAuthenticateResponse{ + Authenticated: true, + ErrorReason: "", + AdminId: 1, + } + }).Mock("admin/secure/authorize", func(req domain.AdminAuthorizeRequest) domain.AdminAuthorizeResponse { + if req.Permission == "ok_permission" { + return domain.AdminAuthorizeResponse{Authorized: true} + } + return domain.AdminAuthorizeResponse{Authorized: false} + }) + + return config, redisCli, systemCli, adminCli +} + +func TestHappyPathTestSuite(t *testing.T) { + suite.Run(t, new(HappyPathTestSuite)) +} + +func assertHeaders(require *require.Assertions, requestId string, ctx context.Context, headers http.Header) { + systemId, err := strconv.Atoi(headers.Get("x-system-identity")) + require.NoError(err) + domainId, err := strconv.Atoi(headers.Get("x-domain-identity")) + require.NoError(err) + serviceId, err := strconv.Atoi(headers.Get("x-service-identity")) + require.NoError(err) + applicationId, err := strconv.Atoi(headers.Get("x-application-identity")) + require.NoError(err) + require.EqualValues(requestId, requestid.FromContext(ctx)) + require.EqualValues(1, systemId) + require.EqualValues(2, domainId) + require.EqualValues(3, serviceId) + require.EqualValues(4, applicationId) + + adminId, err := strconv.Atoi(headers.Get("x-admin-id")) + require.NoError(err) + require.EqualValues(1, adminId) +} diff --git a/tests/bench/bench.go b/tests/bench/bench.go new file mode 100644 index 0000000..dabd1a5 --- /dev/null +++ b/tests/bench/bench.go @@ -0,0 +1,143 @@ +package main + +import ( + "context" + "net" + "net/http" + + "github.com/redis/go-redis/v9" + "isp-gate-service/assembly" + "isp-gate-service/conf" + "isp-gate-service/domain" + "isp-gate-service/routes" + + "github.com/integration-system/isp-kit/grpc" + "github.com/integration-system/isp-kit/grpc/client" + endpoint2 "github.com/integration-system/isp-kit/grpc/endpoint" + "github.com/integration-system/isp-kit/grpc/isp" + "github.com/integration-system/isp-kit/log" +) + +type request struct { + Id string +} + +type response struct { + Id string +} + +// nolint +func main() { + redisCli := redis.NewClient(&redis.Options{}) + ctx := context.Background() + logger, err := log.New() + if err != nil { + panic(err) + } + defer func() { + _, _ = redisCli.Pipelined(ctx, func(p redis.Pipeliner) error { + p.Select(ctx, 0) + p.FlushDB(ctx) + p.Select(ctx, 1) + p.FlushDB(ctx) + p.Select(ctx, 2) + p.FlushDB(ctx) + return nil + }) + }() + config := conf.Remote{ + Redis: &conf.Redis{Address: "localhost:6379"}, + Http: conf.Http{MaxRequestBodySizeInMb: 1, ProxyTimeoutInSec: 15}, + Logging: conf.Logging{LogLevel: log.DebugLevel, RequestLogEnable: true, BodyLogEnable: true}, + Caching: conf.Caching{AuthorizationDataInSec: 15, AuthenticationDataInSec: 15}, + DailyLimits: []conf.DailyLimit{{ApplicationId: 1, RequestsPerDay: 100000000}}, + Throttling: []conf.Throttling{{ApplicationId: 1, RequestsPerSeconds: 5000}}, + } + + systemService, systemCli, _ := NewMock(logger) + systemService.Mock("system/secure/authenticate", func() domain.AuthenticateResponse { + return domain.AuthenticateResponse{ + Authenticated: true, + ErrorReason: "", + AuthData: &domain.AuthData{ + SystemId: 1, + DomainId: 1, + ServiceId: 1, + ApplicationId: 1, + }, + } + }).Mock("system/secure/authorize", func() domain.AuthorizeResponse { + return domain.AuthorizeResponse{Authorized: true} + }) + + adminService, _, adminCli := NewMock(logger) + adminService.Mock("admin/secure/authenticate", func() domain.AdminAuthenticateResponse { + return domain.AdminAuthenticateResponse{ + Authenticated: true, + ErrorReason: "", + AdminId: 1, + } + }) + + targetService, targetCli, _ := NewMock(logger) + targetService.Mock("endpoint", func(req request) response { + return response{Id: req.Id} + }) + targetClients := map[string]*client.Client{"target": targetCli} + logger, _ = log.New(log.WithLevel(log.DebugLevel)) + locator := assembly.NewLocator(logger, targetClients, nil, routes.NewRoutes(), systemCli, adminCli) + locations := []conf.Location{{ + SkipAuth: false, + PathPrefix: "/api", + Protocol: "grpc", + TargetModule: "target", + }} + handler, _ := locator.Handler(config, locations, redisCli) + + srv := &http.Server{ + Addr: "localhost:8000", + Handler: handler, + } + srv.ListenAndServe() +} + +func TestServer(service isp.BackendServiceServer) (*grpc.Server, *client.Client, *client.Client) { + listener, _ := net.Listen("tcp", "127.0.0.1:") + srv := grpc.NewServer() + sysCli, _ := client.Default() + adminCli, _ := client.Default() + srv.Upgrade(service) + go func() { + _ = srv.Serve(listener) + }() + + sysCli.Upgrade([]string{listener.Addr().String()}) + adminCli.Upgrade([]string{listener.Addr().String()}) + return srv, sysCli, adminCli +} + +type MockServer struct { + srv *grpc.Server + logger log.Logger + mockEndpoints map[string]interface{} +} + +func NewMock(logger log.Logger) (*MockServer, *client.Client, *client.Client) { + srv, syscli, admincli := TestServer(grpc.NewMux()) + return &MockServer{ + srv: srv, + logger: logger, + mockEndpoints: make(map[string]interface{}), + }, syscli, admincli +} + +func (m *MockServer) Mock(endpoint string, handler interface{}) *MockServer { + m.mockEndpoints[endpoint] = handler + wrapper := endpoint2.DefaultWrapper(m.logger) + muxer := grpc.NewMux() + for e, handler := range m.mockEndpoints { + muxer.Handle(e, wrapper.Endpoint(handler)) + } + m.srv.Upgrade(muxer) + return m +} diff --git a/tests/bench/body.json b/tests/bench/body.json new file mode 100644 index 0000000..fe45c5c --- /dev/null +++ b/tests/bench/body.json @@ -0,0 +1,3 @@ +{ + "id": "GO4IIZW5uav4cSo2zyR6i41LdalKytNH628yDhC92jXQF07gu4LS75JuzQgc6d3Dly48fwla9iHK6LPTJcvFbOcklXp7Zr9g3b180s0H3dVgaYGcO8BrAFxMVb2KcHyu" +} diff --git a/tests/bench/run.sh b/tests/bench/run.sh new file mode 100644 index 0000000..baec1f7 --- /dev/null +++ b/tests/bench/run.sh @@ -0,0 +1,2 @@ +bombardier -c 128 -t 1s -d 60s --fasthttp -H "x-application-token: token" -m POST -f body.json http://localhost:8000/api/endpoint + diff --git a/tests/redis.go b/tests/redis.go new file mode 100644 index 0000000..47f813e --- /dev/null +++ b/tests/redis.go @@ -0,0 +1,25 @@ +package tests + +import ( + "fmt" + + "github.com/integration-system/isp-kit/test" + "github.com/redis/go-redis/v9" +) + +type Redis struct { + address string + redis.UniversalClient +} + +func NewRedis(test *test.Test) Redis { + redisHost := test.Config().Optional().String("REDIS_HOST", "localhost") + redisPort := test.Config().Optional().String("REDIS_PORT", "6379") + addr := fmt.Sprintf("%s:%s", redisHost, redisPort) + cli := redis.NewClient(&redis.Options{Addr: addr}) + return Redis{UniversalClient: cli, address: addr} +} + +func (r Redis) Address() string { + return r.address +}