Compare commits

..
30 Commits
Author SHA1 Message Date
txix 2f88738f78 2026-01-23 12:57:58: merge [main:4f90477e73bbbbbfe9cdb168b87e0ea201679912];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-01-23 12:57:58 +03:00
txix a637d56ea7 2026-01-14 11:52:30: merge [main:1a274e79e588612933ce36c33b236a91fc74db9a];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-01-14 11:52:30 +03:00
txix a841cd082b 2025-12-26 09:37:14: merge [main:2b5ee66527f48ea4e6111148c0ba3c23611d6772];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-12-26 09:37:14 +03:00
txix 9b18fe7351 2025-11-26 13:43:01: merge [main:e9c5c9b80517122ca122933c111070bf470e31c1];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-11-26 13:43:01 +03:00
txix f3c801e4a4 2025-11-26 10:05:59: merge [main:96f8e79d3384c01bf52552f94afdf4ed662997e5];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-11-26 10:05:59 +03:00
txix ee13991d87 2025-10-03 15:15:07: merge [main:c3e3ed9636c6987e89feaf39503dda74462fcfde];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-10-03 15:15:07 +03:00
txix d4846359e4 2025-10-02 16:02:08: merge [main:13db082fcac220b28433a207845ceb3bef8bd07d];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-10-02 16:02:08 +03:00
txix 13cf0075f6 2025-09-17 18:07:26: merge [main:f5bfe7d2ba0d7a2f391f4ffaff6fffc1686ba3c7];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-09-17 18:07:26 +03:00
txix 135e551473 2025-08-21 15:04:13: merge [main:a4b6e5fd1d9685c751c5988518e9f8dd62a8e519]; 2025-08-21 15:04:13 +03:00
txix 689f730a3e 2025-07-09 12:35:19: merge [main:9f485b5e57937029be52e58137ef79ad5c3ca524];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-07-09 12:35:19 +03:00
txix a30582fa38 2025-07-03 12:26:31: merge [main:66e6c4b9c432b19b644d033703545d38aba3b847];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-07-03 12:26:31 +03:00
txix 5b1ce14467 2025-07-01 16:40:11: merge [main:61f11c0bda72fe35f473f8302edfaf86f151c0ad];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-07-01 16:40:11 +03:00
txix 264b438cdb 2025-07-01 13:32:55: merge [main:6491e79afd06cd665731c89f8ab2cd373351c1b4]; 2025-07-01 13:32:55 +03:00
txix f699aefa58 2025-05-27 14:32:05: merge [master:01f8dcdc36fb3f9867a65ffb7379ad25c85cd988];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-05-27 14:32:05 +03:00
txix 8d40e76637 2025-05-13 13:05:46: merge [master:49d1bfaa3f027c5465de7a0c0d46a9bab0588e19]; 2025-05-13 13:05:46 +03:00
txix e2b4becfd6 2025-04-29 14:57:30: merge [master:357ce03935a551e8be5766b349a621104998de83]; 2025-04-29 14:57:30 +03:00
txix e4ef2d8645 2025-04-23 12:39:56: merge [master:82ac257e917aa3f9ab915b911afbd28c0f52f88e]; 2025-04-23 12:39:56 +03:00
txix bfc28503d5 2025-04-18 12:46:39: merge [master:7b5fc0b41640a6b6648e6391777fa08099997af1]; 2025-04-18 12:46:39 +03:00
txix d759f883f4 2025-04-18 12:26:12: merge [master:576ef18526fa6f0685f8ab997cae0d31a4ebce90]; 2025-04-18 12:26:13 +03:00
txix 64373fdf3c 2025-04-03 17:31:43: merge [master:03df79d7b37febb99439347c2da79707bf437498]; 2025-04-03 17:31:43 +03:00
txix 1dd566593e 2024-12-27 17:46:16: merge [master:4898a95fc423e3ae55135d3023a1b78fb18edebc]; 2024-12-27 17:46:16 +03:00
txix 560c1f22c4 2024-12-27 12:28:18: merge [master:9ec52bd8525d6120bfebe62b6da4eb172a000ee8]; 2024-12-27 12:28:18 +03:00
txix 171b85f627 2024-12-27 12:14:12: merge [master:bf6ba426f66d82ef1e76da30674890898919501b]; 2024-12-27 12:14:12 +03:00
txix 734b83b2b8 2024-12-11 12:34:04: merge [master:744eaa2605c9d3eb73b2db76661b2d0a6949d4d9]; 2024-12-11 12:34:04 +03:00
txix bdeb2c0753 2024-12-03 13:02:16: merge [master:b21f96b8a5ec988002a89bd9d1f51e90c01a2d21]; 2024-12-03 13:02:16 +03:00
txix 97c44fb3bd 2024-10-11 14:58:36: merge [master:7f99b95ceaaed865d2833070a0397cf191949b8e]; 2024-10-11 14:58:36 +03:00
txix 6db18c1495 2024-07-01 10:56:14: merge [master:f9b2632335c35844013af97443dacebb9fc385c5]; 2024-07-01 10:56:14 +03:00
txix cd985ff5a3 2024-03-26 12:20:05: merge [master:27c825f7051ccbb42344a2d66c50192e2b3b5889]; 2024-03-26 12:20:05 +03:00
txix 2eed857503 2024-03-22 15:21:57: merge [master:d3624ee87e4530490024ae4023a1c69643689e95]; 2024-03-22 15:21:57 +03:00
txix 2b91caece0 2024-01-22 17:22:41: merge [master:56d3e06e49d7a75f142424293788a4f3b6245430]; 2024-01-22 17:22:41 +03:00
61 changed files with 526 additions and 1786 deletions

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
name: Create and publish a Docker image
on:
push:
tags:
- 'v*'
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
APP_NAME: ${{ github.event.repository.name }}
jobs:
build-and-push-image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
attestations: write
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Get version from tag
id: version_reader
run: |
VERSION=${GITHUB_REF_NAME#v}
echo "version=$VERSION" >> $GITHUB_OUTPUT
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
driver: docker-container
- name: Log in to the Container registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push Docker image
id: push
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version_reader.outputs.version }}
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
labels: |
org.opencontainers.image.title=${{ env.IMAGE_NAME }}
org.opencontainers.image.version=${{ steps.version_reader.outputs.version }}
build-args: |
app_name=${{ env.APP_NAME }}
version=${{ steps.version_reader.outputs.version }}
- name: Generate artifact attestation
uses: actions/attest-build-provenance@v2
with:
subject-name: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME}}
subject-digest: ${{ steps.push.outputs.digest }}
push-to-registry: true
-2
View File
@@ -74,5 +74,3 @@ package.json
yarn.lock
conf/config_dev.yml
.DS_Store
+9 -12
View File
@@ -15,17 +15,11 @@ linters:
- nolintlint # Goland все равно форматирует с отступом
- perfsprint # мнимая производительность в угоду читаемости
- tagalign # не всегда имеет смысл
- testpackage
- varnamelen # очень индивидуально (db)
- wsl # расставление пробелов очень индивидуально
- wsl_v5 # расставление пробелов очень индивидуально
- godoclint # ругается на // nolint, не удобно
- prealloc # слишком аггресивный, в большинстве случаев не требуется
- gomodguard # deprecated
- goconst # слишком агрессивный
settings:
exhaustruct_v5:
allow-empty: true
explicit-mode: true
cyclop:
max-complexity: 15 # по умолчанию 10 мало
funlen:
@@ -62,12 +56,15 @@ linters:
- wrapcheck
path: transaction # транзакции прозрачны
- linters:
- unqueryvet
- prealloc
path: ".*_test\\.go$"
- wrapcheck
path: middleware #отсутствует необходимость оборачивать ошибки
- linters:
- goconst
path: "tests/" # компонентные тесты: фикстуры и моки не выносим в константы
- gochecknoglobals
- mnd
path: proxy
- linters:
- wrapcheck
path: httperrors #отсутствует необходимость оборачивать ошибки
paths:
- third_party$
- builtin$
+1 -1
View File
@@ -1 +1 @@
5.11.5
5.6.2
-37
View File
@@ -1,40 +1,3 @@
### v5.11.5
* Обновлена версия go до версии 1.27
* Обновлены правила для linter
* Обновлены зависимости
### v5.11.4
* добавлена возможность через переменную окружения `adminServiceName` переопределить название сервиса `msp-admin-service`
### v5.11.3
* добавлена настройка для преопределения content-type в ответе с `application/json` на `application/json; charset=utf-8` для конкретных приложений
### v5.11.2
* обновлены зависимости
### v5.11.1
* Обновлен isp-kit
### v5.11.0
* Добавлена поддержка нескольких `tokenProvider` для `customAuth.userAuthSettings`: используется первый провайдер, вернувший токен
### v5.10.2
* Убрано дублирование поля `requestId` при логгировании
### v5.10.1
* Изменен нейминг настройки `customAuth.userAuthSettings.authenticateMethodPath` на `customAuth.userAuthSettings.authenticateEndpoint`
### v5.10.0
* Добавлена конфигурируемая аутентификация/авторизация пользователя
### v5.9.3
* Исправлена опечатка при вызове `strings.TrimPrefix`
### v5.9.2
* При проверке `logging.skipBodyLoggingEndpointPrefixes` игнорируется `/` в начале, путь для проверки берётся из `pathSchema`, если `pathSchema` пустая, берётся вызываемый `endpoint`
* В логе `log request` из значения в поле `endpoint` удаляется `/` в начале, путь берётся из `pathSchema`, если `pathSchema` пустая, берётся вызываемый `endpoint`
### v5.9.1
* Добавлен `warn` лог на неизвестный endpoint
### v5.9.0
* Теперь в зависимоси от `StatusCode` выводится соотвествующий уровень логирования: 400 -> warn, 500 -> error
* Исправлен порядок мидлварей, для корректного проброса `requestId`
### v5.8.1
* Обновлены зависимости
### v5.8.0
* Изменён resolve для endpoint'ов, теперь используется `lookup` у `github.com/julienschmidt/httprouter`
* Добавлен http метод в запрос авторизации (`system/secure/authorize`)
### v5.7.0
* Добавлено лог поле `applicationName` в логи `log request` и `bypassing unauthorized request because it has admin privilege`
### v5.6.2
* Обновлено заполнение заголовка `x-application-name` для поддержки кириллических символов
### v5.6.1
+6 -30
View File
@@ -2,28 +2,20 @@ package assembly
import (
"context"
"time"
"isp-gate-service/cache"
"isp-gate-service/conf"
"isp-gate-service/routes"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/app"
"github.com/txix-open/isp-kit/bootstrap"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/lb"
"github.com/txix-open/isp-kit/log"
)
const (
routerModuleName = "isp-router-service"
defaultAdminServiceName = "msp-admin-service"
usersAuthCachePurgeInterval = 5 * time.Second
)
type Assembly struct {
boot *bootstrap.Bootstrap
server *http.Server
@@ -32,13 +24,10 @@ type Assembly struct {
systemCli *client.Client
adminCli *client.Client
lockerCli *client.Client
routerLb *lb.RoundRobin
localConfig conf.Local
locations []conf.Location
grpcClientByModuleName map[string]*client.Client
httpHostManagerByModuleName map[string]*lb.RoundRobin
usersAuthCache *cache.Cache
}
func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
@@ -85,15 +74,13 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
boot: boot,
server: server,
logger: boot.App.Logger(),
routes: routes.NewRoutes(boot.App.Logger()),
localConfig: localConfig,
routes: routes.NewRoutes(),
locations: localConfig.Locations,
grpcClientByModuleName: grpcClientByModuleName,
httpHostManagerByModuleName: httpHostManagerByModuleName,
systemCli: systemCli,
adminCli: adminCli,
lockerCli: lockerCli,
routerLb: lb.NewRoundRobin(nil),
usersAuthCache: cache.New(),
}, nil
}
@@ -116,10 +103,8 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error
a.systemCli,
a.adminCli,
a.lockerCli,
a.routerLb,
a.usersAuthCache,
)
handler, err := locator.Handler(newCfg, a.localConfig.Locations)
handler, err := locator.Handler(newCfg, a.locations)
if err != nil {
return errors.WithMessage(err, "locator handler")
}
@@ -140,14 +125,9 @@ func (a *Assembly) Runners() []app.Runner {
for moduleName, upgrader := range a.httpHostManagerByModuleName {
eventHandler.RequireModule(moduleName, upgrader)
}
adminServiceName := a.localConfig.AdminServiceName
if adminServiceName == "" {
adminServiceName = defaultAdminServiceName
}
eventHandler.RequireModule("isp-system-service", a.systemCli)
eventHandler.RequireModule(adminServiceName, a.adminCli)
eventHandler.RequireModule("msp-admin-service", a.adminCli)
eventHandler.RequireModule("isp-lock-service", a.lockerCli)
eventHandler.RequireModule(routerModuleName, a.routerLb)
return []app.Runner{
app.RunnerFunc(func(ctx context.Context) error {
@@ -156,10 +136,6 @@ func (a *Assembly) Runners() []app.Runner {
app.RunnerFunc(func(ctx context.Context) error {
return a.boot.ClusterCli.Run(ctx, eventHandler)
}),
app.RunnerFunc(func(ctx context.Context) error {
a.usersAuthCache.StartCleaner(ctx, usersAuthCachePurgeInterval)
return nil
}),
}
}
+9 -51
View File
@@ -1,14 +1,11 @@
package assembly
import (
"net/http"
"strings"
"time"
"github.com/txix-open/isp-kit/metrics"
"github.com/txix-open/isp-kit/metrics/http_metrics"
"net/http"
"time"
"isp-gate-service/cache"
"isp-gate-service/conf"
"isp-gate-service/middleware"
"isp-gate-service/proxy"
@@ -17,7 +14,7 @@ import (
"isp-gate-service/service"
mux2 "github.com/gorilla/mux"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/lb"
"github.com/txix-open/isp-kit/log"
@@ -31,8 +28,6 @@ type Locator struct {
systemCli *client.Client
adminCli *client.Client
lockerCli *client.Client
routerLb *lb.RoundRobin
usersAuthCache *cache.Cache
}
func NewLocator(
@@ -43,8 +38,6 @@ func NewLocator(
systemCli *client.Client,
adminCli *client.Client,
lockerCli *client.Client,
routerLb *lb.RoundRobin,
usersAuthCache *cache.Cache,
) Locator {
return Locator{
logger: logger,
@@ -54,8 +47,6 @@ func NewLocator(
systemCli: systemCli,
adminCli: adminCli,
lockerCli: lockerCli,
routerLb: routerLb,
usersAuthCache: usersAuthCache,
}
}
@@ -66,17 +57,6 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
authenticationCache := repository.NewAuthenticationCache(time.Duration(config.Caching.AuthenticationDataInSec) * time.Second)
authentication := service.NewAuthentication(authenticationCache, systemRepo)
userAuthenticationCache := repository.NewUserAuthenticationCache(l.usersAuthCache)
userAuthRepo := repository.NewUserAuth(l.routerLb)
userAuthentication, err := service.NewUserAuthentication(
config.CustomAuth,
userAuthenticationCache,
userAuthRepo,
)
if err != nil {
return nil, errors.WithMessage(err, "new user authentication")
}
adminService := service.NewAdmin(
repository.NewAuthorizationCache(time.Duration(config.Caching.AuthorizationDataInSec)*time.Second),
adminRepo,
@@ -91,11 +71,6 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
dailyLimitService := service.NewDailyLimit(lockRepo, config.DailyLimits)
throttlingService := service.NewThrottling(lockRepo, config.Throttling)
skipBodyLoggingEndpointPrefixes := make([]string, 0, len(config.Logging.SkipBodyLoggingEndpointPrefixes))
for _, prefix := range config.Logging.SkipBodyLoggingEndpointPrefixes {
skipBodyLoggingEndpointPrefixes = append(skipBodyLoggingEndpointPrefixes, strings.TrimPrefix(prefix, "/"))
}
mux := mux2.NewRouter()
for _, location := range locations {
var proxyFunc middleware.Handler
@@ -107,9 +82,6 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
proxyFunc = proxy.NewGrpc(cli, location.SkipAuth, time.Duration(config.Http.ProxyTimeoutInSec)*time.Second)
case conf.HttpProtocol:
hostManager := l.httpHostManagerByModuleName[location.TargetModule]
if location.TargetModule == routerModuleName {
hostManager = l.routerLb
}
proxyFunc = proxy.NewHttp(hostManager, location.SkipAuth, time.Duration(config.Http.ProxyTimeoutInSec)*time.Second)
case conf.WsProtocol:
hostManager := l.httpHostManagerByModuleName[location.TargetModule]
@@ -124,11 +96,6 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
forwardReqIdByAppId[setting.ApplicationId] = setting.ForwardRequestId
}
enableUtf8JsonCharsetByApp := make(map[int]bool, len(config.ResponseContentTypeSettings))
for _, setting := range config.ResponseContentTypeSettings {
enableUtf8JsonCharsetByApp[setting.ApplicationId] = setting.AddJsonUtf8Charset
}
metricsStorage := http_metrics.NewServerStorage(metrics.DefaultRegistry)
handler := middleware.Chain(
@@ -139,33 +106,26 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
config.Logging.SkipBodyLoggingEndpointPrefixes,
config.Logging.EnableForceUnescapingUnicode,
),
middleware.RequestId(),
middleware.ErrorHandler(l.logger),
middleware.UserAuthenticate(userAuthentication, l.logger),
middleware.Authenticate(authentication),
middleware.AdminAuthenticate(adminService),
middleware.ClientRequestId(config.EnableClientRequestIdForwarding, forwardReqIdByAppId),
middleware.JsonResponseUtf8Charset(enableUtf8JsonCharsetByApp),
middleware.Authorize(authorization, l.logger),
middleware.AdminAuthorize(adminService),
middleware.AdminAuthorize(l.routes, adminService),
middleware.Throttling(throttlingService),
middleware.DailyLimit(dailyLimitService),
middleware.RequestId(config.EnableClientRequestIdForwarding, forwardReqIdByAppId),
middleware.Metrics(metricsStorage),
)
errorOnUnknownEndpoint := true
if location.SkipAuth {
errorOnUnknownEndpoint = false
handler = middleware.Chain(
proxyFunc,
middleware.Logger(l.logger, config.Logging.RequestLogEnable,
enableBodyLog,
skipBodyLoggingEndpointPrefixes,
config.Logging.SkipBodyLoggingEndpointPrefixes,
config.Logging.EnableForceUnescapingUnicode,
),
middleware.RequestId(),
middleware.ErrorHandler(l.logger),
middleware.ClientRequestId(config.EnableClientRequestIdForwarding, forwardReqIdByAppId),
middleware.RequestId(config.EnableClientRequestIdForwarding, forwardReqIdByAppId),
middleware.Metrics(metricsStorage),
)
}
@@ -173,10 +133,8 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
config.Http.MaxRequestBodySizeInMb*1024*1024, //nolint:mnd
handler,
middleware.EntryPointConfig{
WithPrefix: location.WithPrefix,
PathPrefix: location.PathPrefix,
ErrorOnUnknownEndpoint: errorOnUnknownEndpoint,
WithLendingSlash: location.Protocol != conf.GrpcProtocol,
WithPrefix: location.WithPrefix,
PathPrefix: location.PathPrefix,
},
l.routes,
l.logger,
-29
View File
@@ -1,7 +1,6 @@
package cache
import (
"context"
"sync"
"time"
)
@@ -49,34 +48,6 @@ func (c *Cache) Set(key string, data []byte, lifeTime time.Duration) {
}
}
// StartCleaner runs periodic cleanup.
// Blocking call: intended to be run in a separate goroutine.
func (c *Cache) StartCleaner(ctx context.Context, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
c.cleanup()
}
}
}
func (c *Cache) cleanup() {
c.lock.Lock()
defer c.lock.Unlock()
now := c.now()
for k, v := range c.store {
if now.After(v.expiredAt) {
delete(c.store, k)
}
}
}
func (c *Cache) now() time.Time {
return time.Now()
}
+1 -2
View File
@@ -17,9 +17,8 @@ logfile:
maxBackups: 4
compress: true
adminServiceName: msp-admin-service
locations:
- pathPrefix: /api
protocol: grpc
targetModule: router
targetModule: router
+1 -2
View File
@@ -7,8 +7,7 @@ const (
)
type Local struct {
Locations []Location
AdminServiceName string
Locations []Location
}
type Location struct {
+2 -48
View File
@@ -9,15 +9,10 @@ import (
"github.com/txix-open/jsonschema"
)
const (
HeaderTokenProviderType = "HEADER"
CookieTokenProviderType = "COOKIE"
)
func init() {
schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Schema) {
t.Type = "string"
t.Enum = []any{"debug", "info", "warn", "error", "fatal"}
t.Enum = []interface{}{"debug", "info", "warn", "error", "fatal"}
})
}
@@ -29,8 +24,6 @@ type Remote struct {
Throttling []Throttling `schema:"Настройки пропускной способности"`
EnableClientRequestIdForwarding bool `schema:"Включить проброс requestId из заголовка запроса"`
ForwardReqIdClientSettings []ForwardReqIdClientSettings `schema:"Настройки проброcа requestId для приложений"`
CustomAuth CustomAuth `schema:"Настройка кастомной аутентификации/авторизации"`
ResponseContentTypeSettings []ResponseContentTypeSetting `schema:"Настройки Content-Type ответов"`
}
type ForwardReqIdClientSettings struct {
@@ -47,7 +40,7 @@ type Logging struct {
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования,логирование запросов осуществляется на уровне debug"`
RequestLogEnable bool `schema:"Включить логирование запросов"`
BodyLogEnable bool `schema:"Включить логирование тел запросов и ответов,должно быть включено логирование запросов"`
SkipBodyLoggingEndpointPrefixes []string `schema:"Выключить логирование тел запросов и ответов для путей имеющих префикс из списка,'/' в начале игнорируется"`
SkipBodyLoggingEndpointPrefixes []string `schema:"регулярные выражения для отключения логирования"`
EnableForceUnescapingUnicode bool `schema:"Включить перевод тел запроса из unicode в utf-8, должно быть включено логирование тел запросов и ответов"`
}
@@ -65,42 +58,3 @@ type Throttling struct {
ApplicationId int `validate:"required" schema:"ID приложения"`
RequestsPerSeconds int `validate:"required,min=1,max=1000" schema:"Запросов в секунду,не конфликтует с суточными ограничениями, алгоритм не работает на значениях больше 1000"`
}
type CustomAuth struct {
TokenProviders []TokenProvider `schema:"Настройки получения токена из запроса"`
UserAuthSettings []UserAuthSetting `schema:"Настройка пользовательской аутентификации/авторизации"`
}
type AuthProvider struct {
Name string `schema:"Название настройки аутентификации/авторизации,должно быть уникальным" validate:"required"`
ModuleName string `schema:"Название модуля,реализующего аутентификацию/авторизацию" validate:"required"`
}
type TokenProvider struct {
Name string `schema:"Название метода получения токена из запроса,должно быть уникальным" validate:"required"`
Type string `schema:"Тип метода получения токена,один из: HEADER COOKIE" validate:"required,oneof=HEADER COOKIE"`
HeaderProvider *HeaderTokenProvider `schema:"Настройки для получения токена из заголовка"`
CookieProvider *CookieTokenProvider `schema:"Настройки для получения токена из cookie"`
}
type HeaderTokenProvider struct {
HeaderName string `schema:"Название заголовка,из которого берётся токен" validate:"required"`
}
type CookieTokenProvider struct {
CookieName string `schema:"Название cookie,из которого берётся токен" validate:"required"`
Validate bool `schema:"Проверить валидность cookie"`
}
type UserAuthSetting struct {
ModuleNameList []string `schema:"Название модулей,для которых настраивается аутентификация/авторизация,название модулей должно быть уникальным" validate:"required"`
TokenProviders []string `schema:"Список названий методов получения токена из запроса,используется первый провайдер, вернувший токен"`
AuthenticateEndpoint string `schema:"Endpoint для аутентификации пользователя,вызывается через isp-router-service" validate:"required"`
CacheDataInSec int `schema:"Время кеширования данных аутентификации/авторизации пользователя,отключен при значениях <=0,в секундах"`
SkipAppAuth bool `schema:"Пропустить аутентификацию и авторизацию приложения"`
}
type ResponseContentTypeSetting struct {
ApplicationId int `validate:"required" schema:"ID приложения"`
AddJsonUtf8Charset bool `schema:"Добавлять charset=utf-8 в Content-Type ответа: application/json для locations с protocol=http"`
}
+1 -30
View File
@@ -1,38 +1,9 @@
package domain
type AuthenticateAppResponse struct {
Authenticated bool
ErrorReason string
AuthData *AppAuthData
}
type AppAuthData struct {
type AuthData struct {
AppName string
SystemId int
DomainId int
ServiceId int
ApplicationId int
}
type ApplicationToken struct {
AppToken string
AppName string
}
type UserToken struct {
Token string
}
type AuthenticateUserResponse struct {
Authenticated bool
SkipUserAuth bool
ErrorReason string
AuthData *UserAuthData
}
type UserAuthData struct {
SkipAppAuth bool
Identity string
IdentityHeader string
ExtraHeaders map[string][]string
}
+1 -1
View File
@@ -1,7 +1,7 @@
package domain
import (
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
)
var (
-31
View File
@@ -1,31 +0,0 @@
package domain
import (
"context"
)
type EndpointMeta struct {
Inner bool
UserAuthRequired bool
ModuleName string
RequiredAdminPermission string
// Объявляемый сервисом метод
PathSchema string
// Вызываемый метод
Endpoint string
// Нормализованный путь, для известных путей берётся объявляемый метод, для неизвестных - вызываемый
// Удаляет '/' из начала пути
NormalizedEndpoint string
}
type endpointMetaKey struct{}
func (m EndpointMeta) ToContext(ctx context.Context) context.Context {
return context.WithValue(ctx, endpointMetaKey{}, m)
}
func EndpointMetaFromContext(ctx context.Context) EndpointMeta {
meta, _ := ctx.Value(endpointMetaKey{}).(EndpointMeta)
return meta
}
-9
View File
@@ -1,9 +0,0 @@
package domain
import "github.com/txix-open/isp-kit/errors"
var (
ErrUserAuthSettingNotFound = errors.New("user auth setting not found")
ErrEmptyUserToken = errors.New("failed to extract user token")
ErrInvalidUserToken = errors.New("invalid user token")
)
+2 -3
View File
@@ -1,4 +1,4 @@
package entity
package domain
type AuthenticateRequest struct {
Token string
@@ -7,12 +7,11 @@ type AuthenticateRequest struct {
type AuthenticateResponse struct {
Authenticated bool
ErrorReason string
AuthData *AppAuthData
AuthData *AuthData
}
type AuthorizeRequest struct {
ApplicationId int
HttpMethod string
Endpoint string
}
-7
View File
@@ -1,7 +0,0 @@
package entity
type AdminAuthenticateResponse struct {
Authenticated bool
ErrorReason string
AdminId int
}
-9
View File
@@ -1,9 +0,0 @@
package entity
type AppAuthData struct {
AppName string
SystemId int
DomainId int
ServiceId int
ApplicationId int
}
-17
View File
@@ -1,17 +0,0 @@
package entity
type UserAuthenticateRequest struct {
Token string
}
type UserAuthenticateResponse struct {
Authenticated bool
ErrorReason string
AuthData *UserAuthData
}
type UserAuthData struct {
Identity string
IdentityHeader string
ExtraHeaders map[string][]string
}
+49 -47
View File
@@ -1,77 +1,79 @@
module isp-gate-service
go 1.27.0
go 1.25
require (
github.com/google/uuid v1.6.0
github.com/gorilla/mux v1.8.1
github.com/gorilla/websocket v1.5.3
github.com/julienschmidt/httprouter v1.3.0
github.com/redis/go-redis/v9 v9.24.0
github.com/stretchr/testify v1.12.1
github.com/pkg/errors v0.9.1
github.com/redis/go-redis/v9 v9.11.0
github.com/stretchr/testify v1.11.1
github.com/tomakado/websocketproxy v0.1.0
github.com/txix-open/etp/v3 v3.2.0
github.com/txix-open/isp-kit v1.76.0
github.com/txix-open/isp-kit v1.64.4
github.com/txix-open/jsonschema v1.3.0
google.golang.org/genproto/googleapis/rpc v0.0.0-20261123191846-1e707ab9fbc2
google.golang.org/grpc v1.85.0
golang.org/x/net v0.47.0
google.golang.org/genproto/googleapis/rpc v0.0.0-20250908214217-97024824d090
google.golang.org/grpc v1.75.1
)
require (
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/txix-open/etp/v4 v4.0.1 // indirect
go.opentelemetry.io/auto/sdk v1.2.0 // indirect
go.yaml.in/yaml/v2 v2.4.3 // indirect
)
require (
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/buger/jsonparser v1.6.1 // indirect
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/buger/jsonparser v1.1.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/coder/websocket v1.8.15 // indirect
github.com/gabriel-vasile/mimetype v1.4.16 // indirect
github.com/getsentry/sentry-go v0.50.0 // indirect
github.com/go-faker/faker/v4 v4.12.0 // indirect
github.com/go-logr/logr v1.4.4 // indirect
github.com/coder/websocket v1.8.14 // 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.10 // indirect
github.com/getsentry/sentry-go v0.35.2 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-playground/locales v0.14.2 // indirect
github.com/go-playground/universal-translator v0.18.2 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.20.5 // indirect
github.com/leodido/go-urn v1.5.0 // indirect
github.com/mailru/easyjson v0.9.2 // indirect
github.com/julienschmidt/httprouter v1.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mailru/easyjson v0.9.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/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pandatix/go-abnf v0.5.5 // indirect
github.com/prometheus/client_golang v1.25.0 // indirect
github.com/prometheus/client_model v0.6.3 // indirect
github.com/prometheus/common v0.74.0 // indirect
github.com/prometheus/procfs v0.23.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_golang v1.23.2 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.66.1 // indirect
github.com/prometheus/procfs v0.17.0 // indirect
github.com/txix-open/bellows v1.2.0 // indirect
github.com/txix-open/etp/v4 v4.1.3 // indirect
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 // indirect
github.com/txix-open/etp/v3 v3.2.0
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb // 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/auto/sdk v1.2.2 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 // indirect
go.opentelemetry.io/otel v1.47.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 // indirect
go.opentelemetry.io/otel/log v1.47.0 // indirect
go.opentelemetry.io/otel/metric v1.47.0 // indirect
go.opentelemetry.io/otel/sdk v1.47.0 // indirect
go.opentelemetry.io/otel/trace v1.47.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.1 // indirect
go.uber.org/atomic v1.12.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.63.0 // indirect
go.opentelemetry.io/otel v1.38.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 // indirect
go.opentelemetry.io/otel/metric v1.38.0 // indirect
go.opentelemetry.io/otel/sdk v1.38.0 // indirect
go.opentelemetry.io/otel/trace v1.38.0 // indirect
go.opentelemetry.io/proto/otlp v1.8.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.28.0 // indirect
go.yaml.in/yaml/v3 v3.0.6 // indirect
golang.org/x/crypto v0.59.0 // indirect
golang.org/x/net v0.63.0 // indirect
golang.org/x/sys v0.50.0 // indirect
golang.org/x/text v0.44.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20261123191846-1e707ab9fbc2 // indirect
google.golang.org/protobuf v1.36.12 // indirect
go.uber.org/zap v1.27.0 // indirect
golang.org/x/crypto v0.45.0 // indirect
golang.org/x/sys v0.38.0 // indirect
golang.org/x/text v0.31.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250908214217-97024824d090 // indirect
google.golang.org/protobuf v1.36.9 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+102 -106
View File
@@ -8,37 +8,44 @@ 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.6.1 h1:I0phFv0PlbLHnM7TZAVjZ2MJ2/eWRTDyuO7GLR98IEs=
github.com/buger/jsonparser v1.6.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
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.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=
github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
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/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4=
github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g=
github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8=
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.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0=
github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/getsentry/sentry-go v0.35.2 h1:jKuujpRwa8FFRYMIwwZpu83Xh0voll9bmvyc6310WBM=
github.com/getsentry/sentry-go v0.35.2/go.mod h1:mdL49ixwT2yi57k5eh7mpnDyPybixPzlzEJFu0Z76QA=
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-faker/faker/v4 v4.12.0 h1:yZXxuoQjxN+C2PVgYoDSHGiD9wj6dX1/Ful4p7QQV0k=
github.com/go-faker/faker/v4 v4.12.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
github.com/go-faker/faker/v4 v4.6.1 h1:xUyVpAjEtB04l6XFY0V/29oR332rOSPWV4lU8RwDt4k=
github.com/go-faker/faker/v4 v4.6.1/go.mod h1:arSdxNCSt7mOhdk8tEolvHeIJ7eX4OX80wXjKKvkKBY=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/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.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.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY=
github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU=
github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk=
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.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-resty/resty/v2 v2.16.5 h1:hBKqmWrr7uRc3euHVqmh1HTHcKn99Smr7o5spptdhTM=
github.com/go-resty/resty/v2 v2.16.5/go.mod h1:hkJtXbA2iKHzJheXYvQ8snQES5ZLGKMwQ07xAwp/fiA=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
@@ -50,26 +57,24 @@ 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.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 h1:vzlTzzi4tHLa/JQdIE5LeXw6SEX5EVVhq/VPqKHnKOk=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 h1:8Tjv8EJ+pM1xP8mK6egEbD1OgnVTyacbefKhmbLhIhU=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2/go.mod h1:pkJQ2tZHJ0aFOVEEot6oZmaVEZcRme73eIFmhiVuRWs=
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.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs=
github.com/klauspost/compress v1.20.5/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/klauspost/compress v1.18.1 h1:bcSGx7UbpBqMChDtsF28Lw6v/G94LPrrbMbdC3JH2co=
github.com/klauspost/compress v1.18.1/go.mod h1:ZQFFVG+MdnR0P+l6wpXgIL4NTtwiKIdBnrBd8Nrxr+0=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
github.com/mailru/easyjson v0.9.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M=
github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mailru/easyjson v0.9.0 h1:PrnmzHw7262yW8sTBwxi1PdJA3Iw/EKBa8psRf7d9a4=
github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
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=
@@ -79,25 +84,24 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/pandatix/go-abnf v0.5.5 h1:EXex5KkRQx4Dm6GnpAcQnIMBs9KiK0uf8p/wq+4t9PM=
github.com/pandatix/go-abnf v0.5.5/go.mod h1:AE0KD3/VNoCjGzc1gqetRKshbI4SYErXQ/8kPenR5mc=
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.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/nrLI=
github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA=
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
github.com/rabbitmq/amqp091-go v1.17.0 h1:6KmTqrnJq93cGIE3Q3UnXgsqw6NtLu8MNfFoIbfBAIQ=
github.com/rabbitmq/amqp091-go v1.17.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
github.com/redis/go-redis/v9 v9.24.0 h1:X1AnQHWaSfMeggDQm7UFad1YwJmoZxVm5XkaP0kr6nQ=
github.com/redis/go-redis/v9 v9.24.0/go.mod h1:ted97kpLnB4S2KJkTkw+7GzRjgkFnU909IIrksu+ut4=
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0=
github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw=
github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw=
github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
github.com/redis/go-redis/v9 v9.11.0 h1:E3S08Gl/nJNn5vkxd2i78wZxWAPNZgUNTp8WIJUAiIs=
github.com/redis/go-redis/v9 v9.11.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
@@ -109,24 +113,24 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
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/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgjeY=
github.com/txix-open/bellows v1.2.0/go.mod h1:qbKCy+RTgD30Qpw1fyb3y3jp5Y9mGhLLxgae1l0W92o=
github.com/txix-open/etp/v3 v3.2.0 h1:EgTchT8VtCYV1iEo/y4jII3/NybrXiQDE0y6pmS350M=
github.com/txix-open/etp/v3 v3.2.0/go.mod h1:lgen0TJmiturgBhvlxH1/PQ7iLL/OebKbxPAQYkuKI0=
github.com/txix-open/etp/v4 v4.1.3 h1:u9ZyU2yKGgoQ1/DSaElhazWm8xASdqGEdWjoJ2xQlfo=
github.com/txix-open/etp/v4 v4.1.3/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM=
github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y=
github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE=
github.com/txix-open/isp-kit v1.76.0 h1:kqhX2DuoTfeW7BIshedG26TRIfOgX0QOInm606ssGVg=
github.com/txix-open/isp-kit v1.76.0/go.mod h1:hR9iAlh3x9gEg5GfALrrkN/2SbGkgZQCmwO2GZWjC1M=
github.com/txix-open/etp/v4 v4.0.1 h1:5VSYgGsvnMz0tvUHsjVWFETI0qWBTCF1O3ARCHaCIgA=
github.com/txix-open/etp/v4 v4.0.1/go.mod h1:FIu7TUDdwcgmtmF6tFTV1bGA2fRY/iVaPQdsGzvqYc8=
github.com/txix-open/grmq v1.9.0 h1:ArDbJJcFX9zXKEcPf49rp9nYiRyGMJxGKJAxdbSsfaM=
github.com/txix-open/grmq v1.9.0/go.mod h1:EyFOP17KrwEFOUjR+PH8iH3LCtiN9TSQ8t0ysyk62po=
github.com/txix-open/isp-kit v1.64.4 h1:Z8YuaAhfJnvTdHAZB03GY5Kgnz7RyxWh1i3mALmj7A8=
github.com/txix-open/isp-kit v1.64.4/go.mod h1:GvBsX5p2U3/ugK6PuWANYzSy/4YgawROm3eAKb35G6o=
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4=
github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 h1:1jE11HLmMHDYYAcE+UmQ5VHgz4stzz0+daJbDWS+sEs=
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3/go.mod h1:Yf41v210LFyYAj+tGmDh7PHdGsTaZjdBzHG0ptUvihw=
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb/go.mod h1:0biAFE0bgbcKeBBAwgEDhbZz6uT1vuSETCrFQlv2RiA=
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=
@@ -136,64 +140,56 @@ github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHo
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=
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
go.opentelemetry.io/auto/sdk v1.2.2 h1:ErNn7NW2t1F9CFBLb9iyPMyLRbcEd07l5m/StCe9AEE=
go.opentelemetry.io/auto/sdk v1.2.2/go.mod h1:Ca3X8ec6gdTYjAirla//dnp05ECtQPfN4Ut74OJLVsQ=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 h1:jva1c3z2ZFEQ5sTvnLG2tBALNehO+QvdXKQii6eKRoo=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0/go.mod h1:3pjFS5EnOVfjvYO6/NMdtJFHFQR+8uiGtrZ965nZP4w=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38=
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I=
go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0=
go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw=
go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw=
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
go.opentelemetry.io/proto/otlp v1.11.1 h1:SCrPqH9NE5CmBrOqpjNCiT0X5mGwMyGERXdogfR7Yjw=
go.opentelemetry.io/proto/otlp v1.11.1/go.mod h1:wq8W4aSf6bOy8RZyESOeQFr9Pu7wydWX/TY4sgvrTPg=
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
go.opentelemetry.io/auto/sdk v1.2.0 h1:YpRtUFjvhSymycLS2T81lT6IGhcUP+LUPtv0iv1N8bM=
go.opentelemetry.io/auto/sdk v1.2.0/go.mod h1:1deq2zL7rwjwC8mR7XgY2N+tlIl6pjmEUoLDENMEzwk=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.63.0 h1:2pn7OzMewmYRiNtv1doZnLo3gONcnMHlFnmOR8Vgt+8=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.63.0/go.mod h1:rjbQTDEPQymPE0YnRQp9/NuPwwtL0sesz/fnqRW/v84=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg=
go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8=
go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 h1:GqRJVj7UmLjCVyVJ3ZFLdPRmhDUp2zFmQe3RHIOsw24=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0/go.mod h1:ri3aaHSmCTVYu2AWv44YMauwAQc0aqI9gHKIcSbI1pU=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 h1:aTL7F04bJHUlztTsNGJ2l+6he8c+y/b//eR0jjjemT4=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0/go.mod h1:kldtb7jDTeol0l3ewcmd8SDvx3EmIE7lyvqbasU3QC4=
go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA=
go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=
go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E=
go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=
go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM=
go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA=
go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
go.opentelemetry.io/proto/otlp v1.8.0 h1:fRAZQDcAFHySxpJ1TwlA1cJ4tvcrw7nXl9xWWC8N5CE=
go.opentelemetry.io/proto/otlp v1.8.0/go.mod h1:tIeYOeNBU4cvmPqpaji1P+KbB4Oloai8wN4rWzRrFF0=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
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.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
go.yaml.in/yaml/v2 v2.4.5 h1:a5nxWvYi94DRl6QSLlTbLpVmutgx2qg8EVjnJtuFpwI=
go.yaml.in/yaml/v2 v2.4.5/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/api v0.0.0-20261123191846-1e707ab9fbc2 h1:TVEW5ciB4lPlyo3RBDd2JTlUY0vAzMkPlU/qAzC+rqU=
google.golang.org/genproto/googleapis/api v0.0.0-20261123191846-1e707ab9fbc2/go.mod h1:3q/FqMoaJXT/mbOLAkZaCXuOEpmvBNwYXqdJKeN0gD0=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261123191846-1e707ab9fbc2 h1:FCWn4wv5of/ooWpbWDIeOXqI3+h2MGnV7SvvcJ8f+bQ=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261123191846-1e707ab9fbc2/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
google.golang.org/genproto/googleapis/api v0.0.0-20250908214217-97024824d090 h1:d8Nakh1G+ur7+P3GcMjpRDEkoLUcLW2iU92XVqR+XMQ=
google.golang.org/genproto/googleapis/api v0.0.0-20250908214217-97024824d090/go.mod h1:U8EXRNSd8sUYyDfs/It7KVWodQr+Hf9xtxyxWudSwEw=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250908214217-97024824d090 h1:/OQuEa4YWtDt7uQWHd3q3sUMb+QOLQUg1xa8CEsRv5w=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250908214217-97024824d090/go.mod h1:GmFNa4BdJZ2a8G+wCe9Bg3wwThLrJun751XstdJt5Og=
google.golang.org/grpc v1.75.1 h1:/ODCNEuf9VghjgO3rqLcfg8fiOP0nSluljWFlDxELLI=
google.golang.org/grpc v1.75.1/go.mod h1:JtPAzKiq4v1xcAB2hydNlWI2RnF85XXcV0mhKXr2ecQ=
google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw=
google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/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=
+1 -1
View File
@@ -1,4 +1,4 @@
// nolint:mnd,gosec
// nolint:mnd
package helpers
import (
+2 -7
View File
@@ -3,7 +3,6 @@ package httperrors
import (
"net/http"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/json"
)
@@ -29,16 +28,12 @@ func (e *HttpError) Error() string {
func (e *HttpError) WriteError(w http.ResponseWriter) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(e.statusCode)
data := map[string]any{
data := map[string]interface{}{
"errorCode": http.StatusText(e.statusCode),
"errorMessage": e.userMessage,
"details": e.details,
}
err := json.NewEncoder(w).Encode(data)
if err != nil {
return errors.WithMessage(err, "json encode error")
}
return nil
return json.NewEncoder(w).Encode(data)
}
func (e *HttpError) WithDetails(details ...any) {
+3 -5
View File
@@ -1,12 +1,10 @@
package main
import (
"github.com/txix-open/isp-kit/bootstrap"
"github.com/txix-open/isp-kit/shutdown"
"isp-gate-service/assembly"
"isp-gate-service/conf"
"github.com/txix-open/isp-kit/bootstrap"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/shutdown"
)
var (
@@ -14,7 +12,7 @@ var (
)
func main() {
boot := bootstrap.New(version, conf.Remote{}, nil, cluster.HttpTransport)
boot := bootstrap.New(version, conf.Remote{}, nil)
app := boot.App
logger := app.Logger()
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"isp-gate-service/httperrors"
"isp-gate-service/request"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
)
const (
+12 -10
View File
@@ -4,21 +4,24 @@ import (
"context"
"net/http"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
"isp-gate-service/httperrors"
"isp-gate-service/request"
)
type AdminMethodStore interface {
IsInnerEndpoint(endpoint string) bool
RequiredAdminPermission(endpoint string) (string, bool)
}
type AdminAuthorizer interface {
AdminAuthorize(ctx context.Context, adminId int, permission string) (bool, error)
}
func AdminAuthorize(authorizer AdminAuthorizer) Middleware {
func AdminAuthorize(store AdminMethodStore, authorizer AdminAuthorizer) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
endpointMeta := ctx.EndpointMeta()
isInner := endpointMeta.Inner
isInner := store.IsInnerEndpoint(ctx.Endpoint())
if !isInner {
return next.Handle(ctx)
}
@@ -27,13 +30,12 @@ func AdminAuthorize(authorizer AdminAuthorizer) Middleware {
return httperrors.New(
http.StatusForbidden,
"admin authentication required",
errors.Errorf("admin authorization: admin authentication required for '%s'",
endpointMeta.Endpoint),
errors.Errorf("admin authorization: admin authentication required for '%s'", ctx.Endpoint()),
)
}
requiredPerm := endpointMeta.RequiredAdminPermission
if requiredPerm == "" {
requiredPerm, ok := store.RequiredAdminPermission(ctx.Endpoint())
if !ok {
return next.Handle(ctx)
}
@@ -47,7 +49,7 @@ func AdminAuthorize(authorizer AdminAuthorizer) Middleware {
"endpoint is not allowed",
errors.Errorf(
"admin authorization: endpoint '%s' requires '%s' permission, but admin '%d' doesn't have it",
endpointMeta.Endpoint, requiredPerm, ctx.AdminId(),
ctx.Endpoint(), requiredPerm, ctx.AdminId(),
),
)
}
+3 -7
View File
@@ -8,7 +8,7 @@ import (
"isp-gate-service/httperrors"
"isp-gate-service/request"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
)
const (
@@ -16,16 +16,12 @@ const (
)
type Authenticator interface {
Authenticate(ctx context.Context, token string) (*domain.AuthenticateAppResponse, error)
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 {
if ctx.SkipAppAuth() {
return next.Handle(ctx)
}
token, appName, err := extractToken(ctx)
if err != nil {
return err
@@ -59,7 +55,7 @@ func Authenticate(authenticator Authenticator) Middleware {
)
}
ctx.Authenticate(*resp.AuthData)
ctx.Authenticate(request.AuthData(*resp.AuthData))
return next.Handle(ctx)
})
}
+5 -19
View File
@@ -4,36 +4,25 @@ import (
"context"
"net/http"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/log"
"isp-gate-service/httperrors"
"isp-gate-service/request"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
)
type Authorizer interface {
Authorize(ctx context.Context, applicationId int, httpMethod string, pathSchema string) (bool, error)
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 {
if ctx.SkipAppAuth() {
return next.Handle(ctx)
}
authData, err := ctx.GetAuthData()
if err != nil {
return errors.WithMessage(err, "authorize: get auth data")
}
endpointMeta := ctx.EndpointMeta()
ok, err := authorizer.Authorize(
ctx.Context(),
authData.ApplicationId,
ctx.Request().Method,
endpointMeta.PathSchema,
)
ok, err := authorizer.Authorize(ctx.Context(), authData.ApplicationId, ctx.Endpoint())
if err != nil {
return errors.WithMessage(err, "authorize: authorize")
}
@@ -42,7 +31,6 @@ func Authorize(authorizer Authorizer, logger log.Logger) Middleware {
ctx.Context(),
"bypassing unauthorized request because it has admin privilege",
log.Int("applicationId", authData.ApplicationId),
log.String("applicationName", authData.AppName),
log.Int("adminId", ctx.AdminId()),
)
return next.Handle(ctx)
@@ -51,9 +39,7 @@ func Authorize(authorizer Authorizer, logger log.Logger) Middleware {
return httperrors.New(
http.StatusForbidden,
"endpoint is not allowed",
errors.Errorf("authorize: endpoint '%s' with http method '%s' is not allowed for application '%d'",
endpointMeta.PathSchema, ctx.Request().Method, authData.ApplicationId,
),
errors.Errorf("authorize: endpoint '%s' is not allowed for application '%d'", ctx.Endpoint(), authData.ApplicationId),
)
}
+1 -5
View File
@@ -4,7 +4,7 @@ import (
"context"
"net/http"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
"isp-gate-service/httperrors"
"isp-gate-service/request"
)
@@ -16,10 +16,6 @@ type DailyLimitChecker interface {
func DailyLimit(checker DailyLimitChecker) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
if ctx.SkipAppAuth() {
return next.Handle(ctx)
}
authData, err := ctx.GetAuthData()
if err != nil {
return errors.WithMessage(err, "daily limit: get auth data")
+7 -28
View File
@@ -1,24 +1,19 @@
package middleware
import (
"isp-gate-service/domain"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/log"
"isp-gate-service/request"
"net/http"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
)
type EntryPointConfig struct {
PathPrefix string
WithPrefix bool
ErrorOnUnknownEndpoint bool
WithLendingSlash bool
PathPrefix string
WithPrefix bool
}
type EndpointResolver interface {
ResolveEndpoint(method string, path string, cfg EntryPointConfig) (*domain.EndpointMeta, error)
GetPaths(path string, cfg EntryPointConfig) (string, string)
ResolveEndpoint(path string, cfg EntryPointConfig) string
}
func Entrypoint(
@@ -31,26 +26,10 @@ func Entrypoint(
return http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {
req.Body = http.MaxBytesReader(writer, req.Body, maxReqBodySize)
endpoint, err := entryPointResolver.ResolveEndpoint(req.Method, req.URL.Path, cfg)
if err != nil {
lookupPath, endpoint := entryPointResolver.GetPaths(req.URL.Path, cfg)
logger.Warn(
req.Context(),
"call unknown method",
log.String("pathPrefix", cfg.PathPrefix),
log.String("httpMethod", req.Method),
log.String("originalPath", req.URL.Path),
log.String("lookupPath", lookupPath),
log.String("enpoint", endpoint),
)
http.Error(writer, err.Error(), http.StatusNotImplemented)
return
}
endpoint := entryPointResolver.ResolveEndpoint(req.URL.Path, cfg)
ctx := request.NewContext(req, writer, endpoint)
err = next.Handle(ctx)
err := next.Handle(ctx)
if err != nil {
logger.Error(req.Context(), errors.WithMessage(err, "uncaught error"))
}
-15
View File
@@ -1,15 +0,0 @@
package middleware
import (
"isp-gate-service/request"
)
func JsonResponseUtf8Charset(applicationIds map[int]bool) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
authData, _ := ctx.GetAuthData()
ctx.EnableHttpJsonUtf8Charset(applicationIds[authData.ApplicationId])
return next.Handle(ctx)
})
}
}
+7 -21
View File
@@ -11,7 +11,7 @@ import (
"isp-gate-service/helpers"
"isp-gate-service/request"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/http/endpoint/buffer"
"github.com/txix-open/isp-kit/log"
)
@@ -35,11 +35,7 @@ func (w *writerWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if !ok {
return nil, nil, errors.New("writerWrapper: upstream writer doesn't implement Hijack")
}
conn, rw, err := upstream.Hijack()
if err != nil {
return nil, nil, errors.WithMessage(err, "hijack error")
}
return conn, rw, nil
return upstream.Hijack()
}
func (w *writerWrapper) StatusCode() int {
@@ -54,7 +50,7 @@ func (w *writerWrapper) WriteHeader(statusCode int) {
w.ResponseWriter.WriteHeader(statusCode)
}
func Logger( // nolint:gocognit,funlen
func Logger( // nolint:gocognit
logger log.Logger,
enableRequestLogging bool,
enableBodyLogging bool,
@@ -69,11 +65,10 @@ func Logger( // nolint:gocognit,funlen
r := ctx.Request()
endpoint := ctx.EndpointMeta().NormalizedEndpoint
logBodyFromCurrenRequest := enableBodyLogging
if logBodyFromCurrenRequest {
for _, prefix := range skipBodyLoggingEndpointPrefixes {
if strings.HasPrefix(endpoint, prefix) {
if strings.HasPrefix(ctx.Endpoint(), prefix) {
logBodyFromCurrenRequest = false
break
}
@@ -115,9 +110,8 @@ func Logger( // nolint:gocognit,funlen
log.String("xForwardedFor", r.Header.Get("X-Forwarded-For")),
log.Int("statusCode", scSrc.StatusCode()),
log.String("path", originalPath),
log.String("endpoint", endpoint),
log.String("endpoint", ctx.Endpoint()),
log.Int("applicationId", authData.ApplicationId),
log.String("applicationName", authData.AppName),
log.Int("adminId", ctx.AdminId()),
}
@@ -130,17 +124,9 @@ func Logger( // nolint:gocognit,funlen
fields = append(fields, log.ByteString("response", buf.ResponseBody()))
}
logger.Debug(ctx.Context(), "log request", fields...)
switch {
case scSrc.StatusCode() >= http.StatusInternalServerError:
logger.Error(ctx.Context(), "log request", fields...)
case scSrc.StatusCode() >= http.StatusBadRequest:
logger.Warn(ctx.Context(), "log request", fields...)
default:
logger.Debug(ctx.Context(), "log request", fields...)
}
return errors.WithMessage(err, "logger middleware error")
return err
})
}
}
+5 -7
View File
@@ -1,19 +1,17 @@
package middleware
import (
"isp-gate-service/request"
"time"
"isp-gate-service/request"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/metrics/http_metrics"
)
func Metrics(storage *http_metrics.ServerStorage) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
pathSchema := ctx.EndpointMeta().PathSchema
if pathSchema == "" {
endpoint := ctx.Endpoint()
if endpoint == "" {
return next.Handle(ctx)
}
@@ -22,10 +20,10 @@ func Metrics(storage *http_metrics.ServerStorage) Middleware {
start := time.Now()
err := next.Handle(ctx)
if err != nil {
return errors.WithMessage(err, "metrics middleware error")
return err
}
storage.ObserveDuration(r.Method, pathSchema, time.Since(start))
storage.ObserveDuration(r.Method, endpoint, time.Since(start))
return nil
})
+1 -1
View File
@@ -16,7 +16,7 @@ func (f HandlerFunc) Handle(ctx *request.Context) error {
type Middleware func(next Handler) Handler
// nolint:ireturn, modernize
// nolint:ireturn
func Chain(root Handler, middlewares ...Middleware) Handler {
for i := len(middlewares) - 1; i >= 0; i-- {
root = middlewares[i](root)
+11 -21
View File
@@ -9,39 +9,29 @@ import (
"github.com/txix-open/isp-kit/requestid"
)
func RequestId() Middleware {
const (
requestIdHeader = "x-request-id"
)
func RequestId(forwardClientRequestId bool, forwardReqIdByApp map[int]bool) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
requestId := requestid.Next()
clientRequestId := strings.TrimSpace(ctx.Request().Header.Get(requestIdHeader))
context := requestid.ToContext(ctx.Context(), requestId)
context = log.ToContext(context, log.String(requestid.LogKey, requestId))
ctx.SetContext(context)
return next.Handle(ctx)
})
}
}
func ClientRequestId(forwardClientRequestId bool, forwardReqIdByApp map[int]bool) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
requestId := requestid.FromContext(ctx.Context())
clientRequestId := strings.TrimSpace(ctx.Request().Header.Get(requestid.Header))
clientLogFields := make([]log.Field, 0, 1)
logFields := make([]log.Field, 0)
if clientRequestId != "" {
logFields = append(logFields, log.String("clientRequestId", clientRequestId))
authData, _ := ctx.GetAuthData()
if forwardClientRequestId || forwardReqIdByApp[authData.ApplicationId] {
requestId = clientRequestId
}
clientLogFields = append(clientLogFields, log.String("clientRequestId", clientRequestId))
}
logFields = append(logFields, log.String("requestId", requestId))
context := requestid.ToContext(ctx.Context(), requestId)
context = log.RewriteContextField(context, log.String(requestid.LogKey, requestId))
context = log.ToContext(context, clientLogFields...)
context = log.ToContext(context, logFields...)
ctx.SetContext(context)
return next.Handle(ctx)
+1 -5
View File
@@ -5,7 +5,7 @@ import (
"fmt"
"net/http"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
"isp-gate-service/domain"
"isp-gate-service/httperrors"
"isp-gate-service/request"
@@ -18,10 +18,6 @@ type Throttler interface {
func Throttling(throttler Throttler) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
if ctx.SkipAppAuth() {
return next.Handle(ctx)
}
authData, err := ctx.GetAuthData()
if err != nil {
return errors.WithMessage(err, "throttling: get auth data")
-61
View File
@@ -1,61 +0,0 @@
package middleware
import (
"net/http"
"isp-gate-service/domain"
"isp-gate-service/httperrors"
"isp-gate-service/request"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
)
type UserAuthenticator interface {
Authenticate(ctx *request.Context) (*domain.AuthenticateUserResponse, error)
}
func UserAuthenticate(authenticator UserAuthenticator, logger log.Logger) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
resp, err := authenticator.Authenticate(ctx)
switch {
case errors.Is(err, domain.ErrEmptyUserToken):
return httperrors.New(
http.StatusUnauthorized,
"user token required",
errors.New("customAuth: authenticate user: user token required"),
)
case errors.Is(err, domain.ErrInvalidUserToken):
return httperrors.New(
http.StatusUnauthorized,
"invalid user token",
errors.WithMessage(err, "customAuth: authenticate user: invalid user token"),
)
case err != nil:
return errors.WithMessage(err, "customAuth: authenticate user: authenticator error")
}
if resp.SkipUserAuth {
return next.Handle(ctx)
}
if !resp.Authenticated {
return httperrors.New(
http.StatusUnauthorized,
"invalid user token",
errors.Errorf("customAuth: authenticate user: authenticate: %s", resp.ErrorReason),
)
}
ctx.AuthenticateUser(*resp.AuthData)
if ctx.SkipAppAuth() {
logger.Debug(
ctx.Context(),
"skip app auth is set. All steps that require app auth data are skipped",
)
}
return next.Handle(ctx)
})
}
}
+23 -47
View File
@@ -5,16 +5,14 @@ import (
"context"
"encoding/base64"
"io"
"maps"
"net/http"
"strconv"
"strings"
"time"
"isp-gate-service/httperrors"
"isp-gate-service/request"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/grpc/isp"
@@ -33,7 +31,6 @@ func init() {
}
var (
// nolint: gochecknoglobals
codeMap = map[int]codes.Code{
http.StatusOK: codes.OK,
http.StatusRequestTimeout: codes.Canceled,
@@ -49,7 +46,6 @@ var (
http.StatusInternalServerError: codes.Internal,
http.StatusServiceUnavailable: codes.Unavailable,
}
// nolint: gochecknoglobals
inverseCodeMap = map[codes.Code]int{}
)
@@ -74,7 +70,26 @@ func (p Grpc) Handle(ctx *request.Context) error {
}
requestId := requestid.FromContext(ctx.Context())
md := p.writeMetadata(ctx)
md := metadata.MD{
grpc.ProxyMethodNameHeader: {ctx.Endpoint()},
requestid.Header: {requestId},
}
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)}
encodedAppName := base64.StdEncoding.EncodeToString([]byte(authData.AppName))
md[grpc.ApplicationNameHeader] = []string{encodedAppName}
if ctx.IsAdminAuthenticated() {
md[xAdminIdHeader] = []string{strconv.Itoa(ctx.AdminId())}
}
}
requestContext := metadata.NewOutgoingContext(ctx.Context(), md)
requestContext, cancel := context.WithTimeout(requestContext, p.timeout)
@@ -83,7 +98,7 @@ func (p Grpc) Handle(ctx *request.Context) error {
Body: &isp.Message_BytesBody{BytesBody: body},
})
if err != nil {
return p.handleError(err, ctx.ResponseWriter(), ctx.EndpointMeta().Endpoint)
return p.handleError(err, ctx.ResponseWriter(), ctx.Endpoint())
}
return p.writeResponse(http.StatusOK, result.GetBytesBody(), requestId, ctx.ResponseWriter())
@@ -123,7 +138,7 @@ func (p Grpc) handleError(err error, w http.ResponseWriter, endpoint string) err
)
}
func (p Grpc) writeProto(statusCode int, proto any, w http.ResponseWriter) error {
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")
@@ -152,42 +167,3 @@ func (p Grpc) codeToHttpStatus(code codes.Code) int {
return s
}
func (p Grpc) writeMetadata(ctx *request.Context) metadata.MD {
requestId := requestid.FromContext(ctx.Context())
md := metadata.MD{
grpc.ProxyMethodNameHeader: {ctx.EndpointMeta().Endpoint},
requestid.Header: {requestId},
}
if p.skipAuth {
return md
}
appAuthData, err := ctx.GetAuthData()
if err == nil {
md[grpc.SystemIdHeader] = []string{strconv.Itoa(appAuthData.SystemId)}
md[grpc.DomainIdHeader] = []string{strconv.Itoa(appAuthData.DomainId)}
md[grpc.ServiceIdHeader] = []string{strconv.Itoa(appAuthData.ServiceId)}
md[grpc.ApplicationIdHeader] = []string{strconv.Itoa(appAuthData.ApplicationId)}
encodedAppName := base64.StdEncoding.EncodeToString([]byte(appAuthData.AppName))
md[grpc.ApplicationNameHeader] = []string{encodedAppName}
}
userAuthData, err := ctx.GetUserAuthData()
if err == nil {
proxyHeaders := maps.Clone(userAuthData.ExtraHeaders)
proxyHeaders[userAuthData.IdentityHeader] = []string{userAuthData.Identity}
for header, values := range proxyHeaders {
header = strings.ToLower(header)
if strings.HasPrefix(header, "x-") {
md.Set(header, values...)
}
}
}
if ctx.IsAdminAuthenticated() {
md[xAdminIdHeader] = []string{strconv.Itoa(ctx.AdminId())}
}
return md
}
+23 -46
View File
@@ -1,7 +1,6 @@
package proxy
import (
"context"
"encoding/base64"
"fmt"
"net"
@@ -9,19 +8,18 @@ import (
"net/http/httputil"
"net/url"
"strconv"
"strings"
"time"
"isp-gate-service/httperrors"
"isp-gate-service/request"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/requestid"
"golang.org/x/net/context"
)
var (
// nolint: gochecknoglobals, mnd
httpTransport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: defaultTransportDialContext(&net.Dialer{
@@ -68,9 +66,11 @@ func (p Http) Handle(ctx *request.Context) error {
}
request := ctx.Request()
request.URL.Path = ctx.EndpointMeta().Endpoint
setHttpHeaders(ctx, request.Header, p.skipAuth)
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
@@ -81,9 +81,6 @@ func (p Http) Handle(ctx *request.Context) error {
errors.WithMessagef(err, "http proxy to %s", host),
)
}
if ctx.IsJsonUtf8CharsetEnabled() {
reverseProxy.ModifyResponse = addJsonUtf8Charset
}
context, cancel := context.WithTimeout(request.Context(), p.timeout)
defer cancel()
@@ -93,48 +90,28 @@ func (p Http) Handle(ctx *request.Context) error {
return resultError
}
func setHttpHeaders(ctx *request.Context, header http.Header, skipAuth bool) {
func setHttpHeaders(ctx *request.Context, header http.Header, skipAuth bool) error {
header.Set(requestid.Header, requestid.FromContext(ctx.Context()))
if skipAuth {
return
}
userAuthData, err := ctx.GetUserAuthData()
if err == nil {
for key, values := range userAuthData.ExtraHeaders {
for _, value := range values {
header.Add(key, value)
}
if !skipAuth {
authData, err := ctx.GetAuthData()
if err != nil {
return errors.WithMessage(err, "http: get auth data")
}
header.Set(userAuthData.IdentityHeader, userAuthData.Identity)
}
appAuthData, err := ctx.GetAuthData()
if err == nil {
header.Set(grpc.SystemIdHeader, strconv.Itoa(appAuthData.SystemId))
header.Set(grpc.DomainIdHeader, strconv.Itoa(appAuthData.DomainId))
header.Set(grpc.ServiceIdHeader, strconv.Itoa(appAuthData.ServiceId))
header.Set(grpc.ApplicationIdHeader, strconv.Itoa(appAuthData.ApplicationId))
encodedAppName := base64.StdEncoding.EncodeToString([]byte(appAuthData.AppName))
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))
encodedAppName := base64.StdEncoding.EncodeToString([]byte(authData.AppName))
header.Set(grpc.ApplicationNameHeader, encodedAppName) //nolint:canonicalheader
if ctx.IsAdminAuthenticated() {
header.Set(xAdminIdHeader, strconv.Itoa(ctx.AdminId())) //nolint:canonicalheader
} else {
header.Del(xAdminIdHeader) //nolint:canonicalheader
}
}
if ctx.IsAdminAuthenticated() {
header.Set(xAdminIdHeader, strconv.Itoa(ctx.AdminId())) //nolint:canonicalheader
} else {
header.Del(xAdminIdHeader) //nolint:canonicalheader
}
return nil
}
func defaultTransportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) {
return dialer.DialContext
}
func addJsonUtf8Charset(response *http.Response) error {
contentType := response.Header.Get("Content-Type")
if strings.EqualFold(contentType, "application/json") {
response.Header.Set("Content-Type", "application/json; charset=utf-8")
}
return nil
}
+5 -7
View File
@@ -6,12 +6,11 @@ import (
"net/url"
"time"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
"github.com/tomakado/websocketproxy"
"isp-gate-service/httperrors"
"isp-gate-service/request"
"github.com/gorilla/websocket"
"github.com/tomakado/websocketproxy"
"github.com/txix-open/isp-kit/errors"
)
type Ws struct {
@@ -39,14 +38,13 @@ func (ws Ws) Handle(ctx *request.Context) error {
}
request := ctx.Request()
request.URL.Path = ctx.EndpointMeta().Endpoint
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)
_ = setHttpHeaders(ctx, out, ws.skipAuth)
}
// nolint: mnd
proxy.Upgrader = &websocket.Upgrader{
HandshakeTimeout: 5 * time.Second,
ReadBufferSize: 1024,
+7 -7
View File
@@ -4,9 +4,9 @@ package repository
import (
"context"
"isp-gate-service/entity"
"isp-gate-service/domain"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/client"
)
@@ -23,10 +23,10 @@ func NewAdmin(cli *client.Client) Admin {
return Admin{cli: cli}
}
func (r Admin) Authenticate(ctx context.Context, token string) (*entity.AdminAuthenticateResponse, error) {
resp := entity.AdminAuthenticateResponse{}
func (r Admin) Authenticate(ctx context.Context, token string) (*domain.AdminAuthenticateResponse, error) {
resp := domain.AdminAuthenticateResponse{}
err := r.cli.Invoke(adminAuthenticate).
JsonRequestBody(entity.AuthenticateRequest{Token: token}).
JsonRequestBody(domain.AuthenticateRequest{Token: token}).
JsonResponseBody(&resp).
Do(ctx)
if err != nil {
@@ -36,9 +36,9 @@ func (r Admin) Authenticate(ctx context.Context, token string) (*entity.AdminAut
}
func (r Admin) Authorize(ctx context.Context, adminId int, permission string) (bool, error) {
resp := entity.AdminAuthorizeResponse{}
resp := domain.AdminAuthorizeResponse{}
err := r.cli.Invoke(adminAuthorize).
JsonRequestBody(entity.AdminAuthorizeRequest{AdminId: adminId, Permission: permission}).
JsonRequestBody(domain.AdminAuthorizeRequest{AdminId: adminId, Permission: permission}).
JsonResponseBody(&resp).
Do(ctx)
if err != nil {
+5 -7
View File
@@ -4,12 +4,10 @@ import (
"context"
"time"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/json"
"isp-gate-service/cache"
"isp-gate-service/domain"
"isp-gate-service/entity"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/json"
)
type AuthenticationCache struct {
@@ -24,13 +22,13 @@ func NewAuthenticationCache(duration time.Duration) AuthenticationCache {
}
}
func (r AuthenticationCache) Get(ctx context.Context, token string) (*entity.AppAuthData, error) {
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 := entity.AppAuthData{}
result := domain.AuthData{}
err := json.Unmarshal(data, &result)
if err != nil {
return nil, errors.WithMessage(err, "json unmarshal auth data")
@@ -39,7 +37,7 @@ func (r AuthenticationCache) Get(ctx context.Context, token string) (*entity.App
return &result, nil
}
func (r AuthenticationCache) Set(ctx context.Context, token string, data entity.AppAuthData) error {
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")
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"context"
"time"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/client"
"isp-gate-service/entity"
)
+8 -9
View File
@@ -4,10 +4,9 @@ package repository
import (
"context"
"isp-gate-service/entity"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/client"
"isp-gate-service/domain"
)
const (
@@ -25,10 +24,10 @@ func NewSystem(cli *client.Client) System {
}
}
func (r System) Authenticate(ctx context.Context, token string) (*entity.AuthenticateResponse, error) {
resp := entity.AuthenticateResponse{}
func (r System) Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error) {
resp := domain.AuthenticateResponse{}
err := r.cli.Invoke(authenticate).
JsonRequestBody(entity.AuthenticateRequest{Token: token}).
JsonRequestBody(domain.AuthenticateRequest{Token: token}).
JsonResponseBody(&resp).
Do(ctx)
if err != nil {
@@ -37,10 +36,10 @@ func (r System) Authenticate(ctx context.Context, token string) (*entity.Authent
return &resp, nil
}
func (r System) Authorize(ctx context.Context, req entity.AuthorizeRequest) (bool, error) {
resp := entity.AuthorizeResponse{}
func (r System) Authorize(ctx context.Context, applicationId int, endpoint string) (bool, error) {
resp := domain.AuthorizeResponse{}
err := r.cli.Invoke(authorize).
JsonRequestBody(req).
JsonRequestBody(domain.AuthorizeRequest{ApplicationId: applicationId, Endpoint: endpoint}).
JsonResponseBody(&resp).
Do(ctx)
if err != nil {
+4 -5
View File
@@ -5,10 +5,9 @@ import (
"time"
"isp-gate-service/domain"
"isp-gate-service/entity"
"github.com/pkg/errors"
"github.com/redis/go-redis/v9"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/json"
)
@@ -26,7 +25,7 @@ func NewRedisAuthCache(cli redis.UniversalClient, duration time.Duration, db int
}
}
func (r RedisAuthCache) Get(ctx context.Context, token string) (*entity.AppAuthData, error) {
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)
@@ -44,7 +43,7 @@ func (r RedisAuthCache) Get(ctx context.Context, token string) (*entity.AppAuthD
return nil, errors.WithMessage(err, "get")
}
result := entity.AppAuthData{}
result := domain.AuthData{}
err = json.Unmarshal([]byte(data), &result)
if err != nil {
return nil, errors.WithMessage(err, "json unmarshal auth data")
@@ -53,7 +52,7 @@ func (r RedisAuthCache) Get(ctx context.Context, token string) (*entity.AppAuthD
return &result, nil
}
func (r RedisAuthCache) Set(ctx context.Context, token string, data entity.AppAuthData) error {
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")
+1 -1
View File
@@ -5,8 +5,8 @@ import (
"fmt"
"time"
"github.com/pkg/errors"
"github.com/redis/go-redis/v9"
"github.com/txix-open/isp-kit/errors"
)
type RedisAuthzCache struct {
-51
View File
@@ -1,51 +0,0 @@
package repository
import (
"context"
"fmt"
"isp-gate-service/entity"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/http/httpclix"
"github.com/txix-open/isp-kit/lb"
"github.com/txix-open/isp-kit/metrics/http_metrics"
)
type UserAuth struct {
lb *lb.RoundRobin
cli *httpcli.Client
}
func NewUserAuth(lb *lb.RoundRobin) UserAuth {
return UserAuth{
lb: lb,
cli: httpclix.Default(),
}
}
func (r UserAuth) Authenticate(
ctx context.Context,
method string,
token string,
) (*entity.UserAuthenticateResponse, error) {
ctx = http_metrics.ClientEndpointToContext(ctx, method)
host, err := r.lb.Next()
if err != nil {
return nil, errors.WithMessage(err, "lb next")
}
endpoint := fmt.Sprintf("http://%s/%s", host, method)
resp := entity.UserAuthenticateResponse{}
err = r.cli.Post(endpoint).
JsonRequestBody(entity.UserAuthenticateRequest{
Token: token,
}).JsonResponseBody(&resp).
StatusCodeToError().
DoWithoutResponse(ctx)
if err != nil {
return nil, errors.WithMessagef(err, "http client invoke: %s", endpoint)
}
return &resp, nil
}
-64
View File
@@ -1,64 +0,0 @@
package repository
import (
"context"
"fmt"
"time"
"isp-gate-service/domain"
"isp-gate-service/entity"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/json"
)
type Cache interface {
Get(key string) ([]byte, bool)
Set(key string, data []byte, lifeTime time.Duration)
}
type UserAuthenticationCache struct {
cache Cache
}
func NewUserAuthenticationCache(cache Cache) UserAuthenticationCache {
return UserAuthenticationCache{
cache: cache,
}
}
func (r UserAuthenticationCache) Get(ctx context.Context, authMethodPath string, token string) (*entity.UserAuthData, error) {
data, ok := r.cache.Get(r.key(authMethodPath, token))
if !ok {
return nil, domain.ErrAuthenticationCacheMiss
}
result := entity.UserAuthData{}
err := json.Unmarshal(data, &result)
if err != nil {
return nil, errors.WithMessage(err, "json unmarshal auth data")
}
return &result, nil
}
func (r UserAuthenticationCache) Set(
ctx context.Context,
authMethodPath string,
token string,
data entity.UserAuthData,
duration time.Duration,
) error {
value, err := json.Marshal(data)
if err != nil {
return errors.WithMessage(err, "json marshal auth data")
}
r.cache.Set(r.key(authMethodPath, token), value, duration)
return nil
}
func (r UserAuthenticationCache) key(authModuleName string, token string) string {
return fmt.Sprintf("%s:%s", authModuleName, token)
}
+18 -44
View File
@@ -2,47 +2,45 @@ package request
import (
"context"
"isp-gate-service/domain"
"net/http"
"strings"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
)
var (
ErrNotAuthenticated = errors.New("not authenticated")
)
type AuthData struct {
AppName string
SystemId int
DomainId int
ServiceId int
ApplicationId int
}
type Context struct {
request *http.Request
responseWriter http.ResponseWriter
endpointMeta *domain.EndpointMeta
endpoint string
authenticated bool
authData *domain.AppAuthData
userAuthenticated bool
userAuthData *domain.UserAuthData
authData *AuthData
adminAuthenticated bool
adminId int
adminToken string
queryParams map[string]string
httpJsonUtf8Charset bool
}
func NewContext(
request *http.Request,
response http.ResponseWriter,
endpointMeta *domain.EndpointMeta,
) *Context {
func NewContext(request *http.Request, response http.ResponseWriter, endpoint string) *Context {
return &Context{
request: request,
responseWriter: response,
endpointMeta: endpointMeta,
endpoint: endpoint,
}
}
@@ -58,38 +56,22 @@ func (c *Context) SetResponseWriter(writer http.ResponseWriter) {
c.responseWriter = writer
}
func (c *Context) EndpointMeta() *domain.EndpointMeta {
return c.endpointMeta
func (c *Context) Endpoint() string {
return c.endpoint
}
func (c *Context) Authenticate(authData domain.AppAuthData) {
func (c *Context) Authenticate(authData AuthData) {
c.authenticated = true
c.authData = &authData
}
func (c *Context) GetAuthData() (domain.AppAuthData, error) {
func (c *Context) GetAuthData() (AuthData, error) {
if !c.authenticated {
return domain.AppAuthData{}, ErrNotAuthenticated
return AuthData{}, ErrNotAuthenticated
}
return *c.authData, nil
}
func (c *Context) AuthenticateUser(authData domain.UserAuthData) {
c.userAuthenticated = true
c.userAuthData = &authData
}
func (c *Context) GetUserAuthData() (domain.UserAuthData, error) {
if !c.userAuthenticated {
return domain.UserAuthData{}, ErrNotAuthenticated
}
return *c.userAuthData, nil
}
func (c *Context) SkipAppAuth() bool {
return c.userAuthData != nil && c.userAuthData.SkipAppAuth
}
func (c *Context) IsAdminAuthenticated() bool {
return c.adminAuthenticated
}
@@ -116,14 +98,6 @@ func (c *Context) SetContext(ctx context.Context) {
c.request = c.request.WithContext(ctx)
}
func (c *Context) EnableHttpJsonUtf8Charset(enable bool) {
c.httpJsonUtf8Charset = enable
}
func (c *Context) IsJsonUtf8CharsetEnabled() bool {
return c.httpJsonUtf8Charset
}
func (c *Context) Param(name string) string {
value := c.request.Header.Get(name)
if value != "" {
+50 -91
View File
@@ -2,126 +2,85 @@ package routes
import (
"context"
"isp-gate-service/domain"
"fmt"
"isp-gate-service/middleware"
"net/http"
"strings"
"github.com/julienschmidt/httprouter"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/log"
)
type Routes struct {
logger log.Logger
allHttpMethods []string
router *httprouter.Router
allEndpoints map[string]bool
innerEndpoints map[string]bool
requiredPermissions map[string]string
}
func NewRoutes(logger log.Logger) *Routes {
func NewRoutes() *Routes {
return &Routes{
logger: logger,
allHttpMethods: []string{
http.MethodGet,
http.MethodHead,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
http.MethodConnect,
http.MethodOptions,
http.MethodTrace,
},
router: httprouter.New(),
allEndpoints: make(map[string]bool),
innerEndpoints: make(map[string]bool),
requiredPermissions: make(map[string]string),
}
}
func (s *Routes) ReceiveRoutes(ctx context.Context, routes cluster.RoutingConfig) error {
router := httprouter.New()
newAllEndpoints := make(map[string]bool)
newInnerMethods := make(map[string]bool)
newRequiredPermissions := make(map[string]string)
for _, backend := range routes {
for _, descriptor := range backend.Endpoints {
path := normalizeDescriptorPath(descriptor.Path)
if descriptor.HttpMethod != "" {
s.registerEndpoint(router, backend.ModuleName, descriptor.HttpMethod, path, descriptor)
} else {
for _, httpMethod := range s.allHttpMethods {
s.registerEndpoint(router, backend.ModuleName, httpMethod, path, descriptor)
}
for _, v := range backend.Endpoints {
newAllEndpoints[v.Path] = true
if v.Inner {
newInnerMethods[v.Path] = true
}
perm, ok := cluster.GetRequiredAdminPermission(v)
if ok {
newRequiredPermissions[v.Path] = perm
}
}
}
s.router = router
s.allEndpoints = newAllEndpoints
s.innerEndpoints = newInnerMethods
s.requiredPermissions = newRequiredPermissions
return nil
}
func (s *Routes) ResolveEndpoint(method string, path string, cfg middleware.EntryPointConfig) (*domain.EndpointMeta, error) {
lookupPath, metaEndpoint := s.GetPaths(path, cfg)
handler, params, _ := s.router.Lookup(method, lookupPath)
if handler == nil {
if cfg.ErrorOnUnknownEndpoint {
return nil, errors.Errorf("unknown endpoint '%s'", lookupPath)
}
return &domain.EndpointMeta{
Endpoint: metaEndpoint,
NormalizedEndpoint: normalizePath(metaEndpoint),
}, nil
func (s *Routes) ResolveEndpoint(path string, cfg middleware.EntryPointConfig) string {
if cfg.WithPrefix {
return path
}
req, _ := http.NewRequestWithContext(context.Background(), method, lookupPath, nil)
handler(nil, req, params)
prefix := fmt.Sprintf("%s/", cfg.PathPrefix)
noPrefixPath := strings.TrimPrefix(path, prefix)
ok := s.allEndpoints[noPrefixPath]
if ok {
return noPrefixPath
}
meta := domain.EndpointMetaFromContext(req.Context())
meta.Endpoint = metaEndpoint
meta.NormalizedEndpoint = normalizePath(meta.PathSchema)
return &meta, nil
invertedLeadingSlash := invertLeadingSlash(noPrefixPath)
ok = s.allEndpoints[invertedLeadingSlash]
if ok {
return invertedLeadingSlash
}
return noPrefixPath // pdp-webapi-service(анонсирует вот такой ендпоинт GET /api/:token/profile/me/:blocks) hack =(
}
func (s *Routes) GetPaths(path string, cfg middleware.EntryPointConfig) (string, string) {
lookupPath := path
if !cfg.WithPrefix {
lookupPath = strings.TrimPrefix(lookupPath, cfg.PathPrefix)
}
metaEndpoint := lookupPath
if !cfg.WithLendingSlash {
metaEndpoint = strings.TrimLeft(metaEndpoint, "/")
}
return lookupPath, metaEndpoint
func (s *Routes) IsInnerEndpoint(endpoint string) bool {
return s.innerEndpoints[endpoint]
}
func (s *Routes) registerEndpoint(
router *httprouter.Router,
moduleName string,
httpMethod string,
path string,
descriptor cluster.EndpointDescriptor,
) {
defer func() {
_ = recover()
}()
requiredAdminPerm, _ := cluster.GetRequiredAdminPermission(descriptor)
meta := domain.EndpointMeta{
Inner: descriptor.Inner,
UserAuthRequired: descriptor.UserAuthRequired,
ModuleName: moduleName,
RequiredAdminPermission: requiredAdminPerm,
PathSchema: descriptor.Path,
}
handler := func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
ctx := meta.ToContext(r.Context())
// хак для передачи метадаты обратно в код
*r = *r.WithContext(ctx)
}
router.Handle(httpMethod, path, handler)
func (s *Routes) RequiredAdminPermission(endpoint string) (string, bool) {
perm, ok := s.requiredPermissions[endpoint]
return perm, ok
}
func normalizePath(path string) string {
return strings.TrimPrefix(path, "/")
func invertLeadingSlash(path string) string {
path, withoutSlash := strings.CutPrefix(path, "/")
if withoutSlash {
return path
}
return "/" + path
}
-16
View File
@@ -1,16 +0,0 @@
package routes
import "strings"
// nolint:mnd
func normalizeDescriptorPath(path string) string {
pathParts := strings.Split(path, " ")
// хак для endpoint'ов с GET /path
if len(pathParts) == 2 {
path = pathParts[1]
}
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
return path
}
+3 -8
View File
@@ -4,13 +4,12 @@ import (
"context"
"isp-gate-service/domain"
"isp-gate-service/entity"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
)
type AdminAuth interface {
Authenticate(ctx context.Context, token string) (*entity.AdminAuthenticateResponse, error)
Authenticate(ctx context.Context, token string) (*domain.AdminAuthenticateResponse, error)
Authorize(ctx context.Context, adminId int, permission string) (bool, error)
}
@@ -31,11 +30,7 @@ func (s Admin) AdminAuthenticate(ctx context.Context, token string) (*domain.Adm
if err != nil {
return nil, errors.WithMessage(err, "get admin token data from admin service")
}
return &domain.AdminAuthenticateResponse{
Authenticated: resp.Authenticated,
ErrorReason: resp.ErrorReason,
AdminId: resp.AdminId,
}, nil
return resp, nil
}
func (s Admin) AdminAuthorize(ctx context.Context, adminId int, permission string) (bool, error) {
+19 -46
View File
@@ -2,81 +2,54 @@ package service
import (
"context"
"isp-gate-service/domain"
"isp-gate-service/entity"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
"isp-gate-service/domain"
)
type AuthenticationCache interface {
Get(ctx context.Context, token string) (*entity.AppAuthData, error)
Set(ctx context.Context, token string, data entity.AppAuthData) error
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) (*entity.AuthenticateResponse, error)
Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error)
}
type Authentication struct {
type Auth struct {
cache AuthenticationCache
repo AuthenticationRepo
}
func NewAuthentication(
cache AuthenticationCache,
repo AuthenticationRepo,
) Authentication {
return Authentication{
func NewAuthentication(cache AuthenticationCache, repo AuthenticationRepo) Auth {
return Auth{
cache: cache,
repo: repo,
}
}
func (s Authentication) Authenticate(ctx context.Context, token string) (*domain.AuthenticateAppResponse, error) {
func (s Auth) Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error) {
authData, err := s.cache.Get(ctx, token)
switch {
case errors.Is(err, domain.ErrAuthenticationCacheMiss):
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 s.convertAuthReponse(resp), nil
return resp, nil
}
err = s.cache.Set(ctx, token, *resp.AuthData)
if err != nil {
return nil, errors.WithMessage(err, "auth cache set")
}
return s.convertAuthReponse(resp), nil
case err != nil:
return resp, nil
}
if err != nil {
return nil, errors.WithMessage(err, "auth cache get")
default:
return &domain.AuthenticateAppResponse{
Authenticated: true,
ErrorReason: "",
AuthData: s.convertAuthData(authData),
}, nil
}
}
func (s Authentication) convertAuthReponse(resp *entity.AuthenticateResponse) *domain.AuthenticateAppResponse {
return &domain.AuthenticateAppResponse{
Authenticated: resp.Authenticated,
ErrorReason: resp.ErrorReason,
AuthData: s.convertAuthData(resp.AuthData),
}
}
func (Authentication) convertAuthData(authData *entity.AppAuthData) *domain.AppAuthData {
if authData == nil {
return nil
}
return &domain.AppAuthData{
AppName: authData.AppName,
SystemId: authData.SystemId,
DomainId: authData.DomainId,
ServiceId: authData.ServiceId,
ApplicationId: authData.ApplicationId,
}
return &domain.AuthenticateResponse{
Authenticated: true,
ErrorReason: "",
AuthData: authData,
}, nil
}
+7 -14
View File
@@ -2,10 +2,8 @@ package service
import (
"context"
"fmt"
"isp-gate-service/entity"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
)
type AuthorizationCache interface {
@@ -14,7 +12,7 @@ type AuthorizationCache interface {
}
type AuthorizationRepo interface {
Authorize(ctx context.Context, req entity.AuthorizeRequest) (bool, error)
Authorize(ctx context.Context, applicationId int, endpoint string) (bool, error)
}
type Authorization struct {
@@ -29,26 +27,21 @@ func NewAuthorization(cache AuthorizationCache, repo AuthorizationRepo) Authoriz
}
}
func (s Authorization) Authorize(ctx context.Context, applicationId int, httpMethod string, endpoint string) (bool, error) {
cacheKey := fmt.Sprintf("%s %s", httpMethod, endpoint)
ok, err := s.cache.Get(ctx, applicationId, cacheKey)
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 true, nil
return ok, nil
}
ok, err = s.repo.Authorize(ctx, entity.AuthorizeRequest{
ApplicationId: applicationId,
HttpMethod: httpMethod,
Endpoint: endpoint,
})
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, cacheKey)
err = s.cache.SetAuthorized(ctx, applicationId, endpoint)
if err != nil {
return false, errors.WithMessagef(err, "authz cache set")
}
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"fmt"
"time"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
"isp-gate-service/conf"
)
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"context"
"fmt"
"github.com/txix-open/isp-kit/errors"
"github.com/pkg/errors"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/entity"
-47
View File
@@ -1,47 +0,0 @@
package token_provider
import (
"isp-gate-service/conf"
"isp-gate-service/request"
"net/http"
"strings"
"github.com/txix-open/isp-kit/errors"
)
type CookieProvider struct {
name string
cookieName string
validate bool
}
func NewCookieProvider(name string, cfg conf.CookieTokenProvider) CookieProvider {
return CookieProvider{
name: name,
cookieName: cfg.CookieName,
validate: cfg.Validate,
}
}
func (p CookieProvider) GetName() string {
return p.name
}
func (p CookieProvider) ExtractToken(ctx *request.Context) (string, error) {
cookie, err := ctx.Request().Cookie(p.cookieName)
switch {
case errors.Is(err, http.ErrNoCookie):
return "", nil
case err != nil:
return "", errors.WithMessagef(err, "get cookie with name '%s'", p.cookieName)
}
if !p.validate {
return strings.TrimSpace(cookie.Value), nil
}
err = cookie.Valid()
if err != nil {
return "", errors.WithMessagef(err, "validate cookie with name '%s'", p.cookieName)
}
return strings.TrimSpace(cookie.Value), nil
}
-28
View File
@@ -1,28 +0,0 @@
package token_provider
import (
"isp-gate-service/conf"
"isp-gate-service/request"
"strings"
)
type HeaderProvider struct {
name string
headerName string
}
func NewHeaderProvider(name string, cfg conf.HeaderTokenProvider) HeaderProvider {
return HeaderProvider{
name: name,
headerName: cfg.HeaderName,
}
}
func (p HeaderProvider) GetName() string {
return p.name
}
func (p HeaderProvider) ExtractToken(ctx *request.Context) (string, error) {
value := ctx.Request().Header.Get(p.headerName)
return strings.TrimSpace(value), nil
}
-234
View File
@@ -1,234 +0,0 @@
// nolint:ireturn
package service
import (
"context"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/entity"
"isp-gate-service/request"
"isp-gate-service/service/token_provider"
"strings"
"time"
"github.com/txix-open/isp-kit/errors"
)
type UserAuthenticationCache interface {
Get(ctx context.Context, authEndpoint string, token string) (*entity.UserAuthData, error)
Set(ctx context.Context, authEndpoint string, token string, data entity.UserAuthData, duration time.Duration) error
}
type UserAuthenticationRepo interface {
Authenticate(ctx context.Context, authEndpoint string, token string) (*entity.UserAuthenticateResponse, error)
}
type TokenProvider interface {
GetName() string
ExtractToken(ctx *request.Context) (string, error)
}
type userAuthSetting struct {
tokenProviders []TokenProvider
authEndpoint string
authCacheDuration time.Duration
skipAppAuth bool
}
type UserAuthentication struct {
cache UserAuthenticationCache
repo UserAuthenticationRepo
settingsByModuleName map[string]userAuthSetting
}
func NewUserAuthentication(
cfg conf.CustomAuth,
cache UserAuthenticationCache,
repo UserAuthenticationRepo,
) (UserAuthentication, error) {
tokenProviders := make(map[string]TokenProvider, len(cfg.TokenProviders))
for i, provider := range cfg.TokenProviders {
_, ok := tokenProviders[provider.Name]
if ok {
return UserAuthentication{}, errors.Errorf("token provider name must have unique name, found duplicate at [%d] with name '%s'", i, provider.Name)
}
tokenProvider, err := tokenProviderFromConfig(provider)
if err != nil {
return UserAuthentication{}, errors.WithMessagef(err, "init token provider with name '%s'", provider.Name)
}
tokenProviders[provider.Name] = tokenProvider
}
settingsByModuleName := make(map[string]userAuthSetting, len(cfg.UserAuthSettings))
for _, setting := range cfg.UserAuthSettings {
settingTokenProviders := make([]TokenProvider, 0, len(setting.TokenProviders))
for _, providerName := range setting.TokenProviders {
tokenProvider, ok := tokenProviders[providerName]
if !ok {
return UserAuthentication{},
errors.Errorf("modules with names'[%s]' has unknown token provider '%s'",
strings.Join(setting.ModuleNameList, ","),
providerName,
)
}
settingTokenProviders = append(settingTokenProviders, tokenProvider)
}
cacheDuration := time.Duration(setting.CacheDataInSec) * time.Second
for _, moduleName := range setting.ModuleNameList {
_, ok := settingsByModuleName[moduleName]
if ok {
return UserAuthentication{},
errors.Errorf("setting unique violation, setting for module with name '%s' already present",
moduleName,
)
}
settingsByModuleName[moduleName] = userAuthSetting{
tokenProviders: settingTokenProviders,
authEndpoint: setting.AuthenticateEndpoint,
authCacheDuration: cacheDuration,
skipAppAuth: setting.SkipAppAuth,
}
}
}
return UserAuthentication{
cache: cache,
repo: repo,
settingsByModuleName: settingsByModuleName,
}, nil
}
func (s UserAuthentication) Authenticate(ctx *request.Context) (*domain.AuthenticateUserResponse, error) {
meta := ctx.EndpointMeta()
if !meta.UserAuthRequired {
return &domain.AuthenticateUserResponse{
SkipUserAuth: true,
}, nil
}
setting, ok := s.settingsByModuleName[meta.ModuleName]
if !ok {
return nil, errors.WithMessagef(domain.ErrUserAuthSettingNotFound,
"setting for module '%s' and endpoint '%s' not found",
meta.ModuleName, meta.Endpoint,
)
}
token, err := s.extractToken(ctx, setting.tokenProviders)
if err != nil {
return nil, errors.WithMessage(err, "extract user token")
}
resp, err := s.authenticate(
ctx.Context(),
setting,
token,
)
if err != nil {
return nil, errors.WithMessage(err, "auth")
}
return resp, nil
}
func (s UserAuthentication) extractToken(ctx *request.Context, providers []TokenProvider) (string, error) {
for _, provider := range providers {
token, err := provider.ExtractToken(ctx)
if err != nil {
return "", errors.WithMessagef(
domain.ErrInvalidUserToken,
"extract token by '%s' error: %s",
provider.GetName(),
err.Error(),
)
}
if token != "" {
return token, nil
}
}
return "", domain.ErrEmptyUserToken
}
func (s UserAuthentication) authenticate(
ctx context.Context,
setting userAuthSetting,
token string,
) (*domain.AuthenticateUserResponse, error) {
if setting.authCacheDuration <= 0 {
resp, err := s.repo.Authenticate(ctx, setting.authEndpoint, token)
if err != nil {
return nil, errors.WithMessage(err, "auth repo authenticate")
}
return s.convertAuthResponse(resp, setting.skipAppAuth), nil
}
authData, err := s.cache.Get(ctx, setting.authEndpoint, token)
switch {
case errors.Is(err, domain.ErrAuthenticationCacheMiss):
resp, err := s.repo.Authenticate(ctx, setting.authEndpoint, token)
if err != nil {
return nil, errors.WithMessage(err, "auth repo authenticate")
}
if !resp.Authenticated {
return s.convertAuthResponse(resp, setting.skipAppAuth), nil
}
err = s.cache.Set(
ctx,
setting.authEndpoint,
token,
*resp.AuthData,
setting.authCacheDuration,
)
if err != nil {
return nil, errors.WithMessage(err, "auth cache set")
}
return s.convertAuthResponse(resp, setting.skipAppAuth), nil
case err != nil:
return nil, errors.WithMessage(err, "auth cache get")
default:
return &domain.AuthenticateUserResponse{
Authenticated: true,
ErrorReason: "",
AuthData: s.convertAuthData(authData, setting.skipAppAuth),
}, nil
}
}
func (s UserAuthentication) convertAuthResponse(resp *entity.UserAuthenticateResponse, skipAppAuth bool) *domain.AuthenticateUserResponse {
return &domain.AuthenticateUserResponse{
Authenticated: resp.Authenticated,
ErrorReason: resp.ErrorReason,
AuthData: s.convertAuthData(resp.AuthData, skipAppAuth),
}
}
func (UserAuthentication) convertAuthData(authData *entity.UserAuthData, skipAppAuth bool) *domain.UserAuthData {
if authData == nil {
return nil
}
return &domain.UserAuthData{
Identity: authData.Identity,
IdentityHeader: authData.IdentityHeader,
ExtraHeaders: authData.ExtraHeaders,
SkipAppAuth: skipAppAuth,
}
}
func tokenProviderFromConfig(cfg conf.TokenProvider) (TokenProvider, error) {
switch cfg.Type {
case conf.HeaderTokenProviderType:
if cfg.HeaderProvider == nil {
return nil, errors.Errorf("token method '%s' has empty header provider", cfg.Name)
}
return token_provider.NewHeaderProvider(cfg.Name, *cfg.HeaderProvider), nil
case conf.CookieTokenProviderType:
if cfg.CookieProvider == nil {
return nil, errors.Errorf("token method '%s' has empty cookie provider", cfg.Name)
}
return token_provider.NewCookieProvider(cfg.Name, *cfg.CookieProvider), nil
default:
return nil, errors.Errorf("unknown token provider with type '%s'", cfg.Type)
}
}
+37 -312
View File
@@ -1,4 +1,5 @@
package tests_test
// nolint:canonicalheader
package tests
import (
"context"
@@ -11,20 +12,15 @@ import (
"time"
"isp-gate-service/assembly"
"isp-gate-service/cache"
"isp-gate-service/conf"
"isp-gate-service/entity"
"isp-gate-service/domain"
"isp-gate-service/routes"
"github.com/stretchr/testify/require"
"github.com/txix-open/etp/v3"
"github.com/txix-open/etp/v3/msg"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/http/endpoint"
"github.com/txix-open/isp-kit/http/endpoint/httplog"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/http/router"
"github.com/txix-open/isp-kit/test/fake"
"github.com/google/uuid"
"github.com/stretchr/testify/suite"
@@ -82,7 +78,7 @@ func (s *HappyPathTestSuite) TestGrpcProxy() {
logger, err := log.New(log.WithLevel(log.DebugLevel))
require.NoError(err)
routes := routes.NewRoutes(logger)
routes := routes.NewRoutes()
err = routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{
Endpoints: []cluster.EndpointDescriptor{{
Path: "endpoint",
@@ -90,7 +86,7 @@ func (s *HappyPathTestSuite) TestGrpcProxy() {
}})
require.NoError(err)
locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil, nil, nil)
locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil)
locations := []conf.Location{{
SkipAuth: false,
@@ -105,14 +101,14 @@ func (s *HappyPathTestSuite) TestGrpcProxy() {
cli := httpcli.New()
req := request{Id: uuid.New().String()}
resp := response{}
err = cli.Post(srv.URL+"/api/endpoint").
_, 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().
DoWithoutResponse(s.T().Context())
Do(context.Background())
require.NoError(err)
require.EqualValues(req.Id, resp.Id)
}
@@ -132,7 +128,7 @@ func (s *HappyPathTestSuite) TestHttpProxy() {
rr := lb.NewRoundRobin([]string{targetUrl.Host})
targetClients := map[string]*lb.RoundRobin{"target": rr}
routes := routes.NewRoutes(test.Logger())
routes := routes.NewRoutes()
err = routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{
Endpoints: []cluster.EndpointDescriptor{{
Path: "/endpoint",
@@ -140,7 +136,7 @@ func (s *HappyPathTestSuite) TestHttpProxy() {
}})
require.NoError(err)
locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes, systemCli, adminCli, nil, nil, nil)
locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes, systemCli, adminCli, nil)
locations := []conf.Location{{
SkipAuth: false,
PathPrefix: "/api",
@@ -154,19 +150,19 @@ func (s *HappyPathTestSuite) TestHttpProxy() {
cli := httpcli.New()
req := request{Id: uuid.New().String()}
resp := response{}
err = cli.Post(srv.URL+"/api/endpoint").
_, 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().
DoWithoutResponse(s.T().Context())
Do(context.Background())
require.NoError(err)
require.EqualValues(req.Id, resp.Id)
}
func (s *HappyPathTestSuite) TestWsProxy() { // nolint:funlen
func (s *HappyPathTestSuite) TestWsProxy() { // nolint: funlen
test, require := test.New(s.T())
config, systemCli, adminCli := s.commonDependencies(test)
@@ -188,7 +184,7 @@ func (s *HappyPathTestSuite) TestWsProxy() { // nolint:funlen
rr := lb.NewRoundRobin([]string{targetUrl.Host})
targetClients := map[string]*lb.RoundRobin{"target": rr}
routes := routes.NewRoutes(test.Logger())
routes := routes.NewRoutes()
err = routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{
Endpoints: []cluster.EndpointDescriptor{{
Path: "/service",
@@ -196,7 +192,7 @@ func (s *HappyPathTestSuite) TestWsProxy() { // nolint:funlen
}})
require.NoError(err)
locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes, systemCli, adminCli, nil, nil, nil)
locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes, systemCli, adminCli, nil)
locations := []conf.Location{{
SkipAuth: false,
PathPrefix: "/ws",
@@ -238,7 +234,7 @@ type wsEventHandlerMock struct {
func (s wsEventHandlerMock) Handle(_ context.Context, conn *etp.Conn, event msg.Event) []byte {
headers := conn.HttpRequest().Header
ctx := requestid.ToContext(context.Background(), headers.Get("x-request-id")) // nolint: canonicalheader
ctx := requestid.ToContext(context.Background(), headers.Get("x-request-id"))
assertHeaders(s.require, s.requestId, ctx, headers)
require.EqualValues(s.t, "data", event.Data)
return []byte("world")
@@ -255,8 +251,8 @@ func (s *HappyPathTestSuite) TestAdminAuthorization() {
targetClients := map[string]*client.Client{"target": targetCli}
logger, err := log.New(log.WithLevel(log.DebugLevel))
require.NoError(err)
routes := routes.NewRoutes(logger)
locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil, nil, nil)
routes := routes.NewRoutes()
locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil)
locations := []conf.Location{{
SkipAuth: false,
@@ -285,299 +281,28 @@ func (s *HappyPathTestSuite) TestAdminAuthorization() {
cli := httpcli.New()
req := request{Id: uuid.New().String()}
resp := response{}
err = cli.Post(srv.URL+"/api/endpoint").
_, err = cli.Post(srv.URL+"/api/endpoint").
Header("x-application-token", "token").
Header("x-auth-admin", "mock-token").
JsonRequestBody(req).
JsonResponseBody(&resp).
StatusCodeToError().
DoWithoutResponse(s.T().Context())
Do(context.Background())
require.NoError(err)
require.EqualValues(req.Id, resp.Id)
err = cli.Post(srv.URL+"/api/failed_endpoint").
_, err = cli.Post(srv.URL+"/api/failed_endpoint").
Header("x-application-token", "token").
Header("x-auth-admin", "mock-token").
JsonRequestBody(req).
JsonResponseBody(&resp).
StatusCodeToError().
DoWithoutResponse(s.T().Context())
Do(context.Background())
errResp := httpcli.ErrorResponse{}
require.ErrorAs(err, &errResp)
require.EqualValues(http.StatusForbidden, errResp.StatusCode)
}
func (s *HappyPathTestSuite) TestUserAuthorization() { // nolint:funlen
test, require := test.New(s.T())
config, systemCli, adminCli := s.commonDependencies(test)
userAuthData := fake.It[entity.UserAuthData]()
userAuthData.IdentityHeader = "x-" + userAuthData.IdentityHeader
targetService, targetCli := grpct.NewMock(test)
targetService.Mock("endpoint", func(ctx context.Context, authData grpc.AuthData, req request) response {
md, ok := metadata.FromIncomingContext(ctx)
require.True(ok)
require.ElementsMatch([]string{userAuthData.Identity}, md.Get(userAuthData.IdentityHeader))
return response{Id: req.Id}
})
targetService.Mock("failed_auth_endpoint", func(ctx context.Context, authData grpc.AuthData, req request) response {
return response{Id: req.Id}
})
routerMux := router.New()
defaultWrapper := endpoint.DefaultWrapper(
test.Logger(),
httplog.Noop(),
)
userAuthToken := fake.It[string]()
routerMux.POST("/test-user-auth/authenticate",
defaultWrapper.Endpoint(func(req entity.UserAuthenticateRequest) entity.UserAuthenticateResponse {
require.Equal(userAuthToken, req.Token)
return entity.UserAuthenticateResponse{
Authenticated: true,
AuthData: &userAuthData,
}
}))
routerMux.POST("/failed-user-auth/authenticate",
defaultWrapper.Endpoint(func(req entity.UserAuthenticateRequest) entity.UserAuthenticateResponse {
require.Equal(userAuthToken, req.Token)
return entity.UserAuthenticateResponse{
Authenticated: false,
ErrorReason: "test fail",
}
}))
routerMock := httptest.NewServer(routerMux)
targetUrl, err := url.Parse(routerMock.URL)
require.NoError(err)
rr := lb.NewRoundRobin([]string{targetUrl.Host})
targetClients := map[string]*client.Client{"target": targetCli}
logger, err := log.New(log.WithLevel(log.DebugLevel))
require.NoError(err)
routes := routes.NewRoutes(logger)
locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil, rr, cache.New())
locations := []conf.Location{{
SkipAuth: false,
PathPrefix: "/api",
Protocol: "grpc",
TargetModule: "target",
}}
config.CustomAuth = conf.CustomAuth{
TokenProviders: []conf.TokenProvider{
{
Name: "test_provider",
Type: conf.HeaderTokenProviderType,
HeaderProvider: &conf.HeaderTokenProvider{
HeaderName: "test-token-header",
},
},
},
UserAuthSettings: []conf.UserAuthSetting{
{
ModuleNameList: []string{"target"},
TokenProviders: []string{"test_provider"},
AuthenticateEndpoint: "test-user-auth/authenticate",
},
{
ModuleNameList: []string{"target2"},
TokenProviders: []string{"test_provider"},
AuthenticateEndpoint: "failed-user-auth/authenticate",
},
},
}
handler, err := locator.Handler(config, locations)
require.NoError(err)
err = routes.ReceiveRoutes(context.Background(), cluster.RoutingConfig{
{
ModuleName: "target",
Endpoints: []cluster.EndpointDescriptor{{
Path: "endpoint",
Inner: true,
UserAuthRequired: true,
},
},
},
{
ModuleName: "target2",
Endpoints: []cluster.EndpointDescriptor{
{
Path: "failed_auth_endpoint",
Inner: true,
UserAuthRequired: true,
}, {
Path: "failed_endpoint",
Inner: true,
UserAuthRequired: true,
},
},
},
})
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("test-token-header", userAuthToken).
Header("x-auth-admin", "mock-token").
JsonRequestBody(req).
JsonResponseBody(&resp).
StatusCodeToError().
DoWithoutResponse(s.T().Context())
require.NoError(err)
require.EqualValues(req.Id, resp.Id)
err = cli.Post(srv.URL+"/api/failed_auth_endpoint").
Header("x-application-token", "token").
Header("test-token-header", userAuthToken).
Header("x-auth-admin", "mock-token").
JsonRequestBody(req).
JsonResponseBody(&resp).
StatusCodeToError().
DoWithoutResponse(s.T().Context())
errResp := httpcli.ErrorResponse{}
require.ErrorAs(err, &errResp)
require.EqualValues(http.StatusUnauthorized, errResp.StatusCode)
}
func (s *HappyPathTestSuite) TestUserAuthorization_SkipAppAuth() { // nolint:funlen
test, require := test.New(s.T())
config, _, adminCli := s.commonDependencies(test)
systemService, systemCli := grpct.NewMock(test)
systemService.Mock("system/secure/authenticate", func() entity.AuthenticateResponse {
return entity.AuthenticateResponse{
Authenticated: false,
ErrorReason: "",
}
}).Mock("system/secure/authorize", func() entity.AuthorizeResponse {
return entity.AuthorizeResponse{Authorized: false}
})
userAuthData := fake.It[entity.UserAuthData]()
userAuthData.IdentityHeader = "x-" + userAuthData.IdentityHeader
targetService, targetCli := grpct.NewMock(test)
targetService.Mock("endpoint", func(ctx context.Context, authData grpc.AuthData, req request) response {
md, ok := metadata.FromIncomingContext(ctx)
require.True(ok)
require.ElementsMatch([]string{userAuthData.Identity}, md.Get(userAuthData.IdentityHeader))
return response{Id: req.Id}
})
routerMux := router.New()
defaultWrapper := endpoint.DefaultWrapper(
test.Logger(),
httplog.Noop(),
)
userAuthToken := fake.It[string]()
routerMux.POST("/test-user-auth/authenticate",
defaultWrapper.Endpoint(func(req entity.UserAuthenticateRequest) entity.UserAuthenticateResponse {
require.Equal(userAuthToken, req.Token)
return entity.UserAuthenticateResponse{
Authenticated: true,
AuthData: &userAuthData,
}
}))
routerMock := httptest.NewServer(routerMux)
targetUrl, err := url.Parse(routerMock.URL)
require.NoError(err)
rr := lb.NewRoundRobin([]string{targetUrl.Host})
targetClients := map[string]*client.Client{"target": targetCli}
logger, err := log.New(log.WithLevel(log.DebugLevel))
require.NoError(err)
routes := routes.NewRoutes(logger)
locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil, rr, cache.New())
locations := []conf.Location{{
SkipAuth: false,
PathPrefix: "/api",
Protocol: "grpc",
TargetModule: "target",
}}
config.CustomAuth = conf.CustomAuth{
TokenProviders: []conf.TokenProvider{
{
Name: "test_provider",
Type: conf.HeaderTokenProviderType,
HeaderProvider: &conf.HeaderTokenProvider{
HeaderName: "test-token-header",
},
},
},
UserAuthSettings: []conf.UserAuthSetting{
{
ModuleNameList: []string{"target"},
TokenProviders: []string{"test_provider"},
AuthenticateEndpoint: "test-user-auth/authenticate",
SkipAppAuth: true,
},
{
ModuleNameList: []string{"target2"},
TokenProviders: []string{"test_provider"},
AuthenticateEndpoint: "test-user-auth/authenticate",
},
},
}
handler, err := locator.Handler(config, locations)
require.NoError(err)
err = routes.ReceiveRoutes(context.Background(), cluster.RoutingConfig{{
ModuleName: "target",
Endpoints: []cluster.EndpointDescriptor{{
Path: "endpoint",
Inner: true,
UserAuthRequired: true,
}}},
{
ModuleName: "target2",
Endpoints: []cluster.EndpointDescriptor{{
Path: "failed_endpoint",
Inner: true,
UserAuthRequired: true,
}},
},
})
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("test-token-header", userAuthToken).
Header("x-auth-admin", "mock-token").
JsonRequestBody(req).
JsonResponseBody(&resp).
StatusCodeToError().
DoWithoutResponse(s.T().Context())
require.NoError(err)
require.EqualValues(req.Id, resp.Id)
err = cli.Post(srv.URL+"/api/failed_endpoint").
Header("x-application-token", "token").
Header("test-token-header", userAuthToken).
Header("x-auth-admin", "mock-token").
JsonRequestBody(req).
JsonResponseBody(&resp).
StatusCodeToError().
DoWithoutResponse(s.T().Context())
errResp := httpcli.ErrorResponse{}
require.ErrorAs(err, &errResp)
require.EqualValues(http.StatusUnauthorized, errResp.StatusCode)
}
// nolint:ireturn
func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *client.Client, *client.Client) {
config := conf.Remote{
@@ -591,11 +316,11 @@ func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *
}
systemService, systemCli := grpct.NewMock(test)
systemService.Mock("system/secure/authenticate", func() entity.AuthenticateResponse {
return entity.AuthenticateResponse{
systemService.Mock("system/secure/authenticate", func() domain.AuthenticateResponse {
return domain.AuthenticateResponse{
Authenticated: true,
ErrorReason: "",
AuthData: &entity.AppAuthData{
AuthData: &domain.AuthData{
SystemId: 1,
DomainId: 2,
ServiceId: 3,
@@ -603,22 +328,22 @@ func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *
AppName: "test",
},
}
}).Mock("system/secure/authorize", func() entity.AuthorizeResponse {
return entity.AuthorizeResponse{Authorized: true}
}).Mock("system/secure/authorize", func() domain.AuthorizeResponse {
return domain.AuthorizeResponse{Authorized: true}
})
adminService, adminCli := grpct.NewMock(test)
adminService.Mock("admin/secure/authenticate", func(req entity.AdminAuthorizeRequest) entity.AdminAuthenticateResponse {
return entity.AdminAuthenticateResponse{
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 entity.AdminAuthorizeRequest) entity.AdminAuthorizeResponse {
}).Mock("admin/secure/authorize", func(req domain.AdminAuthorizeRequest) domain.AdminAuthorizeResponse {
if req.Permission == "ok_permission" {
return entity.AdminAuthorizeResponse{Authorized: true}
return domain.AdminAuthorizeResponse{Authorized: true}
}
return entity.AdminAuthorizeResponse{Authorized: false}
return domain.AdminAuthorizeResponse{Authorized: false}
})
return config, systemCli, adminCli
@@ -630,13 +355,13 @@ func TestHappyPathTestSuite(t *testing.T) {
}
func assertHeaders(require *require.Assertions, requestId string, ctx context.Context, headers http.Header) {
systemId, err := strconv.Atoi(headers.Get("x-system-identity")) // nolint: canonicalheader
systemId, err := strconv.Atoi(headers.Get("x-system-identity"))
require.NoError(err)
domainId, err := strconv.Atoi(headers.Get("x-domain-identity")) // nolint: canonicalheader
domainId, err := strconv.Atoi(headers.Get("x-domain-identity"))
require.NoError(err)
serviceId, err := strconv.Atoi(headers.Get("x-service-identity")) // nolint: canonicalheader
serviceId, err := strconv.Atoi(headers.Get("x-service-identity"))
require.NoError(err)
applicationId, err := strconv.Atoi(headers.Get("x-application-identity")) // nolint: canonicalheader
applicationId, err := strconv.Atoi(headers.Get("x-application-identity"))
require.NoError(err)
require.EqualValues(requestId, requestid.FromContext(ctx))
require.EqualValues(1, systemId)
@@ -644,9 +369,9 @@ func assertHeaders(require *require.Assertions, requestId string, ctx context.Co
require.EqualValues(3, serviceId)
require.EqualValues(4, applicationId)
expectedAppName := base64.StdEncoding.EncodeToString([]byte("test"))
require.EqualValues(expectedAppName, headers.Get("x-application-name")) // nolint: canonicalheader
require.EqualValues(expectedAppName, headers.Get("x-application-name"))
adminId, err := strconv.Atoi(headers.Get("x-admin-id")) // nolint: canonicalheader
adminId, err := strconv.Atoi(headers.Get("x-admin-id"))
require.NoError(err)
require.EqualValues(1, adminId)
}
+9 -11
View File
@@ -5,14 +5,12 @@ import (
"net"
"net/http"
"github.com/redis/go-redis/v9"
"isp-gate-service/assembly"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/entity"
"isp-gate-service/routes"
"github.com/redis/go-redis/v9"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/grpc/client"
endpoint2 "github.com/txix-open/isp-kit/grpc/endpoint"
@@ -56,19 +54,19 @@ func main() {
}
systemService, systemCli, _ := NewMock(logger)
systemService.Mock("system/secure/authenticate", func() entity.AuthenticateResponse {
return entity.AuthenticateResponse{
systemService.Mock("system/secure/authenticate", func() domain.AuthenticateResponse {
return domain.AuthenticateResponse{
Authenticated: true,
ErrorReason: "",
AuthData: &entity.AppAuthData{
AuthData: &domain.AuthData{
SystemId: 1,
DomainId: 1,
ServiceId: 1,
ApplicationId: 1,
},
}
}).Mock("system/secure/authorize", func() entity.AuthorizeResponse {
return entity.AuthorizeResponse{Authorized: true}
}).Mock("system/secure/authorize", func() domain.AuthorizeResponse {
return domain.AuthorizeResponse{Authorized: true}
})
adminService, _, adminCli := NewMock(logger)
@@ -86,7 +84,7 @@ func main() {
})
targetClients := map[string]*client.Client{"target": targetCli}
logger, _ = log.New(log.WithLevel(log.DebugLevel))
locator := assembly.NewLocator(logger, targetClients, nil, routes.NewRoutes(logger), systemCli, adminCli, nil, nil, nil)
locator := assembly.NewLocator(logger, targetClients, nil, routes.NewRoutes(), systemCli, adminCli, nil)
locations := []conf.Location{{
SkipAuth: false,
PathPrefix: "/api",
@@ -128,11 +126,11 @@ func NewMock(logger log.Logger) (*MockServer, *client.Client, *client.Client) {
return &MockServer{
srv: srv,
logger: logger,
mockEndpoints: make(map[string]any),
mockEndpoints: make(map[string]interface{}),
}, syscli, admincli
}
func (m *MockServer) Mock(endpoint string, handler any) *MockServer {
func (m *MockServer) Mock(endpoint string, handler interface{}) *MockServer {
m.mockEndpoints[endpoint] = handler
wrapper := endpoint2.DefaultWrapper(m.logger)
muxer := grpc.NewMux()