Compare commits

...

7 Commits

Author SHA1 Message Date
1af7248a6f feat: reset proxy cache with sigusr2
All checks were successful
Cadoles/bouncer/pipeline/head This commit looks good
2025-03-18 11:35:15 +01:00
8b132dddd4 feat: add proxy information in sentry context
All checks were successful
Cadoles/bouncer/pipeline/head This commit looks good
2025-03-17 12:07:30 +01:00
6a4a144c97 feat: silence context expired errors
All checks were successful
Cadoles/bouncer/pipeline/head This commit looks good
closes #49
2025-03-10 18:32:36 +01:00
ac7b7e8189 Merge pull request 'Mise en cache des fournisseurs oidc pour améliorer les performances' (#48) from issue-47 into develop
All checks were successful
Cadoles/bouncer/pipeline/head This commit looks good
Reviewed-on: #48
Reviewed-by: Laurent Gourvenec <lgourvenec@cadoles.com>
2025-03-07 13:42:39 +01:00
2df74bad4f feat: cache oidc.Provider to reduce pressure on OIDC identity provider (#47)
All checks were successful
Cadoles/bouncer/pipeline/pr-develop This commit looks good
2025-03-07 11:15:28 +01:00
076a3d784e Merge pull request 'Fix append error in admin/run.go' (#46) from fix-append into develop
All checks were successful
Cadoles/bouncer/pipeline/head This commit looks good
Reviewed-on: #46
2025-03-07 10:21:27 +01:00
826edef358 fix : suppression de append inutile, remonté par go vet
All checks were successful
Cadoles/bouncer/pipeline/head This commit looks good
Cadoles/bouncer/pipeline/pr-develop This commit looks good
2024-11-18 11:05:17 +01:00
13 changed files with 166 additions and 59 deletions

View File

@ -3,4 +3,5 @@ package cache
type Cache[K comparable, V any] interface { type Cache[K comparable, V any] interface {
Get(key K) (V, bool) Get(key K) (V, bool)
Set(key K, value V) Set(key K, value V)
Clear()
} }

View File

@ -25,6 +25,10 @@ func (c *Cache[K, V]) Set(key K, value V) {
c.store.Store(key, value) c.store.Store(key, value)
} }
func (c *Cache[K, V]) Clear() {
c.store.Clear()
}
func NewCache[K comparable, V any]() *Cache[K, V] { func NewCache[K comparable, V any]() *Cache[K, V] {
return &Cache[K, V]{ return &Cache[K, V]{
store: new(sync.Map), store: new(sync.Map),

View File

@ -28,6 +28,11 @@ func (c *Cache[K, V]) Set(key K, value V) {
c.values.Set(key, value) c.values.Set(key, value)
} }
func (c *Cache[K, V]) Clear() {
c.timestamps.Clear()
c.values.Clear()
}
func NewCache[K comparable, V any](values cache.Cache[K, V], timestamps cache.Cache[K, time.Time], ttl time.Duration) *Cache[K, V] { func NewCache[K comparable, V any](values cache.Cache[K, V], timestamps cache.Cache[K, time.Time], ttl time.Duration) *Cache[K, V] {
return &Cache[K, V]{ return &Cache[K, V]{
values: values, values: values,

View File

@ -17,9 +17,7 @@ const (
) )
func RunCommand() *cli.Command { func RunCommand() *cli.Command {
flags := append( flags := common.Flags()
common.Flags(),
)
return &cli.Command{ return &cli.Command{
Name: "run", Name: "run",

View File

@ -20,6 +20,7 @@ func NewDefaultLayersConfig() LayersConfig {
TransportConfig: NewDefaultTransportConfig(), TransportConfig: NewDefaultTransportConfig(),
Timeout: NewInterpolatedDuration(10 * time.Second), Timeout: NewInterpolatedDuration(10 * time.Second),
}, },
ProviderCacheTimeout: NewInterpolatedDuration(time.Hour),
}, },
Sessions: AuthnLayerSessionConfig{ Sessions: AuthnLayerSessionConfig{
TTL: NewInterpolatedDuration(time.Hour), TTL: NewInterpolatedDuration(time.Hour),
@ -46,6 +47,7 @@ type AuthnLayerSessionConfig struct {
type AuthnOIDCLayerConfig struct { type AuthnOIDCLayerConfig struct {
HTTPClient AuthnOIDCHTTPClientConfig `yaml:"httpClient"` HTTPClient AuthnOIDCHTTPClientConfig `yaml:"httpClient"`
ProviderCacheTimeout *InterpolatedDuration `yaml:"providerCacheTimeout"`
} }
type AuthnOIDCHTTPClientConfig struct { type AuthnOIDCHTTPClientConfig struct {

View File

@ -6,6 +6,7 @@ import (
"net/url" "net/url"
"forge.cadoles.com/cadoles/bouncer/internal/store" "forge.cadoles.com/cadoles/bouncer/internal/store"
"github.com/getsentry/sentry-go"
"github.com/pkg/errors" "github.com/pkg/errors"
"gitlab.com/wpetit/goweb/logger" "gitlab.com/wpetit/goweb/logger"
) )
@ -17,6 +18,7 @@ const (
contextKeyLayers contextKey = "layers" contextKeyLayers contextKey = "layers"
contextKeyOriginalURL contextKey = "originalURL" contextKeyOriginalURL contextKey = "originalURL"
contextKeyHandleError contextKey = "handleError" contextKeyHandleError contextKey = "handleError"
contextKeySentryScope contextKey = "sentryScope"
) )
var ( var (
@ -82,3 +84,16 @@ func HandleError(ctx context.Context, w http.ResponseWriter, r *http.Request, st
fn(w, r, status, err) fn(w, r, status, err)
} }
func withSentryScope(ctx context.Context, scope *sentry.Scope) context.Context {
return context.WithValue(ctx, contextKeySentryScope, scope)
}
func SentryScope(ctx context.Context) (*sentry.Scope, error) {
scope, err := ctxValue[*sentry.Scope](ctx, contextKeySentryScope)
if err != nil {
return nil, errors.WithStack(err)
}
return scope, nil
}

View File

@ -9,6 +9,7 @@ import (
"forge.cadoles.com/Cadoles/go-proxy/wildcard" "forge.cadoles.com/Cadoles/go-proxy/wildcard"
"forge.cadoles.com/cadoles/bouncer/internal/cache" "forge.cadoles.com/cadoles/bouncer/internal/cache"
"forge.cadoles.com/cadoles/bouncer/internal/store" "forge.cadoles.com/cadoles/bouncer/internal/store"
"github.com/getsentry/sentry-go"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"gitlab.com/wpetit/goweb/logger" "gitlab.com/wpetit/goweb/logger"
@ -76,6 +77,13 @@ func (d *Director) rewriteRequest(r *http.Request) (*http.Request, error) {
proxyCtx = withLayers(proxyCtx, layers) proxyCtx = withLayers(proxyCtx, layers)
r = r.WithContext(proxyCtx) r = r.WithContext(proxyCtx)
if sentryScope, _ := SentryScope(ctx); sentryScope != nil {
sentryScope.SetContext("bouncer", sentry.Context{
"proxy_name": p.Name,
"proxy_target": r.URL.String(),
})
}
return r, nil return r, nil
} }
} }
@ -91,9 +99,12 @@ const proxiesCacheKey = "proxies"
func (d *Director) getProxies(ctx context.Context) ([]*store.Proxy, error) { func (d *Director) getProxies(ctx context.Context) ([]*store.Proxy, error) {
proxies, exists := d.proxyCache.Get(proxiesCacheKey) proxies, exists := d.proxyCache.Get(proxiesCacheKey)
if exists { if exists {
logger.Debug(ctx, "using cached proxies")
return proxies, nil return proxies, nil
} }
logger.Debug(ctx, "querying fresh proxies")
headers, err := d.proxyRepository.QueryProxy(ctx, store.WithProxyQueryEnabled(true)) headers, err := d.proxyRepository.QueryProxy(ctx, store.WithProxyQueryEnabled(true))
if err != nil { if err != nil {
return nil, errors.WithStack(err) return nil, errors.WithStack(err)
@ -126,9 +137,12 @@ func (d *Director) getLayers(ctx context.Context, proxyName store.ProxyName) ([]
layers, exists := d.layerCache.Get(cacheKey) layers, exists := d.layerCache.Get(cacheKey)
if exists { if exists {
logger.Debug(ctx, "using cached layers")
return layers, nil return layers, nil
} }
logger.Debug(ctx, "querying fresh layers")
headers, err := d.layerRepository.QueryLayers(ctx, proxyName, store.WithLayerQueryEnabled(true)) headers, err := d.layerRepository.QueryLayers(ctx, proxyName, store.WithLayerQueryEnabled(true))
if err != nil { if err != nil {
return nil, errors.WithStack(err) return nil, errors.WithStack(err)
@ -216,7 +230,9 @@ func (d *Director) ResponseTransformer() proxy.ResponseTransformer {
func (d *Director) Middleware() proxy.Middleware { func (d *Director) Middleware() proxy.Middleware {
return func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) { fn := func(w http.ResponseWriter, r *http.Request) {
sentry.ConfigureScope(func(scope *sentry.Scope) {
ctx := withHandleError(r.Context(), d.handleError) ctx := withHandleError(r.Context(), d.handleError)
ctx = withSentryScope(ctx, scope)
r = r.WithContext(ctx) r = r.WithContext(ctx)
r, err := d.rewriteRequest(r) r, err := d.rewriteRequest(r)
@ -250,6 +266,7 @@ func (d *Director) Middleware() proxy.Middleware {
handler := createMiddlewareChain(next, httpMiddlewares) handler := createMiddlewareChain(next, httpMiddlewares)
handler.ServeHTTP(w, r) handler.ServeHTTP(w, r)
})
} }
return http.HandlerFunc(fn) return http.HandlerFunc(fn)

View File

@ -13,6 +13,7 @@ import (
"time" "time"
"forge.cadoles.com/Cadoles/go-proxy/wildcard" "forge.cadoles.com/Cadoles/go-proxy/wildcard"
"forge.cadoles.com/cadoles/bouncer/internal/cache"
"forge.cadoles.com/cadoles/bouncer/internal/proxy/director" "forge.cadoles.com/cadoles/bouncer/internal/proxy/director"
"forge.cadoles.com/cadoles/bouncer/internal/proxy/director/layer/authn" "forge.cadoles.com/cadoles/bouncer/internal/proxy/director/layer/authn"
"forge.cadoles.com/cadoles/bouncer/internal/store" "forge.cadoles.com/cadoles/bouncer/internal/store"
@ -27,6 +28,7 @@ type Authenticator struct {
store sessions.Store store sessions.Store
httpTransport *http.Transport httpTransport *http.Transport
httpClientTimeout time.Duration httpClientTimeout time.Duration
oidcProviderCache cache.Cache[string, *oidc.Provider]
} }
func (a *Authenticator) PreAuthentication(w http.ResponseWriter, r *http.Request, layer *store.Layer) error { func (a *Authenticator) PreAuthentication(w http.ResponseWriter, r *http.Request, layer *store.Layer) error {
@ -378,17 +380,25 @@ func (a *Authenticator) getClient(options *LayerOptions, redirectURL string) (*C
Transport: transport, Transport: transport,
} }
provider, exists := a.oidcProviderCache.Get(options.OIDC.IssuerURL)
if !exists {
var err error
ctx = oidc.ClientContext(ctx, httpClient) ctx = oidc.ClientContext(ctx, httpClient)
if options.OIDC.SkipIssuerVerification { if options.OIDC.SkipIssuerVerification {
ctx = oidc.InsecureIssuerURLContext(ctx, options.OIDC.IssuerURL) ctx = oidc.InsecureIssuerURLContext(ctx, options.OIDC.IssuerURL)
} }
provider, err := oidc.NewProvider(ctx, options.OIDC.IssuerURL) logger.Debug(ctx, "refreshing oidc provider", logger.F("issuerURL", options.OIDC.IssuerURL))
provider, err = oidc.NewProvider(ctx, options.OIDC.IssuerURL)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not create oidc provider") return nil, errors.Wrap(err, "could not create oidc provider")
} }
a.oidcProviderCache.Set(options.OIDC.IssuerURL, provider)
}
client := NewClient( client := NewClient(
WithCredentials(options.OIDC.ClientID, options.OIDC.ClientSecret), WithCredentials(options.OIDC.ClientID, options.OIDC.ClientSecret),
WithProvider(provider), WithProvider(provider),

View File

@ -1,8 +1,13 @@
package oidc package oidc
import ( import (
"time"
"forge.cadoles.com/cadoles/bouncer/internal/cache/memory"
"forge.cadoles.com/cadoles/bouncer/internal/cache/ttl"
"forge.cadoles.com/cadoles/bouncer/internal/proxy/director/layer/authn" "forge.cadoles.com/cadoles/bouncer/internal/proxy/director/layer/authn"
"forge.cadoles.com/cadoles/bouncer/internal/store" "forge.cadoles.com/cadoles/bouncer/internal/store"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/gorilla/sessions" "github.com/gorilla/sessions"
) )
@ -14,5 +19,10 @@ func NewLayer(store sessions.Store, funcs ...OptionFunc) *authn.Layer {
httpTransport: opts.HTTPTransport, httpTransport: opts.HTTPTransport,
httpClientTimeout: opts.HTTPClientTimeout, httpClientTimeout: opts.HTTPClientTimeout,
store: store, store: store,
oidcProviderCache: ttl.NewCache(
memory.NewCache[string, *oidc.Provider](),
memory.NewCache[string, time.Time](),
opts.OIDCProviderCacheTimeout,
),
}, opts.AuthnOptions...) }, opts.AuthnOptions...)
} }

View File

@ -11,6 +11,7 @@ type Options struct {
HTTPTransport *http.Transport HTTPTransport *http.Transport
HTTPClientTimeout time.Duration HTTPClientTimeout time.Duration
AuthnOptions []authn.OptionFunc AuthnOptions []authn.OptionFunc
OIDCProviderCacheTimeout time.Duration
} }
type OptionFunc func(opts *Options) type OptionFunc func(opts *Options)
@ -33,11 +34,18 @@ func WithAuthnOptions(funcs ...authn.OptionFunc) OptionFunc {
} }
} }
func WithOIDCProviderCacheTimeout(timeout time.Duration) OptionFunc {
return func(opts *Options) {
opts.OIDCProviderCacheTimeout = timeout
}
}
func NewOptions(funcs ...OptionFunc) *Options { func NewOptions(funcs ...OptionFunc) *Options {
opts := &Options{ opts := &Options{
HTTPTransport: http.DefaultTransport.(*http.Transport), HTTPTransport: http.DefaultTransport.(*http.Transport),
HTTPClientTimeout: 30 * time.Second, HTTPClientTimeout: 30 * time.Second,
AuthnOptions: make([]authn.OptionFunc, 0), AuthnOptions: make([]authn.OptionFunc, 0),
OIDCProviderCacheTimeout: time.Hour,
} }
for _, fn := range funcs { for _, fn := range funcs {

View File

@ -13,8 +13,11 @@ import (
"net/http/httputil" "net/http/httputil"
"net/http/pprof" "net/http/pprof"
"net/url" "net/url"
"os"
"os/signal"
"path/filepath" "path/filepath"
"strconv" "strconv"
"syscall"
"time" "time"
"forge.cadoles.com/Cadoles/go-proxy" "forge.cadoles.com/Cadoles/go-proxy"
@ -94,24 +97,15 @@ func (s *Server) run(parentCtx context.Context, addrs chan net.Addr, errs chan e
logger.Info(ctx, "http server listening") logger.Info(ctx, "http server listening")
layerCache, proxyCache, cancel := s.createDirectorCaches(ctx)
defer cancel()
director := director.New( director := director.New(
s.proxyRepository, s.proxyRepository,
s.layerRepository, s.layerRepository,
director.WithLayers(s.directorLayers...), director.WithLayers(s.directorLayers...),
director.WithLayerCache( director.WithLayerCache(layerCache),
ttl.NewCache( director.WithProxyCache(proxyCache),
memory.NewCache[string, []*store.Layer](),
memory.NewCache[string, time.Time](),
s.directorCacheTTL,
),
),
director.WithProxyCache(
ttl.NewCache(
memory.NewCache[string, []*store.Proxy](),
memory.NewCache[string, time.Time](),
s.directorCacheTTL,
),
),
director.WithHandleErrorFunc(s.handleError), director.WithHandleErrorFunc(s.handleError),
) )
@ -205,6 +199,44 @@ func (s *Server) run(parentCtx context.Context, addrs chan net.Addr, errs chan e
logger.Info(ctx, "http server exiting") logger.Info(ctx, "http server exiting")
} }
func (s *Server) createDirectorCaches(ctx context.Context) (*ttl.Cache[string, []*store.Layer], *ttl.Cache[string, []*store.Proxy], func()) {
layerCache := ttl.NewCache(
memory.NewCache[string, []*store.Layer](),
memory.NewCache[string, time.Time](),
s.directorCacheTTL,
)
proxyCache := ttl.NewCache(
memory.NewCache[string, []*store.Proxy](),
memory.NewCache[string, time.Time](),
s.directorCacheTTL,
)
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGUSR2)
go func() {
for {
_, ok := <-sig
if !ok {
return
}
logger.Info(ctx, "received sigusr2 signal, clearing proxies and layers cache")
layerCache.Clear()
proxyCache.Clear()
}
}()
cancel := func() {
close(sig)
}
return layerCache, proxyCache, cancel
}
func (s *Server) createReverseProxy(ctx context.Context, target *url.URL) *httputil.ReverseProxy { func (s *Server) createReverseProxy(ctx context.Context, target *url.URL) *httputil.ReverseProxy {
reverseProxy := httputil.NewSingleHostReverseProxy(target) reverseProxy := httputil.NewSingleHostReverseProxy(target)
@ -233,9 +265,7 @@ func (s *Server) handleDefault(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleError(w http.ResponseWriter, r *http.Request, status int, err error) { func (s *Server) handleError(w http.ResponseWriter, r *http.Request, status int, err error) {
err = errors.WithStack(err) err = errors.WithStack(err)
if errors.Is(err, context.Canceled) { if !errors.Is(err, context.Canceled) {
logger.Warn(r.Context(), err.Error(), logger.E(err))
} else {
logger.Error(r.Context(), err.Error(), logger.CapturedE(err)) logger.Error(r.Context(), err.Error(), logger.CapturedE(err))
} }

View File

@ -37,5 +37,6 @@ func setupAuthnOIDCLayer(conf *config.Config) (director.Layer, error) {
authn.WithTemplateDir(string(conf.Layers.Authn.TemplateDir)), authn.WithTemplateDir(string(conf.Layers.Authn.TemplateDir)),
authn.WithDebug(bool(conf.Layers.Authn.Debug)), authn.WithDebug(bool(conf.Layers.Authn.Debug)),
), ),
oidc.WithOIDCProviderCacheTimeout(time.Duration(*conf.Layers.Authn.OIDC.ProviderCacheTimeout)),
), nil ), nil
} }

View File

@ -131,6 +131,12 @@ proxy:
# Les proxys/layers sont mis en cache local pour une durée de 30s # Les proxys/layers sont mis en cache local pour une durée de 30s
# par défaut. Si les modifications sont rares, vous pouvez augmenter # par défaut. Si les modifications sont rares, vous pouvez augmenter
# cette valeur pour réduire la "pression" sur le serveur Redis. # cette valeur pour réduire la "pression" sur le serveur Redis.
# Il est possible de forcer la réinitialisation du cache en envoyant
# le signal SIGUSR2 au processus Bouncer.
#
# Exemple
#
# kill -s USR2 $(pgrep bouncer)
ttl: 30s ttl: 30s
# Configuration du transport HTTP(S) # Configuration du transport HTTP(S)