Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
394bbc82e2 | ||
|
|
7de248e63c | ||
|
|
011a1d7048 |
No files matched your search
@@ -1,3 +1,10 @@
|
|||||||
|
### 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
|
### v5.9.1
|
||||||
* Добавлен `warn` лог на неизвестный endpoint
|
* Добавлен `warn` лог на неизвестный endpoint
|
||||||
### v5.9.0
|
### v5.9.0
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ package assembly
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"isp-gate-service/cache"
|
||||||
"isp-gate-service/conf"
|
"isp-gate-service/conf"
|
||||||
"isp-gate-service/routes"
|
"isp-gate-service/routes"
|
||||||
|
|
||||||
@@ -16,6 +18,11 @@ import (
|
|||||||
"github.com/txix-open/isp-kit/log"
|
"github.com/txix-open/isp-kit/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
routerModuleName = "isp-router-service"
|
||||||
|
usersAuthCachePurgeInterval = 5 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
type Assembly struct {
|
type Assembly struct {
|
||||||
boot *bootstrap.Bootstrap
|
boot *bootstrap.Bootstrap
|
||||||
server *http.Server
|
server *http.Server
|
||||||
@@ -24,10 +31,13 @@ type Assembly struct {
|
|||||||
systemCli *client.Client
|
systemCli *client.Client
|
||||||
adminCli *client.Client
|
adminCli *client.Client
|
||||||
lockerCli *client.Client
|
lockerCli *client.Client
|
||||||
|
routerLb *lb.RoundRobin
|
||||||
|
|
||||||
locations []conf.Location
|
locations []conf.Location
|
||||||
grpcClientByModuleName map[string]*client.Client
|
grpcClientByModuleName map[string]*client.Client
|
||||||
httpHostManagerByModuleName map[string]*lb.RoundRobin
|
httpHostManagerByModuleName map[string]*lb.RoundRobin
|
||||||
|
|
||||||
|
usersAuthCache *cache.Cache
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
||||||
@@ -81,6 +91,8 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
|||||||
systemCli: systemCli,
|
systemCli: systemCli,
|
||||||
adminCli: adminCli,
|
adminCli: adminCli,
|
||||||
lockerCli: lockerCli,
|
lockerCli: lockerCli,
|
||||||
|
routerLb: lb.NewRoundRobin(nil),
|
||||||
|
usersAuthCache: cache.New(),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,6 +115,8 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error
|
|||||||
a.systemCli,
|
a.systemCli,
|
||||||
a.adminCli,
|
a.adminCli,
|
||||||
a.lockerCli,
|
a.lockerCli,
|
||||||
|
a.routerLb,
|
||||||
|
a.usersAuthCache,
|
||||||
)
|
)
|
||||||
handler, err := locator.Handler(newCfg, a.locations)
|
handler, err := locator.Handler(newCfg, a.locations)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -128,6 +142,7 @@ func (a *Assembly) Runners() []app.Runner {
|
|||||||
eventHandler.RequireModule("isp-system-service", a.systemCli)
|
eventHandler.RequireModule("isp-system-service", a.systemCli)
|
||||||
eventHandler.RequireModule("msp-admin-service", a.adminCli)
|
eventHandler.RequireModule("msp-admin-service", a.adminCli)
|
||||||
eventHandler.RequireModule("isp-lock-service", a.lockerCli)
|
eventHandler.RequireModule("isp-lock-service", a.lockerCli)
|
||||||
|
eventHandler.RequireModule(routerModuleName, a.routerLb)
|
||||||
|
|
||||||
return []app.Runner{
|
return []app.Runner{
|
||||||
app.RunnerFunc(func(ctx context.Context) error {
|
app.RunnerFunc(func(ctx context.Context) error {
|
||||||
@@ -136,6 +151,10 @@ func (a *Assembly) Runners() []app.Runner {
|
|||||||
app.RunnerFunc(func(ctx context.Context) error {
|
app.RunnerFunc(func(ctx context.Context) error {
|
||||||
return a.boot.ClusterCli.Run(ctx, eventHandler)
|
return a.boot.ClusterCli.Run(ctx, eventHandler)
|
||||||
}),
|
}),
|
||||||
|
app.RunnerFunc(func(ctx context.Context) error {
|
||||||
|
a.usersAuthCache.StartCleaner(ctx, usersAuthCachePurgeInterval)
|
||||||
|
return nil
|
||||||
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+29
-1
@@ -2,11 +2,13 @@ package assembly
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/metrics"
|
"github.com/txix-open/isp-kit/metrics"
|
||||||
"github.com/txix-open/isp-kit/metrics/http_metrics"
|
"github.com/txix-open/isp-kit/metrics/http_metrics"
|
||||||
|
|
||||||
|
"isp-gate-service/cache"
|
||||||
"isp-gate-service/conf"
|
"isp-gate-service/conf"
|
||||||
"isp-gate-service/middleware"
|
"isp-gate-service/middleware"
|
||||||
"isp-gate-service/proxy"
|
"isp-gate-service/proxy"
|
||||||
@@ -29,6 +31,8 @@ type Locator struct {
|
|||||||
systemCli *client.Client
|
systemCli *client.Client
|
||||||
adminCli *client.Client
|
adminCli *client.Client
|
||||||
lockerCli *client.Client
|
lockerCli *client.Client
|
||||||
|
routerLb *lb.RoundRobin
|
||||||
|
usersAuthCache *cache.Cache
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewLocator(
|
func NewLocator(
|
||||||
@@ -39,6 +43,8 @@ func NewLocator(
|
|||||||
systemCli *client.Client,
|
systemCli *client.Client,
|
||||||
adminCli *client.Client,
|
adminCli *client.Client,
|
||||||
lockerCli *client.Client,
|
lockerCli *client.Client,
|
||||||
|
routerLb *lb.RoundRobin,
|
||||||
|
usersAuthCache *cache.Cache,
|
||||||
) Locator {
|
) Locator {
|
||||||
return Locator{
|
return Locator{
|
||||||
logger: logger,
|
logger: logger,
|
||||||
@@ -48,6 +54,8 @@ func NewLocator(
|
|||||||
systemCli: systemCli,
|
systemCli: systemCli,
|
||||||
adminCli: adminCli,
|
adminCli: adminCli,
|
||||||
lockerCli: lockerCli,
|
lockerCli: lockerCli,
|
||||||
|
routerLb: routerLb,
|
||||||
|
usersAuthCache: usersAuthCache,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,6 +66,17 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
|||||||
authenticationCache := repository.NewAuthenticationCache(time.Duration(config.Caching.AuthenticationDataInSec) * time.Second)
|
authenticationCache := repository.NewAuthenticationCache(time.Duration(config.Caching.AuthenticationDataInSec) * time.Second)
|
||||||
authentication := service.NewAuthentication(authenticationCache, systemRepo)
|
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(
|
adminService := service.NewAdmin(
|
||||||
repository.NewAuthorizationCache(time.Duration(config.Caching.AuthorizationDataInSec)*time.Second),
|
repository.NewAuthorizationCache(time.Duration(config.Caching.AuthorizationDataInSec)*time.Second),
|
||||||
adminRepo,
|
adminRepo,
|
||||||
@@ -72,6 +91,11 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
|||||||
dailyLimitService := service.NewDailyLimit(lockRepo, config.DailyLimits)
|
dailyLimitService := service.NewDailyLimit(lockRepo, config.DailyLimits)
|
||||||
throttlingService := service.NewThrottling(lockRepo, config.Throttling)
|
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()
|
mux := mux2.NewRouter()
|
||||||
for _, location := range locations {
|
for _, location := range locations {
|
||||||
var proxyFunc middleware.Handler
|
var proxyFunc middleware.Handler
|
||||||
@@ -83,6 +107,9 @@ 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)
|
proxyFunc = proxy.NewGrpc(cli, location.SkipAuth, time.Duration(config.Http.ProxyTimeoutInSec)*time.Second)
|
||||||
case conf.HttpProtocol:
|
case conf.HttpProtocol:
|
||||||
hostManager := l.httpHostManagerByModuleName[location.TargetModule]
|
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)
|
proxyFunc = proxy.NewHttp(hostManager, location.SkipAuth, time.Duration(config.Http.ProxyTimeoutInSec)*time.Second)
|
||||||
case conf.WsProtocol:
|
case conf.WsProtocol:
|
||||||
hostManager := l.httpHostManagerByModuleName[location.TargetModule]
|
hostManager := l.httpHostManagerByModuleName[location.TargetModule]
|
||||||
@@ -109,6 +136,7 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
|||||||
),
|
),
|
||||||
middleware.RequestId(),
|
middleware.RequestId(),
|
||||||
middleware.ErrorHandler(l.logger),
|
middleware.ErrorHandler(l.logger),
|
||||||
|
middleware.UserAuthenticate(userAuthentication, l.logger),
|
||||||
middleware.Authenticate(authentication),
|
middleware.Authenticate(authentication),
|
||||||
middleware.AdminAuthenticate(adminService),
|
middleware.AdminAuthenticate(adminService),
|
||||||
middleware.ClientRequestId(config.EnableClientRequestIdForwarding, forwardReqIdByAppId),
|
middleware.ClientRequestId(config.EnableClientRequestIdForwarding, forwardReqIdByAppId),
|
||||||
@@ -126,7 +154,7 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
|||||||
proxyFunc,
|
proxyFunc,
|
||||||
middleware.Logger(l.logger, config.Logging.RequestLogEnable,
|
middleware.Logger(l.logger, config.Logging.RequestLogEnable,
|
||||||
enableBodyLog,
|
enableBodyLog,
|
||||||
config.Logging.SkipBodyLoggingEndpointPrefixes,
|
skipBodyLoggingEndpointPrefixes,
|
||||||
config.Logging.EnableForceUnescapingUnicode,
|
config.Logging.EnableForceUnescapingUnicode,
|
||||||
),
|
),
|
||||||
middleware.RequestId(),
|
middleware.RequestId(),
|
||||||
|
|||||||
Vendored
+29
@@ -1,6 +1,7 @@
|
|||||||
package cache
|
package cache
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -48,6 +49,34 @@ 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 {
|
func (c *Cache) now() time.Time {
|
||||||
return time.Now()
|
return time.Now()
|
||||||
}
|
}
|
||||||
+41
-1
@@ -9,6 +9,11 @@ import (
|
|||||||
"github.com/txix-open/jsonschema"
|
"github.com/txix-open/jsonschema"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
HeaderTokenProviderType = "HEADER"
|
||||||
|
CookieTokenProviderType = "COOKIE"
|
||||||
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Schema) {
|
schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Schema) {
|
||||||
t.Type = "string"
|
t.Type = "string"
|
||||||
@@ -24,6 +29,7 @@ type Remote struct {
|
|||||||
Throttling []Throttling `schema:"Настройки пропускной способности"`
|
Throttling []Throttling `schema:"Настройки пропускной способности"`
|
||||||
EnableClientRequestIdForwarding bool `schema:"Включить проброс requestId из заголовка запроса"`
|
EnableClientRequestIdForwarding bool `schema:"Включить проброс requestId из заголовка запроса"`
|
||||||
ForwardReqIdClientSettings []ForwardReqIdClientSettings `schema:"Настройки проброcа requestId для приложений"`
|
ForwardReqIdClientSettings []ForwardReqIdClientSettings `schema:"Настройки проброcа requestId для приложений"`
|
||||||
|
CustomAuth CustomAuth `schema:"Настройка кастомной аутентификации/авторизации"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ForwardReqIdClientSettings struct {
|
type ForwardReqIdClientSettings struct {
|
||||||
@@ -40,7 +46,7 @@ type Logging struct {
|
|||||||
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования,логирование запросов осуществляется на уровне debug"`
|
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования,логирование запросов осуществляется на уровне debug"`
|
||||||
RequestLogEnable bool `schema:"Включить логирование запросов"`
|
RequestLogEnable bool `schema:"Включить логирование запросов"`
|
||||||
BodyLogEnable bool `schema:"Включить логирование тел запросов и ответов,должно быть включено логирование запросов"`
|
BodyLogEnable bool `schema:"Включить логирование тел запросов и ответов,должно быть включено логирование запросов"`
|
||||||
SkipBodyLoggingEndpointPrefixes []string `schema:"регулярные выражения для отключения логирования"`
|
SkipBodyLoggingEndpointPrefixes []string `schema:"Выключить логирование тел запросов и ответов для путей имеющих префикс из списка,'/' в начале игнорируется"`
|
||||||
EnableForceUnescapingUnicode bool `schema:"Включить перевод тел запроса из unicode в utf-8, должно быть включено логирование тел запросов и ответов"`
|
EnableForceUnescapingUnicode bool `schema:"Включить перевод тел запроса из unicode в utf-8, должно быть включено логирование тел запросов и ответов"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,3 +64,37 @@ type Throttling struct {
|
|||||||
ApplicationId int `validate:"required" schema:"ID приложения"`
|
ApplicationId int `validate:"required" schema:"ID приложения"`
|
||||||
RequestsPerSeconds int `validate:"required,min=1,max=1000" schema:"Запросов в секунду,не конфликтует с суточными ограничениями, алгоритм не работает на значениях больше 1000"`
|
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"`
|
||||||
|
TokenProvider string `schema:"Название метода получения токена из запроса" validate:"required"`
|
||||||
|
AuthenticateMethodPath string `schema:"Путь до метода аутентификации,метод вызывается через isp-router-service" validate:"required"`
|
||||||
|
CacheDataInSec int `schema:"Время кеширования данных аутентификации/авторизации пользователя,отключен при значениях <=0,в секундах"`
|
||||||
|
SkipAppAuth bool `schema:"Пропустить аутентификацию и авторизацию приложения"`
|
||||||
|
}
|
||||||
+30
-1
@@ -1,9 +1,38 @@
|
|||||||
package domain
|
package domain
|
||||||
|
|
||||||
type AuthData struct {
|
type AuthenticateAppResponse struct {
|
||||||
|
Authenticated bool
|
||||||
|
ErrorReason string
|
||||||
|
AuthData *AppAuthData
|
||||||
|
}
|
||||||
|
|
||||||
|
type AppAuthData struct {
|
||||||
AppName string
|
AppName string
|
||||||
SystemId int
|
SystemId int
|
||||||
DomainId int
|
DomainId int
|
||||||
ServiceId int
|
ServiceId int
|
||||||
ApplicationId 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
|
||||||
|
}
|
||||||
+10
-2
@@ -1,14 +1,22 @@
|
|||||||
package domain
|
package domain
|
||||||
|
|
||||||
import "context"
|
import (
|
||||||
|
"context"
|
||||||
|
)
|
||||||
|
|
||||||
type EndpointMeta struct {
|
type EndpointMeta struct {
|
||||||
Inner bool
|
Inner bool
|
||||||
|
UserAuthRequired bool
|
||||||
|
|
||||||
|
ModuleName string
|
||||||
RequiredAdminPermission string
|
RequiredAdminPermission string
|
||||||
// Объявляемый сервисом метод
|
// Объявляемый сервисом метод
|
||||||
PathSchema string
|
PathSchema string
|
||||||
// Вызываемый метод
|
// Вызываемый метод
|
||||||
Endpoint string
|
Endpoint string
|
||||||
|
// Нормализованный путь, для известных путей берётся объявляемый метод, для неизвестных - вызываемый
|
||||||
|
// Удаляет '/' из начала пути
|
||||||
|
NormalizedEndpoint string
|
||||||
}
|
}
|
||||||
|
|
||||||
type endpointMetaKey struct{}
|
type endpointMetaKey struct{}
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package domain
|
||||||
|
|
||||||
|
import "github.com/pkg/errors"
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrUserAuthSettingNotFound = errors.New("user auth setting not found")
|
||||||
|
ErrEmptyUserToken = errors.New("failed to extract user token")
|
||||||
|
ErrInvalidUserToken = errors.New("invalid user token")
|
||||||
|
)
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package entity
|
||||||
|
|
||||||
|
type AdminAuthenticateResponse struct {
|
||||||
|
Authenticated bool
|
||||||
|
ErrorReason string
|
||||||
|
AdminId int
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package entity
|
||||||
|
|
||||||
|
type AppAuthData struct {
|
||||||
|
AppName string
|
||||||
|
SystemId int
|
||||||
|
DomainId int
|
||||||
|
ServiceId int
|
||||||
|
ApplicationId int
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package domain
|
package entity
|
||||||
|
|
||||||
type AuthenticateRequest struct {
|
type AuthenticateRequest struct {
|
||||||
Token string
|
Token string
|
||||||
@@ -7,7 +7,7 @@ type AuthenticateRequest struct {
|
|||||||
type AuthenticateResponse struct {
|
type AuthenticateResponse struct {
|
||||||
Authenticated bool
|
Authenticated bool
|
||||||
ErrorReason string
|
ErrorReason string
|
||||||
AuthData *AuthData
|
AuthData *AppAuthData
|
||||||
}
|
}
|
||||||
|
|
||||||
type AuthorizeRequest struct {
|
type AuthorizeRequest struct {
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -10,7 +10,7 @@ require (
|
|||||||
github.com/redis/go-redis/v9 v9.11.0
|
github.com/redis/go-redis/v9 v9.11.0
|
||||||
github.com/stretchr/testify v1.11.1
|
github.com/stretchr/testify v1.11.1
|
||||||
github.com/tomakado/websocketproxy v0.1.0
|
github.com/tomakado/websocketproxy v0.1.0
|
||||||
github.com/txix-open/isp-kit v1.65.1
|
github.com/txix-open/isp-kit v1.66.2
|
||||||
github.com/txix-open/jsonschema v1.3.0
|
github.com/txix-open/jsonschema v1.3.0
|
||||||
golang.org/x/net v0.52.0
|
golang.org/x/net v0.52.0
|
||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260311181403-84a4fc48630c
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20260311181403-84a4fc48630c
|
||||||
@@ -19,6 +19,7 @@ require (
|
|||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||||
|
github.com/go-faker/faker/v4 v4.7.0 // indirect
|
||||||
github.com/txix-open/etp/v4 v4.0.1 // indirect
|
github.com/txix-open/etp/v4 v4.0.1 // indirect
|
||||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||||
go.yaml.in/yaml/v2 v2.4.4 // indirect
|
go.yaml.in/yaml/v2 v2.4.4 // indirect
|
||||||
|
|||||||
@@ -123,8 +123,8 @@ github.com/txix-open/etp/v4 v4.0.1 h1:5VSYgGsvnMz0tvUHsjVWFETI0qWBTCF1O3ARCHaCIg
|
|||||||
github.com/txix-open/etp/v4 v4.0.1/go.mod h1:FIu7TUDdwcgmtmF6tFTV1bGA2fRY/iVaPQdsGzvqYc8=
|
github.com/txix-open/etp/v4 v4.0.1/go.mod h1:FIu7TUDdwcgmtmF6tFTV1bGA2fRY/iVaPQdsGzvqYc8=
|
||||||
github.com/txix-open/grmq v1.10.0 h1:1bXuF+7TxtUvoh+Wn6SOCYpVACFbWDuDmz/+tKwW9Ms=
|
github.com/txix-open/grmq v1.10.0 h1:1bXuF+7TxtUvoh+Wn6SOCYpVACFbWDuDmz/+tKwW9Ms=
|
||||||
github.com/txix-open/grmq v1.10.0/go.mod h1:EyFOP17KrwEFOUjR+PH8iH3LCtiN9TSQ8t0ysyk62po=
|
github.com/txix-open/grmq v1.10.0/go.mod h1:EyFOP17KrwEFOUjR+PH8iH3LCtiN9TSQ8t0ysyk62po=
|
||||||
github.com/txix-open/isp-kit v1.65.1 h1:KehXIJdPZMnewDd5XQxk87yNAtNhvJXApaLFvbUau5U=
|
github.com/txix-open/isp-kit v1.66.2 h1:+AFj7g9IeWiLSShmotrdheuJuwUNUYeL49D2d7PU3zo=
|
||||||
github.com/txix-open/isp-kit v1.65.1/go.mod h1:F4B/+ErbNVaWzIIGasXM5DtcDKtjl6u2OESO02RyzCI=
|
github.com/txix-open/isp-kit v1.66.2/go.mod h1:F4B/+ErbNVaWzIIGasXM5DtcDKtjl6u2OESO02RyzCI=
|
||||||
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4=
|
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/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
|
||||||
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 h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
|
||||||
|
|||||||
@@ -16,12 +16,16 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Authenticator interface {
|
type Authenticator interface {
|
||||||
Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error)
|
Authenticate(ctx context.Context, token string) (*domain.AuthenticateAppResponse, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Authenticate(authenticator Authenticator) Middleware {
|
func Authenticate(authenticator Authenticator) Middleware {
|
||||||
return func(next Handler) Handler {
|
return func(next Handler) Handler {
|
||||||
return HandlerFunc(func(ctx *request.Context) error {
|
return HandlerFunc(func(ctx *request.Context) error {
|
||||||
|
if ctx.SkipAppAuth() {
|
||||||
|
return next.Handle(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
token, appName, err := extractToken(ctx)
|
token, appName, err := extractToken(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -55,7 +59,7 @@ func Authenticate(authenticator Authenticator) Middleware {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx.Authenticate(request.AuthData(*resp.AuthData))
|
ctx.Authenticate(*resp.AuthData)
|
||||||
return next.Handle(ctx)
|
return next.Handle(ctx)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,10 +4,11 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"github.com/txix-open/isp-kit/log"
|
|
||||||
"isp-gate-service/httperrors"
|
"isp-gate-service/httperrors"
|
||||||
"isp-gate-service/request"
|
"isp-gate-service/request"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/txix-open/isp-kit/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Authorizer interface {
|
type Authorizer interface {
|
||||||
@@ -17,6 +18,10 @@ type Authorizer interface {
|
|||||||
func Authorize(authorizer Authorizer, logger log.Logger) Middleware {
|
func Authorize(authorizer Authorizer, logger log.Logger) Middleware {
|
||||||
return func(next Handler) Handler {
|
return func(next Handler) Handler {
|
||||||
return HandlerFunc(func(ctx *request.Context) error {
|
return HandlerFunc(func(ctx *request.Context) error {
|
||||||
|
if ctx.SkipAppAuth() {
|
||||||
|
return next.Handle(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
authData, err := ctx.GetAuthData()
|
authData, err := ctx.GetAuthData()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "authorize: get auth data")
|
return errors.WithMessage(err, "authorize: get auth data")
|
||||||
|
|||||||
@@ -16,6 +16,10 @@ type DailyLimitChecker interface {
|
|||||||
func DailyLimit(checker DailyLimitChecker) Middleware {
|
func DailyLimit(checker DailyLimitChecker) Middleware {
|
||||||
return func(next Handler) Handler {
|
return func(next Handler) Handler {
|
||||||
return HandlerFunc(func(ctx *request.Context) error {
|
return HandlerFunc(func(ctx *request.Context) error {
|
||||||
|
if ctx.SkipAppAuth() {
|
||||||
|
return next.Handle(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
authData, err := ctx.GetAuthData()
|
authData, err := ctx.GetAuthData()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "daily limit: get auth data")
|
return errors.WithMessage(err, "daily limit: get auth data")
|
||||||
|
|||||||
@@ -65,10 +65,11 @@ func Logger( // nolint:gocognit,funlen
|
|||||||
|
|
||||||
r := ctx.Request()
|
r := ctx.Request()
|
||||||
|
|
||||||
|
endpoint := ctx.EndpointMeta().NormalizedEndpoint
|
||||||
logBodyFromCurrenRequest := enableBodyLogging
|
logBodyFromCurrenRequest := enableBodyLogging
|
||||||
if logBodyFromCurrenRequest {
|
if logBodyFromCurrenRequest {
|
||||||
for _, prefix := range skipBodyLoggingEndpointPrefixes {
|
for _, prefix := range skipBodyLoggingEndpointPrefixes {
|
||||||
if strings.HasPrefix(ctx.EndpointMeta().Endpoint, prefix) {
|
if strings.HasPrefix(endpoint, prefix) {
|
||||||
logBodyFromCurrenRequest = false
|
logBodyFromCurrenRequest = false
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -110,7 +111,7 @@ func Logger( // nolint:gocognit,funlen
|
|||||||
log.String("xForwardedFor", r.Header.Get("X-Forwarded-For")),
|
log.String("xForwardedFor", r.Header.Get("X-Forwarded-For")),
|
||||||
log.Int("statusCode", scSrc.StatusCode()),
|
log.Int("statusCode", scSrc.StatusCode()),
|
||||||
log.String("path", originalPath),
|
log.String("path", originalPath),
|
||||||
log.String("endpoint", ctx.EndpointMeta().Endpoint),
|
log.String("endpoint", endpoint),
|
||||||
log.Int("applicationId", authData.ApplicationId),
|
log.Int("applicationId", authData.ApplicationId),
|
||||||
log.String("applicationName", authData.AppName),
|
log.String("applicationName", authData.AppName),
|
||||||
log.Int("adminId", ctx.AdminId()),
|
log.Int("adminId", ctx.AdminId()),
|
||||||
|
|||||||
@@ -18,6 +18,10 @@ type Throttler interface {
|
|||||||
func Throttling(throttler Throttler) Middleware {
|
func Throttling(throttler Throttler) Middleware {
|
||||||
return func(next Handler) Handler {
|
return func(next Handler) Handler {
|
||||||
return HandlerFunc(func(ctx *request.Context) error {
|
return HandlerFunc(func(ctx *request.Context) error {
|
||||||
|
if ctx.SkipAppAuth() {
|
||||||
|
return next.Handle(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
authData, err := ctx.GetAuthData()
|
authData, err := ctx.GetAuthData()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "throttling: get auth data")
|
return errors.WithMessage(err, "throttling: get auth data")
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"isp-gate-service/domain"
|
||||||
|
"isp-gate-service/httperrors"
|
||||||
|
"isp-gate-service/request"
|
||||||
|
|
||||||
|
"github.com/pkg/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)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
+42
-20
@@ -5,8 +5,10 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"io"
|
"io"
|
||||||
|
"maps"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-gate-service/httperrors"
|
"isp-gate-service/httperrors"
|
||||||
@@ -70,26 +72,7 @@ func (p Grpc) Handle(ctx *request.Context) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
requestId := requestid.FromContext(ctx.Context())
|
requestId := requestid.FromContext(ctx.Context())
|
||||||
md := metadata.MD{
|
md := p.writeMetadata(ctx)
|
||||||
grpc.ProxyMethodNameHeader: {ctx.EndpointMeta().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 := metadata.NewOutgoingContext(ctx.Context(), md)
|
||||||
|
|
||||||
requestContext, cancel := context.WithTimeout(requestContext, p.timeout)
|
requestContext, cancel := context.WithTimeout(requestContext, p.timeout)
|
||||||
@@ -167,3 +150,42 @@ func (p Grpc) codeToHttpStatus(code codes.Code) int {
|
|||||||
|
|
||||||
return s
|
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
|
||||||
|
}
|
||||||
+29
-20
@@ -67,10 +67,8 @@ func (p Http) Handle(ctx *request.Context) error {
|
|||||||
|
|
||||||
request := ctx.Request()
|
request := ctx.Request()
|
||||||
request.URL.Path = ctx.EndpointMeta().Endpoint
|
request.URL.Path = ctx.EndpointMeta().Endpoint
|
||||||
err = setHttpHeaders(ctx, request.Header, p.skipAuth)
|
setHttpHeaders(ctx, request.Header, p.skipAuth)
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
reverseProxy := httputil.NewSingleHostReverseProxy(target)
|
reverseProxy := httputil.NewSingleHostReverseProxy(target)
|
||||||
reverseProxy.Transport = httpTransport
|
reverseProxy.Transport = httpTransport
|
||||||
var resultError error
|
var resultError error
|
||||||
@@ -90,26 +88,37 @@ func (p Http) Handle(ctx *request.Context) error {
|
|||||||
return resultError
|
return resultError
|
||||||
}
|
}
|
||||||
|
|
||||||
func setHttpHeaders(ctx *request.Context, header http.Header, skipAuth bool) error {
|
func setHttpHeaders(ctx *request.Context, header http.Header, skipAuth bool) {
|
||||||
header.Set(requestid.Header, requestid.FromContext(ctx.Context()))
|
header.Set(requestid.Header, requestid.FromContext(ctx.Context()))
|
||||||
if !skipAuth {
|
if skipAuth {
|
||||||
authData, err := ctx.GetAuthData()
|
return
|
||||||
if err != nil {
|
}
|
||||||
return errors.WithMessage(err, "http: get auth data")
|
|
||||||
|
userAuthData, err := ctx.GetUserAuthData()
|
||||||
|
if err == nil {
|
||||||
|
for key, values := range userAuthData.ExtraHeaders {
|
||||||
|
for _, value := range values {
|
||||||
|
header.Add(key, value)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
header.Set(grpc.SystemIdHeader, strconv.Itoa(authData.SystemId))
|
header.Set(userAuthData.IdentityHeader, userAuthData.Identity)
|
||||||
header.Set(grpc.DomainIdHeader, strconv.Itoa(authData.DomainId))
|
}
|
||||||
header.Set(grpc.ServiceIdHeader, strconv.Itoa(authData.ServiceId))
|
|
||||||
header.Set(grpc.ApplicationIdHeader, strconv.Itoa(authData.ApplicationId))
|
appAuthData, err := ctx.GetAuthData()
|
||||||
encodedAppName := base64.StdEncoding.EncodeToString([]byte(authData.AppName))
|
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.ApplicationNameHeader, encodedAppName) //nolint:canonicalheader
|
header.Set(grpc.ApplicationNameHeader, encodedAppName) //nolint:canonicalheader
|
||||||
if ctx.IsAdminAuthenticated() {
|
}
|
||||||
header.Set(xAdminIdHeader, strconv.Itoa(ctx.AdminId())) //nolint:canonicalheader
|
|
||||||
} else {
|
if ctx.IsAdminAuthenticated() {
|
||||||
header.Del(xAdminIdHeader) //nolint:canonicalheader
|
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) {
|
func defaultTransportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) {
|
||||||
|
|||||||
+1
-1
@@ -43,7 +43,7 @@ func (ws Ws) Handle(ctx *request.Context) error {
|
|||||||
var resultError error
|
var resultError error
|
||||||
proxy := websocketproxy.NewProxy(target)
|
proxy := websocketproxy.NewProxy(target)
|
||||||
proxy.Director = func(incoming *http.Request, out http.Header) {
|
proxy.Director = func(incoming *http.Request, out http.Header) {
|
||||||
_ = setHttpHeaders(ctx, out, ws.skipAuth)
|
setHttpHeaders(ctx, out, ws.skipAuth)
|
||||||
}
|
}
|
||||||
proxy.Upgrader = &websocket.Upgrader{
|
proxy.Upgrader = &websocket.Upgrader{
|
||||||
HandshakeTimeout: 5 * time.Second,
|
HandshakeTimeout: 5 * time.Second,
|
||||||
|
|||||||
+6
-6
@@ -4,7 +4,7 @@ package repository
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"isp-gate-service/domain"
|
"isp-gate-service/entity"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/txix-open/isp-kit/grpc/client"
|
"github.com/txix-open/isp-kit/grpc/client"
|
||||||
@@ -23,10 +23,10 @@ func NewAdmin(cli *client.Client) Admin {
|
|||||||
return Admin{cli: cli}
|
return Admin{cli: cli}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Admin) Authenticate(ctx context.Context, token string) (*domain.AdminAuthenticateResponse, error) {
|
func (r Admin) Authenticate(ctx context.Context, token string) (*entity.AdminAuthenticateResponse, error) {
|
||||||
resp := domain.AdminAuthenticateResponse{}
|
resp := entity.AdminAuthenticateResponse{}
|
||||||
err := r.cli.Invoke(adminAuthenticate).
|
err := r.cli.Invoke(adminAuthenticate).
|
||||||
JsonRequestBody(domain.AuthenticateRequest{Token: token}).
|
JsonRequestBody(entity.AuthenticateRequest{Token: token}).
|
||||||
JsonResponseBody(&resp).
|
JsonResponseBody(&resp).
|
||||||
Do(ctx)
|
Do(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -36,9 +36,9 @@ func (r Admin) Authenticate(ctx context.Context, token string) (*domain.AdminAut
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r Admin) Authorize(ctx context.Context, adminId int, permission string) (bool, error) {
|
func (r Admin) Authorize(ctx context.Context, adminId int, permission string) (bool, error) {
|
||||||
resp := domain.AdminAuthorizeResponse{}
|
resp := entity.AdminAuthorizeResponse{}
|
||||||
err := r.cli.Invoke(adminAuthorize).
|
err := r.cli.Invoke(adminAuthorize).
|
||||||
JsonRequestBody(domain.AdminAuthorizeRequest{AdminId: adminId, Permission: permission}).
|
JsonRequestBody(entity.AdminAuthorizeRequest{AdminId: adminId, Permission: permission}).
|
||||||
JsonResponseBody(&resp).
|
JsonResponseBody(&resp).
|
||||||
Do(ctx)
|
Do(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -4,10 +4,12 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"github.com/txix-open/isp-kit/json"
|
|
||||||
"isp-gate-service/cache"
|
"isp-gate-service/cache"
|
||||||
"isp-gate-service/domain"
|
"isp-gate-service/domain"
|
||||||
|
"isp-gate-service/entity"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/txix-open/isp-kit/json"
|
||||||
)
|
)
|
||||||
|
|
||||||
type AuthenticationCache struct {
|
type AuthenticationCache struct {
|
||||||
@@ -22,13 +24,13 @@ func NewAuthenticationCache(duration time.Duration) AuthenticationCache {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r AuthenticationCache) Get(ctx context.Context, token string) (*domain.AuthData, error) {
|
func (r AuthenticationCache) Get(ctx context.Context, token string) (*entity.AppAuthData, error) {
|
||||||
data, ok := r.cache.Get(token)
|
data, ok := r.cache.Get(token)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, domain.ErrAuthenticationCacheMiss
|
return nil, domain.ErrAuthenticationCacheMiss
|
||||||
}
|
}
|
||||||
|
|
||||||
result := domain.AuthData{}
|
result := entity.AppAuthData{}
|
||||||
err := json.Unmarshal(data, &result)
|
err := json.Unmarshal(data, &result)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "json unmarshal auth data")
|
return nil, errors.WithMessage(err, "json unmarshal auth data")
|
||||||
@@ -37,7 +39,7 @@ func (r AuthenticationCache) Get(ctx context.Context, token string) (*domain.Aut
|
|||||||
return &result, nil
|
return &result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r AuthenticationCache) Set(ctx context.Context, token string, data domain.AuthData) error {
|
func (r AuthenticationCache) Set(ctx context.Context, token string, data entity.AppAuthData) error {
|
||||||
value, err := json.Marshal(data)
|
value, err := json.Marshal(data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "json marshal auth data")
|
return errors.WithMessage(err, "json marshal auth data")
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ package repository
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"isp-gate-service/domain"
|
"isp-gate-service/entity"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/txix-open/isp-kit/grpc/client"
|
"github.com/txix-open/isp-kit/grpc/client"
|
||||||
@@ -25,10 +25,10 @@ func NewSystem(cli *client.Client) System {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r System) Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error) {
|
func (r System) Authenticate(ctx context.Context, token string) (*entity.AuthenticateResponse, error) {
|
||||||
resp := domain.AuthenticateResponse{}
|
resp := entity.AuthenticateResponse{}
|
||||||
err := r.cli.Invoke(authenticate).
|
err := r.cli.Invoke(authenticate).
|
||||||
JsonRequestBody(domain.AuthenticateRequest{Token: token}).
|
JsonRequestBody(entity.AuthenticateRequest{Token: token}).
|
||||||
JsonResponseBody(&resp).
|
JsonResponseBody(&resp).
|
||||||
Do(ctx)
|
Do(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -37,8 +37,8 @@ func (r System) Authenticate(ctx context.Context, token string) (*domain.Authent
|
|||||||
return &resp, nil
|
return &resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r System) Authorize(ctx context.Context, req domain.AuthorizeRequest) (bool, error) {
|
func (r System) Authorize(ctx context.Context, req entity.AuthorizeRequest) (bool, error) {
|
||||||
resp := domain.AuthorizeResponse{}
|
resp := entity.AuthorizeResponse{}
|
||||||
err := r.cli.Invoke(authorize).
|
err := r.cli.Invoke(authorize).
|
||||||
JsonRequestBody(req).
|
JsonRequestBody(req).
|
||||||
JsonResponseBody(&resp).
|
JsonResponseBody(&resp).
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-gate-service/domain"
|
"isp-gate-service/domain"
|
||||||
|
"isp-gate-service/entity"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/redis/go-redis/v9"
|
"github.com/redis/go-redis/v9"
|
||||||
@@ -25,7 +26,7 @@ func NewRedisAuthCache(cli redis.UniversalClient, duration time.Duration, db int
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r RedisAuthCache) Get(ctx context.Context, token string) (*domain.AuthData, error) {
|
func (r RedisAuthCache) Get(ctx context.Context, token string) (*entity.AppAuthData, error) {
|
||||||
results, err := r.cli.Pipelined(ctx, func(p redis.Pipeliner) error {
|
results, err := r.cli.Pipelined(ctx, func(p redis.Pipeliner) error {
|
||||||
p.Select(ctx, r.db)
|
p.Select(ctx, r.db)
|
||||||
p.Get(ctx, token)
|
p.Get(ctx, token)
|
||||||
@@ -43,7 +44,7 @@ func (r RedisAuthCache) Get(ctx context.Context, token string) (*domain.AuthData
|
|||||||
return nil, errors.WithMessage(err, "get")
|
return nil, errors.WithMessage(err, "get")
|
||||||
}
|
}
|
||||||
|
|
||||||
result := domain.AuthData{}
|
result := entity.AppAuthData{}
|
||||||
err = json.Unmarshal([]byte(data), &result)
|
err = json.Unmarshal([]byte(data), &result)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "json unmarshal auth data")
|
return nil, errors.WithMessage(err, "json unmarshal auth data")
|
||||||
@@ -52,7 +53,7 @@ func (r RedisAuthCache) Get(ctx context.Context, token string) (*domain.AuthData
|
|||||||
return &result, nil
|
return &result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r RedisAuthCache) Set(ctx context.Context, token string, data domain.AuthData) error {
|
func (r RedisAuthCache) Set(ctx context.Context, token string, data entity.AppAuthData) error {
|
||||||
value, err := json.Marshal(data)
|
value, err := json.Marshal(data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "json marshal auth data")
|
return errors.WithMessage(err, "json marshal auth data")
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"isp-gate-service/entity"
|
||||||
|
|
||||||
|
"github.com/pkg/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
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"isp-gate-service/domain"
|
||||||
|
"isp-gate-service/entity"
|
||||||
|
|
||||||
|
"github.com/pkg/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)
|
||||||
|
}
|
||||||
+23
-12
@@ -13,14 +13,6 @@ var (
|
|||||||
ErrNotAuthenticated = errors.New("not authenticated")
|
ErrNotAuthenticated = errors.New("not authenticated")
|
||||||
)
|
)
|
||||||
|
|
||||||
type AuthData struct {
|
|
||||||
AppName string
|
|
||||||
SystemId int
|
|
||||||
DomainId int
|
|
||||||
ServiceId int
|
|
||||||
ApplicationId int
|
|
||||||
}
|
|
||||||
|
|
||||||
type Context struct {
|
type Context struct {
|
||||||
request *http.Request
|
request *http.Request
|
||||||
responseWriter http.ResponseWriter
|
responseWriter http.ResponseWriter
|
||||||
@@ -28,7 +20,10 @@ type Context struct {
|
|||||||
endpointMeta *domain.EndpointMeta
|
endpointMeta *domain.EndpointMeta
|
||||||
|
|
||||||
authenticated bool
|
authenticated bool
|
||||||
authData *AuthData
|
authData *domain.AppAuthData
|
||||||
|
|
||||||
|
userAuthenticated bool
|
||||||
|
userAuthData *domain.UserAuthData
|
||||||
|
|
||||||
adminAuthenticated bool
|
adminAuthenticated bool
|
||||||
adminId int
|
adminId int
|
||||||
@@ -65,18 +60,34 @@ func (c *Context) EndpointMeta() *domain.EndpointMeta {
|
|||||||
return c.endpointMeta
|
return c.endpointMeta
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Context) Authenticate(authData AuthData) {
|
func (c *Context) Authenticate(authData domain.AppAuthData) {
|
||||||
c.authenticated = true
|
c.authenticated = true
|
||||||
c.authData = &authData
|
c.authData = &authData
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Context) GetAuthData() (AuthData, error) {
|
func (c *Context) GetAuthData() (domain.AppAuthData, error) {
|
||||||
if !c.authenticated {
|
if !c.authenticated {
|
||||||
return AuthData{}, ErrNotAuthenticated
|
return domain.AppAuthData{}, ErrNotAuthenticated
|
||||||
}
|
}
|
||||||
return *c.authData, nil
|
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 {
|
func (c *Context) IsAdminAuthenticated() bool {
|
||||||
return c.adminAuthenticated
|
return c.adminAuthenticated
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-3
@@ -45,10 +45,10 @@ func (s *Routes) ReceiveRoutes(ctx context.Context, routes cluster.RoutingConfig
|
|||||||
for _, descriptor := range backend.Endpoints {
|
for _, descriptor := range backend.Endpoints {
|
||||||
path := normalizeDescriptorPath(descriptor.Path)
|
path := normalizeDescriptorPath(descriptor.Path)
|
||||||
if descriptor.HttpMethod != "" {
|
if descriptor.HttpMethod != "" {
|
||||||
s.registerEndpoint(router, descriptor.HttpMethod, path, descriptor)
|
s.registerEndpoint(router, backend.ModuleName, descriptor.HttpMethod, path, descriptor)
|
||||||
} else {
|
} else {
|
||||||
for _, httpMethod := range s.allHttpMethods {
|
for _, httpMethod := range s.allHttpMethods {
|
||||||
s.registerEndpoint(router, httpMethod, path, descriptor)
|
s.registerEndpoint(router, backend.ModuleName, httpMethod, path, descriptor)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -68,7 +68,8 @@ func (s *Routes) ResolveEndpoint(method string, path string, cfg middleware.Entr
|
|||||||
return nil, errors.Errorf("unknown endpoint '%s'", lookupPath)
|
return nil, errors.Errorf("unknown endpoint '%s'", lookupPath)
|
||||||
}
|
}
|
||||||
return &domain.EndpointMeta{
|
return &domain.EndpointMeta{
|
||||||
Endpoint: metaEndpoint,
|
Endpoint: metaEndpoint,
|
||||||
|
NormalizedEndpoint: normalizePath(metaEndpoint),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,6 +78,7 @@ func (s *Routes) ResolveEndpoint(method string, path string, cfg middleware.Entr
|
|||||||
|
|
||||||
meta := domain.EndpointMetaFromContext(req.Context())
|
meta := domain.EndpointMetaFromContext(req.Context())
|
||||||
meta.Endpoint = metaEndpoint
|
meta.Endpoint = metaEndpoint
|
||||||
|
meta.NormalizedEndpoint = normalizePath(meta.PathSchema)
|
||||||
return &meta, nil
|
return &meta, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,6 +96,7 @@ func (s *Routes) GetPaths(path string, cfg middleware.EntryPointConfig) (string,
|
|||||||
|
|
||||||
func (s *Routes) registerEndpoint(
|
func (s *Routes) registerEndpoint(
|
||||||
router *httprouter.Router,
|
router *httprouter.Router,
|
||||||
|
moduleName string,
|
||||||
httpMethod string,
|
httpMethod string,
|
||||||
path string,
|
path string,
|
||||||
descriptor cluster.EndpointDescriptor,
|
descriptor cluster.EndpointDescriptor,
|
||||||
@@ -105,6 +108,8 @@ func (s *Routes) registerEndpoint(
|
|||||||
requiredAdminPerm, _ := cluster.GetRequiredAdminPermission(descriptor)
|
requiredAdminPerm, _ := cluster.GetRequiredAdminPermission(descriptor)
|
||||||
meta := domain.EndpointMeta{
|
meta := domain.EndpointMeta{
|
||||||
Inner: descriptor.Inner,
|
Inner: descriptor.Inner,
|
||||||
|
UserAuthRequired: descriptor.UserAuthRequired,
|
||||||
|
ModuleName: moduleName,
|
||||||
RequiredAdminPermission: requiredAdminPerm,
|
RequiredAdminPermission: requiredAdminPerm,
|
||||||
PathSchema: descriptor.Path,
|
PathSchema: descriptor.Path,
|
||||||
}
|
}
|
||||||
@@ -116,3 +121,7 @@ func (s *Routes) registerEndpoint(
|
|||||||
}
|
}
|
||||||
router.Handle(httpMethod, path, handler)
|
router.Handle(httpMethod, path, handler)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func normalizePath(path string) string {
|
||||||
|
return strings.TrimPrefix(path, "/")
|
||||||
|
}
|
||||||
+7
-2
@@ -4,12 +4,13 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
|
|
||||||
"isp-gate-service/domain"
|
"isp-gate-service/domain"
|
||||||
|
"isp-gate-service/entity"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
type AdminAuth interface {
|
type AdminAuth interface {
|
||||||
Authenticate(ctx context.Context, token string) (*domain.AdminAuthenticateResponse, error)
|
Authenticate(ctx context.Context, token string) (*entity.AdminAuthenticateResponse, error)
|
||||||
Authorize(ctx context.Context, adminId int, permission string) (bool, error)
|
Authorize(ctx context.Context, adminId int, permission string) (bool, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,7 +31,11 @@ func (s Admin) AdminAuthenticate(ctx context.Context, token string) (*domain.Adm
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "get admin token data from admin service")
|
return nil, errors.WithMessage(err, "get admin token data from admin service")
|
||||||
}
|
}
|
||||||
return resp, nil
|
return &domain.AdminAuthenticateResponse{
|
||||||
|
Authenticated: resp.Authenticated,
|
||||||
|
ErrorReason: resp.ErrorReason,
|
||||||
|
AdminId: resp.AdminId,
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Admin) AdminAuthorize(ctx context.Context, adminId int, permission string) (bool, error) {
|
func (s Admin) AdminAuthorize(ctx context.Context, adminId int, permission string) (bool, error) {
|
||||||
|
|||||||
+45
-18
@@ -2,54 +2,81 @@ package service
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"isp-gate-service/domain"
|
||||||
|
"isp-gate-service/entity"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"isp-gate-service/domain"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type AuthenticationCache interface {
|
type AuthenticationCache interface {
|
||||||
Get(ctx context.Context, token string) (*domain.AuthData, error)
|
Get(ctx context.Context, token string) (*entity.AppAuthData, error)
|
||||||
Set(ctx context.Context, token string, data domain.AuthData) error
|
Set(ctx context.Context, token string, data entity.AppAuthData) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type AuthenticationRepo interface {
|
type AuthenticationRepo interface {
|
||||||
Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error)
|
Authenticate(ctx context.Context, token string) (*entity.AuthenticateResponse, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Auth struct {
|
type Authentication struct {
|
||||||
cache AuthenticationCache
|
cache AuthenticationCache
|
||||||
repo AuthenticationRepo
|
repo AuthenticationRepo
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewAuthentication(cache AuthenticationCache, repo AuthenticationRepo) Auth {
|
func NewAuthentication(
|
||||||
return Auth{
|
cache AuthenticationCache,
|
||||||
|
repo AuthenticationRepo,
|
||||||
|
) Authentication {
|
||||||
|
return Authentication{
|
||||||
cache: cache,
|
cache: cache,
|
||||||
repo: repo,
|
repo: repo,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Auth) Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error) {
|
func (s Authentication) Authenticate(ctx context.Context, token string) (*domain.AuthenticateAppResponse, error) {
|
||||||
authData, err := s.cache.Get(ctx, token)
|
authData, err := s.cache.Get(ctx, token)
|
||||||
if errors.Is(err, domain.ErrAuthenticationCacheMiss) {
|
switch {
|
||||||
|
case errors.Is(err, domain.ErrAuthenticationCacheMiss):
|
||||||
resp, err := s.repo.Authenticate(ctx, token)
|
resp, err := s.repo.Authenticate(ctx, token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "auth repo authenticate")
|
return nil, errors.WithMessage(err, "auth repo authenticate")
|
||||||
}
|
}
|
||||||
if !resp.Authenticated {
|
if !resp.Authenticated {
|
||||||
return resp, nil
|
return s.convertAuthReponse(resp), nil
|
||||||
}
|
}
|
||||||
err = s.cache.Set(ctx, token, *resp.AuthData)
|
err = s.cache.Set(ctx, token, *resp.AuthData)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "auth cache set")
|
return nil, errors.WithMessage(err, "auth cache set")
|
||||||
}
|
}
|
||||||
return resp, nil
|
return s.convertAuthReponse(resp), nil
|
||||||
}
|
case err != nil:
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessage(err, "auth cache get")
|
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
|
|
||||||
}
|
}
|
||||||
@@ -3,7 +3,7 @@ package service
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"isp-gate-service/domain"
|
"isp-gate-service/entity"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
@@ -14,7 +14,7 @@ type AuthorizationCache interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type AuthorizationRepo interface {
|
type AuthorizationRepo interface {
|
||||||
Authorize(ctx context.Context, req domain.AuthorizeRequest) (bool, error)
|
Authorize(ctx context.Context, req entity.AuthorizeRequest) (bool, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Authorization struct {
|
type Authorization struct {
|
||||||
@@ -39,7 +39,7 @@ func (s Authorization) Authorize(ctx context.Context, applicationId int, httpMet
|
|||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
ok, err = s.repo.Authorize(ctx, domain.AuthorizeRequest{
|
ok, err = s.repo.Authorize(ctx, entity.AuthorizeRequest{
|
||||||
ApplicationId: applicationId,
|
ApplicationId: applicationId,
|
||||||
HttpMethod: httpMethod,
|
HttpMethod: httpMethod,
|
||||||
Endpoint: endpoint,
|
Endpoint: endpoint,
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package token_provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"isp-gate-service/conf"
|
||||||
|
"isp-gate-service/request"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
type CookieProvider struct {
|
||||||
|
cookieName string
|
||||||
|
validate bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCookieProvider(cfg conf.CookieTokenProvider) CookieProvider {
|
||||||
|
return CookieProvider{
|
||||||
|
cookieName: cfg.CookieName,
|
||||||
|
validate: cfg.Validate,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package token_provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"isp-gate-service/conf"
|
||||||
|
"isp-gate-service/request"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type HeaderProvider struct {
|
||||||
|
headerName string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHeaderProvider(cfg conf.HeaderTokenProvider) HeaderProvider {
|
||||||
|
return HeaderProvider{
|
||||||
|
headerName: cfg.HeaderName,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p HeaderProvider) ExtractToken(ctx *request.Context) (string, error) {
|
||||||
|
value := ctx.Request().Header.Get(p.headerName)
|
||||||
|
return strings.TrimSpace(value), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
// 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/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
type UserAuthenticationCache interface {
|
||||||
|
Get(ctx context.Context, authMethodPath string, token string) (*entity.UserAuthData, error)
|
||||||
|
Set(ctx context.Context, authMethodPath string, token string, data entity.UserAuthData, duration time.Duration) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserAuthenticationRepo interface {
|
||||||
|
Authenticate(ctx context.Context, methodPath string, token string) (*entity.UserAuthenticateResponse, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type TokenProvider interface {
|
||||||
|
ExtractToken(ctx *request.Context) (string, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type userAuthSetting struct {
|
||||||
|
tokenProvider string
|
||||||
|
authenticatePath string
|
||||||
|
authCacheDuration time.Duration
|
||||||
|
skipAppAuth bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserAuthentication struct {
|
||||||
|
cache UserAuthenticationCache
|
||||||
|
repo UserAuthenticationRepo
|
||||||
|
settingsByModuleName map[string]userAuthSetting
|
||||||
|
tokenProviders map[string]TokenProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
_, ok := tokenProviders[setting.TokenProvider]
|
||||||
|
if !ok {
|
||||||
|
return UserAuthentication{},
|
||||||
|
errors.Errorf("modules with names'[%s]' has unknown token provider '%s'",
|
||||||
|
strings.Join(setting.ModuleNameList, ","),
|
||||||
|
setting.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{
|
||||||
|
tokenProvider: setting.TokenProvider,
|
||||||
|
authenticatePath: setting.AuthenticateMethodPath,
|
||||||
|
authCacheDuration: cacheDuration,
|
||||||
|
skipAppAuth: setting.SkipAppAuth,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return UserAuthentication{
|
||||||
|
cache: cache,
|
||||||
|
repo: repo,
|
||||||
|
settingsByModuleName: settingsByModuleName,
|
||||||
|
tokenProviders: tokenProviders,
|
||||||
|
}, 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,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
provider := s.tokenProviders[setting.tokenProvider]
|
||||||
|
|
||||||
|
token, err := provider.ExtractToken(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessagef(domain.ErrInvalidUserToken,
|
||||||
|
"extract token by '%s' error: %s", setting.tokenProvider, err.Error())
|
||||||
|
}
|
||||||
|
if token == "" {
|
||||||
|
return nil, domain.ErrEmptyUserToken
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := s.authenticate(
|
||||||
|
ctx.Context(),
|
||||||
|
setting,
|
||||||
|
token,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "auth")
|
||||||
|
}
|
||||||
|
return resp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
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.authenticatePath, token)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "auth repo authenticate")
|
||||||
|
}
|
||||||
|
return s.convertAuthReponse(resp, setting.skipAppAuth), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
authData, err := s.cache.Get(ctx, setting.authenticatePath, token)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, domain.ErrAuthenticationCacheMiss):
|
||||||
|
resp, err := s.repo.Authenticate(ctx, setting.authenticatePath, token)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "auth repo authenticate")
|
||||||
|
}
|
||||||
|
if !resp.Authenticated {
|
||||||
|
return s.convertAuthReponse(resp, setting.skipAppAuth), nil
|
||||||
|
}
|
||||||
|
err = s.cache.Set(
|
||||||
|
ctx,
|
||||||
|
setting.authenticatePath,
|
||||||
|
token,
|
||||||
|
*resp.AuthData,
|
||||||
|
setting.authCacheDuration,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "auth cache set")
|
||||||
|
}
|
||||||
|
return s.convertAuthReponse(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) convertAuthReponse(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.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.CookieProvider), nil
|
||||||
|
default:
|
||||||
|
return nil, errors.Errorf("unknown token provider with type '%s'", cfg.Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
+300
-24
@@ -12,15 +12,20 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"isp-gate-service/assembly"
|
"isp-gate-service/assembly"
|
||||||
|
"isp-gate-service/cache"
|
||||||
"isp-gate-service/conf"
|
"isp-gate-service/conf"
|
||||||
"isp-gate-service/domain"
|
"isp-gate-service/entity"
|
||||||
"isp-gate-service/routes"
|
"isp-gate-service/routes"
|
||||||
|
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
"github.com/txix-open/etp/v3"
|
"github.com/txix-open/etp/v3"
|
||||||
"github.com/txix-open/etp/v3/msg"
|
"github.com/txix-open/etp/v3/msg"
|
||||||
"github.com/txix-open/isp-kit/cluster"
|
"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/httpcli"
|
||||||
|
"github.com/txix-open/isp-kit/http/router"
|
||||||
|
"github.com/txix-open/isp-kit/test/fake"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/stretchr/testify/suite"
|
"github.com/stretchr/testify/suite"
|
||||||
@@ -86,7 +91,7 @@ func (s *HappyPathTestSuite) TestGrpcProxy() {
|
|||||||
}})
|
}})
|
||||||
require.NoError(err)
|
require.NoError(err)
|
||||||
|
|
||||||
locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil)
|
locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil, nil, nil)
|
||||||
|
|
||||||
locations := []conf.Location{{
|
locations := []conf.Location{{
|
||||||
SkipAuth: false,
|
SkipAuth: false,
|
||||||
@@ -101,14 +106,14 @@ func (s *HappyPathTestSuite) TestGrpcProxy() {
|
|||||||
cli := httpcli.New()
|
cli := httpcli.New()
|
||||||
req := request{Id: uuid.New().String()}
|
req := request{Id: uuid.New().String()}
|
||||||
resp := response{}
|
resp := response{}
|
||||||
_, err = cli.Post(srv.URL+"/api/endpoint").
|
err = cli.Post(srv.URL+"/api/endpoint").
|
||||||
Header("x-application-token", "token").
|
Header("x-application-token", "token").
|
||||||
Header("x-request-id", requestId).
|
Header("x-request-id", requestId).
|
||||||
Header("x-auth-admin", "mock-token").
|
Header("x-auth-admin", "mock-token").
|
||||||
JsonRequestBody(req).
|
JsonRequestBody(req).
|
||||||
JsonResponseBody(&resp).
|
JsonResponseBody(&resp).
|
||||||
StatusCodeToError().
|
StatusCodeToError().
|
||||||
Do(context.Background())
|
DoWithoutResponse(s.T().Context())
|
||||||
require.NoError(err)
|
require.NoError(err)
|
||||||
require.EqualValues(req.Id, resp.Id)
|
require.EqualValues(req.Id, resp.Id)
|
||||||
}
|
}
|
||||||
@@ -136,7 +141,7 @@ func (s *HappyPathTestSuite) TestHttpProxy() {
|
|||||||
}})
|
}})
|
||||||
require.NoError(err)
|
require.NoError(err)
|
||||||
|
|
||||||
locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes, systemCli, adminCli, nil)
|
locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes, systemCli, adminCli, nil, nil, nil)
|
||||||
locations := []conf.Location{{
|
locations := []conf.Location{{
|
||||||
SkipAuth: false,
|
SkipAuth: false,
|
||||||
PathPrefix: "/api",
|
PathPrefix: "/api",
|
||||||
@@ -150,19 +155,19 @@ func (s *HappyPathTestSuite) TestHttpProxy() {
|
|||||||
cli := httpcli.New()
|
cli := httpcli.New()
|
||||||
req := request{Id: uuid.New().String()}
|
req := request{Id: uuid.New().String()}
|
||||||
resp := response{}
|
resp := response{}
|
||||||
_, err = cli.Post(srv.URL+"/api/endpoint").
|
err = cli.Post(srv.URL+"/api/endpoint").
|
||||||
Header("x-application-token", "token").
|
Header("x-application-token", "token").
|
||||||
Header("x-request-id", requestId).
|
Header("x-request-id", requestId).
|
||||||
Header("x-auth-admin", "mock-token").
|
Header("x-auth-admin", "mock-token").
|
||||||
JsonRequestBody(req).
|
JsonRequestBody(req).
|
||||||
JsonResponseBody(&resp).
|
JsonResponseBody(&resp).
|
||||||
StatusCodeToError().
|
StatusCodeToError().
|
||||||
Do(context.Background())
|
DoWithoutResponse(s.T().Context())
|
||||||
require.NoError(err)
|
require.NoError(err)
|
||||||
require.EqualValues(req.Id, resp.Id)
|
require.EqualValues(req.Id, resp.Id)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *HappyPathTestSuite) TestWsProxy() { // nolint: funlen
|
func (s *HappyPathTestSuite) TestWsProxy() { // nolint:funlen
|
||||||
test, require := test.New(s.T())
|
test, require := test.New(s.T())
|
||||||
config, systemCli, adminCli := s.commonDependencies(test)
|
config, systemCli, adminCli := s.commonDependencies(test)
|
||||||
|
|
||||||
@@ -192,7 +197,7 @@ func (s *HappyPathTestSuite) TestWsProxy() { // nolint: funlen
|
|||||||
}})
|
}})
|
||||||
require.NoError(err)
|
require.NoError(err)
|
||||||
|
|
||||||
locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes, systemCli, adminCli, nil)
|
locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes, systemCli, adminCli, nil, nil, nil)
|
||||||
locations := []conf.Location{{
|
locations := []conf.Location{{
|
||||||
SkipAuth: false,
|
SkipAuth: false,
|
||||||
PathPrefix: "/ws",
|
PathPrefix: "/ws",
|
||||||
@@ -252,7 +257,7 @@ func (s *HappyPathTestSuite) TestAdminAuthorization() {
|
|||||||
logger, err := log.New(log.WithLevel(log.DebugLevel))
|
logger, err := log.New(log.WithLevel(log.DebugLevel))
|
||||||
require.NoError(err)
|
require.NoError(err)
|
||||||
routes := routes.NewRoutes(logger)
|
routes := routes.NewRoutes(logger)
|
||||||
locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil)
|
locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil, nil, nil)
|
||||||
|
|
||||||
locations := []conf.Location{{
|
locations := []conf.Location{{
|
||||||
SkipAuth: false,
|
SkipAuth: false,
|
||||||
@@ -281,28 +286,299 @@ func (s *HappyPathTestSuite) TestAdminAuthorization() {
|
|||||||
cli := httpcli.New()
|
cli := httpcli.New()
|
||||||
req := request{Id: uuid.New().String()}
|
req := request{Id: uuid.New().String()}
|
||||||
resp := response{}
|
resp := response{}
|
||||||
_, err = cli.Post(srv.URL+"/api/endpoint").
|
err = cli.Post(srv.URL+"/api/endpoint").
|
||||||
Header("x-application-token", "token").
|
Header("x-application-token", "token").
|
||||||
Header("x-auth-admin", "mock-token").
|
Header("x-auth-admin", "mock-token").
|
||||||
JsonRequestBody(req).
|
JsonRequestBody(req).
|
||||||
JsonResponseBody(&resp).
|
JsonResponseBody(&resp).
|
||||||
StatusCodeToError().
|
StatusCodeToError().
|
||||||
Do(context.Background())
|
DoWithoutResponse(s.T().Context())
|
||||||
require.NoError(err)
|
require.NoError(err)
|
||||||
require.EqualValues(req.Id, resp.Id)
|
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-application-token", "token").
|
||||||
Header("x-auth-admin", "mock-token").
|
Header("x-auth-admin", "mock-token").
|
||||||
JsonRequestBody(req).
|
JsonRequestBody(req).
|
||||||
JsonResponseBody(&resp).
|
JsonResponseBody(&resp).
|
||||||
StatusCodeToError().
|
StatusCodeToError().
|
||||||
Do(context.Background())
|
DoWithoutResponse(s.T().Context())
|
||||||
errResp := httpcli.ErrorResponse{}
|
errResp := httpcli.ErrorResponse{}
|
||||||
require.ErrorAs(err, &errResp)
|
require.ErrorAs(err, &errResp)
|
||||||
require.EqualValues(http.StatusForbidden, errResp.StatusCode)
|
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"},
|
||||||
|
TokenProvider: "test_provider",
|
||||||
|
AuthenticateMethodPath: "test-user-auth/authenticate",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
ModuleNameList: []string{"target2"},
|
||||||
|
TokenProvider: "test_provider",
|
||||||
|
AuthenticateMethodPath: "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"},
|
||||||
|
TokenProvider: "test_provider",
|
||||||
|
AuthenticateMethodPath: "test-user-auth/authenticate",
|
||||||
|
SkipAppAuth: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
ModuleNameList: []string{"target2"},
|
||||||
|
TokenProvider: "test_provider",
|
||||||
|
AuthenticateMethodPath: "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
|
// nolint:ireturn
|
||||||
func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *client.Client, *client.Client) {
|
func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *client.Client, *client.Client) {
|
||||||
config := conf.Remote{
|
config := conf.Remote{
|
||||||
@@ -316,11 +592,11 @@ func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *
|
|||||||
}
|
}
|
||||||
|
|
||||||
systemService, systemCli := grpct.NewMock(test)
|
systemService, systemCli := grpct.NewMock(test)
|
||||||
systemService.Mock("system/secure/authenticate", func() domain.AuthenticateResponse {
|
systemService.Mock("system/secure/authenticate", func() entity.AuthenticateResponse {
|
||||||
return domain.AuthenticateResponse{
|
return entity.AuthenticateResponse{
|
||||||
Authenticated: true,
|
Authenticated: true,
|
||||||
ErrorReason: "",
|
ErrorReason: "",
|
||||||
AuthData: &domain.AuthData{
|
AuthData: &entity.AppAuthData{
|
||||||
SystemId: 1,
|
SystemId: 1,
|
||||||
DomainId: 2,
|
DomainId: 2,
|
||||||
ServiceId: 3,
|
ServiceId: 3,
|
||||||
@@ -328,22 +604,22 @@ func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *
|
|||||||
AppName: "test",
|
AppName: "test",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}).Mock("system/secure/authorize", func() domain.AuthorizeResponse {
|
}).Mock("system/secure/authorize", func() entity.AuthorizeResponse {
|
||||||
return domain.AuthorizeResponse{Authorized: true}
|
return entity.AuthorizeResponse{Authorized: true}
|
||||||
})
|
})
|
||||||
|
|
||||||
adminService, adminCli := grpct.NewMock(test)
|
adminService, adminCli := grpct.NewMock(test)
|
||||||
adminService.Mock("admin/secure/authenticate", func(req domain.AdminAuthorizeRequest) domain.AdminAuthenticateResponse {
|
adminService.Mock("admin/secure/authenticate", func(req entity.AdminAuthorizeRequest) entity.AdminAuthenticateResponse {
|
||||||
return domain.AdminAuthenticateResponse{
|
return entity.AdminAuthenticateResponse{
|
||||||
Authenticated: true,
|
Authenticated: true,
|
||||||
ErrorReason: "",
|
ErrorReason: "",
|
||||||
AdminId: 1,
|
AdminId: 1,
|
||||||
}
|
}
|
||||||
}).Mock("admin/secure/authorize", func(req domain.AdminAuthorizeRequest) domain.AdminAuthorizeResponse {
|
}).Mock("admin/secure/authorize", func(req entity.AdminAuthorizeRequest) entity.AdminAuthorizeResponse {
|
||||||
if req.Permission == "ok_permission" {
|
if req.Permission == "ok_permission" {
|
||||||
return domain.AdminAuthorizeResponse{Authorized: true}
|
return entity.AdminAuthorizeResponse{Authorized: true}
|
||||||
}
|
}
|
||||||
return domain.AdminAuthorizeResponse{Authorized: false}
|
return entity.AdminAuthorizeResponse{Authorized: false}
|
||||||
})
|
})
|
||||||
|
|
||||||
return config, systemCli, adminCli
|
return config, systemCli, adminCli
|
||||||
|
|||||||
@@ -5,12 +5,14 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/redis/go-redis/v9"
|
|
||||||
"isp-gate-service/assembly"
|
"isp-gate-service/assembly"
|
||||||
"isp-gate-service/conf"
|
"isp-gate-service/conf"
|
||||||
"isp-gate-service/domain"
|
"isp-gate-service/domain"
|
||||||
|
"isp-gate-service/entity"
|
||||||
"isp-gate-service/routes"
|
"isp-gate-service/routes"
|
||||||
|
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/grpc"
|
"github.com/txix-open/isp-kit/grpc"
|
||||||
"github.com/txix-open/isp-kit/grpc/client"
|
"github.com/txix-open/isp-kit/grpc/client"
|
||||||
endpoint2 "github.com/txix-open/isp-kit/grpc/endpoint"
|
endpoint2 "github.com/txix-open/isp-kit/grpc/endpoint"
|
||||||
@@ -54,19 +56,19 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
systemService, systemCli, _ := NewMock(logger)
|
systemService, systemCli, _ := NewMock(logger)
|
||||||
systemService.Mock("system/secure/authenticate", func() domain.AuthenticateResponse {
|
systemService.Mock("system/secure/authenticate", func() entity.AuthenticateResponse {
|
||||||
return domain.AuthenticateResponse{
|
return entity.AuthenticateResponse{
|
||||||
Authenticated: true,
|
Authenticated: true,
|
||||||
ErrorReason: "",
|
ErrorReason: "",
|
||||||
AuthData: &domain.AuthData{
|
AuthData: &entity.AppAuthData{
|
||||||
SystemId: 1,
|
SystemId: 1,
|
||||||
DomainId: 1,
|
DomainId: 1,
|
||||||
ServiceId: 1,
|
ServiceId: 1,
|
||||||
ApplicationId: 1,
|
ApplicationId: 1,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}).Mock("system/secure/authorize", func() domain.AuthorizeResponse {
|
}).Mock("system/secure/authorize", func() entity.AuthorizeResponse {
|
||||||
return domain.AuthorizeResponse{Authorized: true}
|
return entity.AuthorizeResponse{Authorized: true}
|
||||||
})
|
})
|
||||||
|
|
||||||
adminService, _, adminCli := NewMock(logger)
|
adminService, _, adminCli := NewMock(logger)
|
||||||
@@ -84,7 +86,7 @@ func main() {
|
|||||||
})
|
})
|
||||||
targetClients := map[string]*client.Client{"target": targetCli}
|
targetClients := map[string]*client.Client{"target": targetCli}
|
||||||
logger, _ = log.New(log.WithLevel(log.DebugLevel))
|
logger, _ = log.New(log.WithLevel(log.DebugLevel))
|
||||||
locator := assembly.NewLocator(logger, targetClients, nil, routes.NewRoutes(logger), systemCli, adminCli, nil)
|
locator := assembly.NewLocator(logger, targetClients, nil, routes.NewRoutes(logger), systemCli, adminCli, nil, nil, nil)
|
||||||
locations := []conf.Location{{
|
locations := []conf.Location{{
|
||||||
SkipAuth: false,
|
SkipAuth: false,
|
||||||
PathPrefix: "/api",
|
PathPrefix: "/api",
|
||||||
|
|||||||
Reference in new issue
Block a user