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
+94 -27

No files matched your search

+11
View File
@@ -2,7 +2,9 @@ package assembly
import (
"context"
"time"
"isp-gate-service/cache"
"isp-gate-service/conf"
"isp-gate-service/routes"
@@ -18,6 +20,7 @@ import (
const (
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
}),
}
}
+5 -1
View File
@@ -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,
+29
View File
@@ -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()
}
+1
View File
@@ -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:"Пропустить аутентификацию и авторизацию приложения"`
}
+11 -8
View File
@@ -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
}
+29 -11
View File
@@ -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 {
@@ -30,6 +31,7 @@ type userAuthSetting struct {
tokenProviders []string
endpointPrefix string
authModuleName string
authCacheDuration time.Duration
skipAppAuth bool
}
@@ -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,
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
}
}
+7 -6
View File
@@ -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,
+1 -1
View File
@@ -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",