From 9d9353cf57717cbc8954f0dae188925169945a5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Thu, 2 Apr 2026 15:36:43 +0300 Subject: [PATCH] MSP-7470 Ref users auth cache --- assembly/assembly.go | 13 +++++- assembly/locator.go | 6 ++- cache/cache.go | 29 +++++++++++++ conf/remote.go | 1 + repository/user_authentication_cache.go | 19 +++++---- service/user_authentication.go | 56 ++++++++++++++++--------- tests/acceptance_test.go | 13 +++--- tests/bench/bench.go | 2 +- 8 files changed, 103 insertions(+), 36 deletions(-) diff --git a/assembly/assembly.go b/assembly/assembly.go index 59c9262..5677ad7 100644 --- a/assembly/assembly.go +++ b/assembly/assembly.go @@ -2,7 +2,9 @@ package assembly import ( "context" + "time" + "isp-gate-service/cache" "isp-gate-service/conf" "isp-gate-service/routes" @@ -17,7 +19,8 @@ import ( ) const ( - routerModuleName = "isp-router-service" + routerModuleName = "isp-router-service" + usersAuthCachePurgeInterval = 5 * time.Second ) type Assembly struct { @@ -33,6 +36,8 @@ type Assembly struct { locations []conf.Location grpcClientByModuleName map[string]*client.Client httpHostManagerByModuleName map[string]*lb.RoundRobin + + usersAuthCache *cache.Cache } func New(boot *bootstrap.Bootstrap) (*Assembly, error) { @@ -87,6 +92,7 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) { adminCli: adminCli, lockerCli: lockerCli, routerLb: lb.NewRoundRobin(nil), + usersAuthCache: cache.New(), }, nil } @@ -110,6 +116,7 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error a.adminCli, a.lockerCli, a.routerLb, + a.usersAuthCache, ) handler, err := locator.Handler(newCfg, a.locations) if err != nil { @@ -144,6 +151,10 @@ func (a *Assembly) Runners() []app.Runner { app.RunnerFunc(func(ctx context.Context) error { return a.boot.ClusterCli.Run(ctx, eventHandler) }), + app.RunnerFunc(func(ctx context.Context) error { + a.usersAuthCache.StartCleaner(ctx, usersAuthCachePurgeInterval) + return nil + }), } } diff --git a/assembly/locator.go b/assembly/locator.go index 7e44244..b81976f 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -8,6 +8,7 @@ import ( "github.com/txix-open/isp-kit/metrics" "github.com/txix-open/isp-kit/metrics/http_metrics" + "isp-gate-service/cache" "isp-gate-service/conf" "isp-gate-service/middleware" "isp-gate-service/proxy" @@ -31,6 +32,7 @@ type Locator struct { adminCli *client.Client lockerCli *client.Client routerLb *lb.RoundRobin + usersAuthCache *cache.Cache } func NewLocator( @@ -42,6 +44,7 @@ func NewLocator( adminCli *client.Client, lockerCli *client.Client, routerLb *lb.RoundRobin, + usersAuthCache *cache.Cache, ) Locator { return Locator{ logger: logger, @@ -52,6 +55,7 @@ func NewLocator( adminCli: adminCli, lockerCli: lockerCli, routerLb: routerLb, + usersAuthCache: usersAuthCache, } } @@ -62,7 +66,7 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha authenticationCache := repository.NewAuthenticationCache(time.Duration(config.Caching.AuthenticationDataInSec) * time.Second) authentication := service.NewAuthentication(authenticationCache, systemRepo) - userAuthenticationCache := repository.NewUserAuthenticationCache(time.Duration(config.Caching.AuthenticationDataInSec) * time.Second) + userAuthenticationCache := repository.NewUserAuthenticationCache(l.usersAuthCache) userAuthRepo := repository.NewUserAuth(l.routerLb) userAuthentication, err := service.NewUserAuthentication( config.CustomAuth, diff --git a/cache/cache.go b/cache/cache.go index feb6565..ef9b025 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -1,6 +1,7 @@ package cache import ( + "context" "sync" "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 { return time.Now() } diff --git a/conf/remote.go b/conf/remote.go index b48b5bc..2730523 100644 --- a/conf/remote.go +++ b/conf/remote.go @@ -95,5 +95,6 @@ type UserAuthSetting struct { EndpointPrefixes []string `schema:"Префиксы пути,для которых настраивается аутентификация/авторизация" validate:"required"` TokenProviders []string `schema:"Список названий методов получения токена из запроса,возвращает токен из первого удачного" validate:"required,min=1"` AuthModuleName string `schema:"Название модуля для аутентификации/авторизации" validate:"required"` + CacheDataInSec int `schema:"Время кеширования данных авторизации пользователя,отключен при значениях <=0,в секундах"` SkipAppAuth bool `schema:"Пропустить аутентификацию и авторизацию приложения"` } diff --git a/repository/user_authentication_cache.go b/repository/user_authentication_cache.go index 0f5d49a..43876ce 100644 --- a/repository/user_authentication_cache.go +++ b/repository/user_authentication_cache.go @@ -5,7 +5,6 @@ import ( "fmt" "time" - "isp-gate-service/cache" "isp-gate-service/domain" "isp-gate-service/entity" @@ -13,15 +12,18 @@ import ( "github.com/txix-open/isp-kit/json" ) -type UserAuthenticationCache struct { - cache *cache.Cache - duration time.Duration +type Cache interface { + Get(key string) ([]byte, bool) + Set(key string, data []byte, lifeTime time.Duration) } -func NewUserAuthenticationCache(duration time.Duration) UserAuthenticationCache { +type UserAuthenticationCache struct { + cache Cache +} + +func NewUserAuthenticationCache(cache Cache) UserAuthenticationCache { return UserAuthenticationCache{ - duration: duration, - cache: cache.New(), + cache: cache, } } @@ -45,13 +47,14 @@ func (r UserAuthenticationCache) Set( authModuleName 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(authModuleName, token), value, r.duration) + r.cache.Set(r.key(authModuleName, token), value, duration) return nil } diff --git a/service/user_authentication.go b/service/user_authentication.go index 29e0ae8..e12afd3 100644 --- a/service/user_authentication.go +++ b/service/user_authentication.go @@ -9,13 +9,14 @@ import ( "isp-gate-service/service/token_provider" "sort" "strings" + "time" "github.com/pkg/errors" ) type UserAuthenticationCache interface { Get(ctx context.Context, authModuleName string, token string) (*entity.UserAuthData, error) - Set(ctx context.Context, authModuleName string, token string, data entity.UserAuthData) error + Set(ctx context.Context, authModuleName string, token string, data entity.UserAuthData, duration time.Duration) error } type UserAuthenticationRepo interface { @@ -27,10 +28,11 @@ type TokenProvider interface { } type userAuthSetting struct { - tokenProviders []string - endpointPrefix string - authModuleName string - skipAppAuth bool + tokenProviders []string + endpointPrefix string + authModuleName string + authCacheDuration time.Duration + skipAppAuth bool } type UserAuthentication struct { @@ -74,12 +76,16 @@ func NewUserAuthentication( ) } } + + cacheDuration := time.Duration(setting.CacheDataInSec) * time.Second + for _, prefix := range setting.EndpointPrefixes { endpointsSettings = append(endpointsSettings, userAuthSetting{ - endpointPrefix: prefix, - authModuleName: setting.AuthModuleName, - tokenProviders: setting.TokenProviders, - skipAppAuth: setting.SkipAppAuth, + endpointPrefix: prefix, + authModuleName: setting.AuthModuleName, + tokenProviders: setting.TokenProviders, + skipAppAuth: setting.SkipAppAuth, + authCacheDuration: cacheDuration, }) } } @@ -115,9 +121,8 @@ func (s UserAuthentication) Authenticate(ctx *request.Context) (*domain.Authenti resp, err := s.authenticate( ctx.Context(), - setting.authModuleName, + setting, token, - setting.skipAppAuth, ) if err != nil { return nil, errors.WithMessage(err, "auth") @@ -147,32 +152,45 @@ func (s UserAuthentication) extractToken(ctx *request.Context, providers []strin func (s UserAuthentication) authenticate( ctx context.Context, - authModuleName string, + setting userAuthSetting, token string, - skipAppAuth bool, ) (*domain.AuthenticateUserResponse, error) { - authData, err := s.cache.Get(ctx, authModuleName, token) + if setting.authCacheDuration <= 0 { + resp, err := s.repo.Authenticate(ctx, setting.authModuleName, 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.authModuleName, token) switch { case errors.Is(err, domain.ErrAuthenticationCacheMiss): - resp, err := s.repo.Authenticate(ctx, authModuleName, token) + resp, err := s.repo.Authenticate(ctx, setting.authModuleName, token) if err != nil { return nil, errors.WithMessage(err, "auth repo authenticate") } if !resp.Authenticated { - return s.convertAuthReponse(resp, skipAppAuth), nil + return s.convertAuthReponse(resp, setting.skipAppAuth), nil } - err = s.cache.Set(ctx, authModuleName, token, *resp.AuthData) + err = s.cache.Set( + ctx, + setting.authModuleName, + token, + *resp.AuthData, + setting.authCacheDuration, + ) if err != nil { return nil, errors.WithMessage(err, "auth cache set") } - return s.convertAuthReponse(resp, skipAppAuth), nil + 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, skipAppAuth), + AuthData: s.convertAuthData(authData, setting.skipAppAuth), }, nil } } diff --git a/tests/acceptance_test.go b/tests/acceptance_test.go index 2849574..dd9903b 100644 --- a/tests/acceptance_test.go +++ b/tests/acceptance_test.go @@ -12,6 +12,7 @@ import ( "time" "isp-gate-service/assembly" + "isp-gate-service/cache" "isp-gate-service/conf" "isp-gate-service/entity" "isp-gate-service/routes" @@ -90,7 +91,7 @@ func (s *HappyPathTestSuite) TestGrpcProxy() { }}) require.NoError(err) - locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil, nil) + locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil, nil, nil) locations := []conf.Location{{ SkipAuth: false, @@ -140,7 +141,7 @@ func (s *HappyPathTestSuite) TestHttpProxy() { }}) require.NoError(err) - locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes, systemCli, adminCli, nil, nil) + locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes, systemCli, adminCli, nil, nil, nil) locations := []conf.Location{{ SkipAuth: false, PathPrefix: "/api", @@ -196,7 +197,7 @@ func (s *HappyPathTestSuite) TestWsProxy() { // nolint:funlen }}) require.NoError(err) - locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes, systemCli, adminCli, nil, nil) + locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes, systemCli, adminCli, nil, nil, nil) locations := []conf.Location{{ SkipAuth: false, PathPrefix: "/ws", @@ -256,7 +257,7 @@ func (s *HappyPathTestSuite) TestAdminAuthorization() { logger, err := log.New(log.WithLevel(log.DebugLevel)) require.NoError(err) routes := routes.NewRoutes(logger) - locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil, nil) + locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil, nil, nil) locations := []conf.Location{{ SkipAuth: false, @@ -358,7 +359,7 @@ func (s *HappyPathTestSuite) TestUserAuthorization() { // nolint:funlen 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) + locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil, rr, cache.New()) locations := []conf.Location{{ SkipAuth: false, @@ -485,7 +486,7 @@ func (s *HappyPathTestSuite) TestUserAuthorization_SkipAppAuth() { // nolint:fun 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) + locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil, rr, cache.New()) locations := []conf.Location{{ SkipAuth: false, diff --git a/tests/bench/bench.go b/tests/bench/bench.go index 026593c..98a13ad 100644 --- a/tests/bench/bench.go +++ b/tests/bench/bench.go @@ -86,7 +86,7 @@ func main() { }) targetClients := map[string]*client.Client{"target": targetCli} logger, _ = log.New(log.WithLevel(log.DebugLevel)) - locator := assembly.NewLocator(logger, targetClients, nil, routes.NewRoutes(logger), systemCli, adminCli, nil, nil) + locator := assembly.NewLocator(logger, targetClients, nil, routes.NewRoutes(logger), systemCli, adminCli, nil, nil, nil) locations := []conf.Location{{ SkipAuth: false, PathPrefix: "/api",