MSP-7470 Ref users auth cache

This commit is contained in:
Синельник Тимур Романович committed 2026-04-02 15:57:30 +03:00
1 parent a185cb0878
commit 9d9353cf57
8 files changed
+103 -36

No files matched your search

+12 -1
View File
@@ -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"
@@ -17,7 +19,8 @@ import (
) )
const ( const (
routerModuleName = "isp-router-service" routerModuleName = "isp-router-service"
usersAuthCachePurgeInterval = 5 * time.Second
) )
type Assembly struct { type Assembly struct {
@@ -33,6 +36,8 @@ type Assembly struct {
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) {
@@ -87,6 +92,7 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
adminCli: adminCli, adminCli: adminCli,
lockerCli: lockerCli, lockerCli: lockerCli,
routerLb: lb.NewRoundRobin(nil), routerLb: lb.NewRoundRobin(nil),
usersAuthCache: cache.New(),
}, nil }, nil
} }
@@ -110,6 +116,7 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error
a.adminCli, a.adminCli,
a.lockerCli, a.lockerCli,
a.routerLb, a.routerLb,
a.usersAuthCache,
) )
handler, err := locator.Handler(newCfg, a.locations) handler, err := locator.Handler(newCfg, a.locations)
if err != nil { if err != nil {
@@ -144,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
}),
} }
} }
+5 -1
View File
@@ -8,6 +8,7 @@ import (
"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"
@@ -31,6 +32,7 @@ type Locator struct {
adminCli *client.Client adminCli *client.Client
lockerCli *client.Client lockerCli *client.Client
routerLb *lb.RoundRobin routerLb *lb.RoundRobin
usersAuthCache *cache.Cache
} }
func NewLocator( func NewLocator(
@@ -42,6 +44,7 @@ func NewLocator(
adminCli *client.Client, adminCli *client.Client,
lockerCli *client.Client, lockerCli *client.Client,
routerLb *lb.RoundRobin, routerLb *lb.RoundRobin,
usersAuthCache *cache.Cache,
) Locator { ) Locator {
return Locator{ return Locator{
logger: logger, logger: logger,
@@ -52,6 +55,7 @@ func NewLocator(
adminCli: adminCli, adminCli: adminCli,
lockerCli: lockerCli, lockerCli: lockerCli,
routerLb: routerLb, 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) authenticationCache := repository.NewAuthenticationCache(time.Duration(config.Caching.AuthenticationDataInSec) * time.Second)
authentication := service.NewAuthentication(authenticationCache, systemRepo) 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) userAuthRepo := repository.NewUserAuth(l.routerLb)
userAuthentication, err := service.NewUserAuthentication( userAuthentication, err := service.NewUserAuthentication(
config.CustomAuth, config.CustomAuth,
+29
View File
@@ -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()
} }
+1
View File
@@ -95,5 +95,6 @@ type UserAuthSetting struct {
EndpointPrefixes []string `schema:"Префиксы пути,для которых настраивается аутентификация/авторизация" validate:"required"` EndpointPrefixes []string `schema:"Префиксы пути,для которых настраивается аутентификация/авторизация" validate:"required"`
TokenProviders []string `schema:"Список названий методов получения токена из запроса,возвращает токен из первого удачного" validate:"required,min=1"` TokenProviders []string `schema:"Список названий методов получения токена из запроса,возвращает токен из первого удачного" validate:"required,min=1"`
AuthModuleName string `schema:"Название модуля для аутентификации/авторизации" validate:"required"` AuthModuleName string `schema:"Название модуля для аутентификации/авторизации" validate:"required"`
CacheDataInSec int `schema:"Время кеширования данных авторизации пользователя,отключен при значениях <=0,в секундах"`
SkipAppAuth bool `schema:"Пропустить аутентификацию и авторизацию приложения"` SkipAppAuth bool `schema:"Пропустить аутентификацию и авторизацию приложения"`
} }
+11 -8
View File
@@ -5,7 +5,6 @@ import (
"fmt" "fmt"
"time" "time"
"isp-gate-service/cache"
"isp-gate-service/domain" "isp-gate-service/domain"
"isp-gate-service/entity" "isp-gate-service/entity"
@@ -13,15 +12,18 @@ import (
"github.com/txix-open/isp-kit/json" "github.com/txix-open/isp-kit/json"
) )
type UserAuthenticationCache struct { type Cache interface {
cache *cache.Cache Get(key string) ([]byte, bool)
duration time.Duration 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{ return UserAuthenticationCache{
duration: duration, cache: cache,
cache: cache.New(),
} }
} }
@@ -45,13 +47,14 @@ func (r UserAuthenticationCache) Set(
authModuleName string, authModuleName string,
token string, token string,
data entity.UserAuthData, data entity.UserAuthData,
duration time.Duration,
) error { ) 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")
} }
r.cache.Set(r.key(authModuleName, token), value, r.duration) r.cache.Set(r.key(authModuleName, token), value, duration)
return nil return nil
} }
+37 -19
View File
@@ -9,13 +9,14 @@ import (
"isp-gate-service/service/token_provider" "isp-gate-service/service/token_provider"
"sort" "sort"
"strings" "strings"
"time"
"github.com/pkg/errors" "github.com/pkg/errors"
) )
type UserAuthenticationCache interface { type UserAuthenticationCache interface {
Get(ctx context.Context, authModuleName string, token string) (*entity.UserAuthData, error) 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 { type UserAuthenticationRepo interface {
@@ -27,10 +28,11 @@ type TokenProvider interface {
} }
type userAuthSetting struct { type userAuthSetting struct {
tokenProviders []string tokenProviders []string
endpointPrefix string endpointPrefix string
authModuleName string authModuleName string
skipAppAuth bool authCacheDuration time.Duration
skipAppAuth bool
} }
type UserAuthentication struct { type UserAuthentication struct {
@@ -74,12 +76,16 @@ func NewUserAuthentication(
) )
} }
} }
cacheDuration := time.Duration(setting.CacheDataInSec) * time.Second
for _, prefix := range setting.EndpointPrefixes { for _, prefix := range setting.EndpointPrefixes {
endpointsSettings = append(endpointsSettings, userAuthSetting{ endpointsSettings = append(endpointsSettings, userAuthSetting{
endpointPrefix: prefix, endpointPrefix: prefix,
authModuleName: setting.AuthModuleName, authModuleName: setting.AuthModuleName,
tokenProviders: setting.TokenProviders, tokenProviders: setting.TokenProviders,
skipAppAuth: setting.SkipAppAuth, skipAppAuth: setting.SkipAppAuth,
authCacheDuration: cacheDuration,
}) })
} }
} }
@@ -115,9 +121,8 @@ func (s UserAuthentication) Authenticate(ctx *request.Context) (*domain.Authenti
resp, err := s.authenticate( resp, err := s.authenticate(
ctx.Context(), ctx.Context(),
setting.authModuleName, setting,
token, token,
setting.skipAppAuth,
) )
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "auth") return nil, errors.WithMessage(err, "auth")
@@ -147,32 +152,45 @@ func (s UserAuthentication) extractToken(ctx *request.Context, providers []strin
func (s UserAuthentication) authenticate( func (s UserAuthentication) authenticate(
ctx context.Context, ctx context.Context,
authModuleName string, setting userAuthSetting,
token string, token string,
skipAppAuth bool,
) (*domain.AuthenticateUserResponse, error) { ) (*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 { switch {
case errors.Is(err, domain.ErrAuthenticationCacheMiss): 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 { 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 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 { if err != nil {
return nil, errors.WithMessage(err, "auth cache set") return nil, errors.WithMessage(err, "auth cache set")
} }
return s.convertAuthReponse(resp, skipAppAuth), nil return s.convertAuthReponse(resp, setting.skipAppAuth), nil
case err != nil: case err != nil:
return nil, errors.WithMessage(err, "auth cache get") return nil, errors.WithMessage(err, "auth cache get")
default: default:
return &domain.AuthenticateUserResponse{ return &domain.AuthenticateUserResponse{
Authenticated: true, Authenticated: true,
ErrorReason: "", ErrorReason: "",
AuthData: s.convertAuthData(authData, skipAppAuth), AuthData: s.convertAuthData(authData, setting.skipAppAuth),
}, nil }, nil
} }
} }
+7 -6
View File
@@ -12,6 +12,7 @@ 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/entity" "isp-gate-service/entity"
"isp-gate-service/routes" "isp-gate-service/routes"
@@ -90,7 +91,7 @@ func (s *HappyPathTestSuite) TestGrpcProxy() {
}}) }})
require.NoError(err) 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{{ locations := []conf.Location{{
SkipAuth: false, SkipAuth: false,
@@ -140,7 +141,7 @@ func (s *HappyPathTestSuite) TestHttpProxy() {
}}) }})
require.NoError(err) 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{{ locations := []conf.Location{{
SkipAuth: false, SkipAuth: false,
PathPrefix: "/api", PathPrefix: "/api",
@@ -196,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, 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",
@@ -256,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, nil) locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil, nil, nil)
locations := []conf.Location{{ locations := []conf.Location{{
SkipAuth: false, SkipAuth: false,
@@ -358,7 +359,7 @@ func (s *HappyPathTestSuite) TestUserAuthorization() { // nolint:funlen
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, rr) locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil, rr, cache.New())
locations := []conf.Location{{ locations := []conf.Location{{
SkipAuth: false, SkipAuth: false,
@@ -485,7 +486,7 @@ func (s *HappyPathTestSuite) TestUserAuthorization_SkipAppAuth() { // nolint:fun
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, rr) locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil, rr, cache.New())
locations := []conf.Location{{ locations := []conf.Location{{
SkipAuth: false, SkipAuth: false,
+1 -1
View File
@@ -86,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, 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",