Compare commits
16 Commits
v2024.10.1
...
v2025.3.18
Author | SHA1 | Date | |
---|---|---|---|
1af7248a6f | |||
8b132dddd4 | |||
6a4a144c97 | |||
ac7b7e8189 | |||
2df74bad4f | |||
076a3d784e | |||
826edef358 | |||
ce7415af20 | |||
7cc9de180c | |||
74c2a2c055 | |||
239d4573c3 | |||
cffe3eca1b | |||
a686c52aed | |||
c0470ca623 | |||
c611705d45 | |||
16fa751dc7 |
@ -60,7 +60,7 @@ Retourne `nil` si le cookie n'existe pas.
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
##### `set_cookie(ctx, cookie Cookie)`
|
##### `add_cookie(ctx, cookie Cookie)`
|
||||||
|
|
||||||
Définit un cookie sur la requête/réponse (en fonction du contexte d'utilisation).
|
Définit un cookie sur la requête/réponse (en fonction du contexte d'utilisation).
|
||||||
Voir la méthode `get_cookie()` pour voir les attributs potentiels.
|
Voir la méthode `get_cookie()` pour voir les attributs potentiels.
|
||||||
|
1
internal/cache/cache.go
vendored
1
internal/cache/cache.go
vendored
@ -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()
|
||||||
}
|
}
|
||||||
|
4
internal/cache/memory/cache.go
vendored
4
internal/cache/memory/cache.go
vendored
@ -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),
|
||||||
|
5
internal/cache/ttl/cache.go
vendored
5
internal/cache/ttl/cache.go
vendored
@ -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,
|
||||||
|
@ -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",
|
||||||
|
@ -20,6 +20,10 @@ func NewDefaultLayersConfig() LayersConfig {
|
|||||||
TransportConfig: NewDefaultTransportConfig(),
|
TransportConfig: NewDefaultTransportConfig(),
|
||||||
Timeout: NewInterpolatedDuration(10 * time.Second),
|
Timeout: NewInterpolatedDuration(10 * time.Second),
|
||||||
},
|
},
|
||||||
|
ProviderCacheTimeout: NewInterpolatedDuration(time.Hour),
|
||||||
|
},
|
||||||
|
Sessions: AuthnLayerSessionConfig{
|
||||||
|
TTL: NewInterpolatedDuration(time.Hour),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@ -31,13 +35,19 @@ type QueueLayerConfig struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type AuthnLayerConfig struct {
|
type AuthnLayerConfig struct {
|
||||||
Debug InterpolatedBool `yaml:"debug"`
|
Debug InterpolatedBool `yaml:"debug"`
|
||||||
TemplateDir InterpolatedString `yaml:"templateDir"`
|
TemplateDir InterpolatedString `yaml:"templateDir"`
|
||||||
OIDC AuthnOIDCLayerConfig `yaml:"oidc"`
|
OIDC AuthnOIDCLayerConfig `yaml:"oidc"`
|
||||||
|
Sessions AuthnLayerSessionConfig `yaml:"sessions"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AuthnLayerSessionConfig struct {
|
||||||
|
TTL *InterpolatedDuration `yaml:"ttl"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type AuthnOIDCLayerConfig struct {
|
type AuthnOIDCLayerConfig struct {
|
||||||
HTTPClient AuthnOIDCHTTPClientConfig `yaml:"httpClient"`
|
HTTPClient AuthnOIDCHTTPClientConfig `yaml:"httpClient"`
|
||||||
|
ProviderCacheTimeout *InterpolatedDuration `yaml:"providerCacheTimeout"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type AuthnOIDCHTTPClientConfig struct {
|
type AuthnOIDCHTTPClientConfig struct {
|
||||||
|
@ -32,7 +32,7 @@ func NewDefaultSentryConfig() SentryConfig {
|
|||||||
EnableTracing: false,
|
EnableTracing: false,
|
||||||
TracesSampleRate: 0.1,
|
TracesSampleRate: 0.1,
|
||||||
ProfilesSampleRate: 0.1,
|
ProfilesSampleRate: 0.1,
|
||||||
IgnoreErrors: []string{"context canceled"},
|
IgnoreErrors: []string{"context canceled", "net/http: abort"},
|
||||||
SendDefaultPII: false,
|
SendDefaultPII: false,
|
||||||
ServerName: "",
|
ServerName: "",
|
||||||
Environment: "",
|
Environment: "",
|
||||||
|
@ -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
|
||||||
|
}
|
||||||
|
@ -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,40 +230,43 @@ 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) {
|
||||||
ctx := withHandleError(r.Context(), d.handleError)
|
sentry.ConfigureScope(func(scope *sentry.Scope) {
|
||||||
r = r.WithContext(ctx)
|
ctx := withHandleError(r.Context(), d.handleError)
|
||||||
|
ctx = withSentryScope(ctx, scope)
|
||||||
|
r = r.WithContext(ctx)
|
||||||
|
|
||||||
r, err := d.rewriteRequest(r)
|
r, err := d.rewriteRequest(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
HandleError(ctx, w, r, http.StatusInternalServerError, errors.Wrap(err, "could not rewrite request"))
|
HandleError(ctx, w, r, http.StatusInternalServerError, errors.Wrap(err, "could not rewrite request"))
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx = r.Context()
|
|
||||||
|
|
||||||
layers, err := ctxLayers(ctx)
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, errContextKeyNotFound) {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
HandleError(ctx, w, r, http.StatusInternalServerError, errors.Wrap(err, "could not retrieve proxy and layers from context"))
|
ctx = r.Context()
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
httpMiddlewares := make([]proxy.Middleware, 0)
|
layers, err := ctxLayers(ctx)
|
||||||
for _, layer := range layers {
|
if err != nil {
|
||||||
middleware, ok := d.layerRegistry.GetMiddleware(layer.Type)
|
if errors.Is(err, errContextKeyNotFound) {
|
||||||
if !ok {
|
return
|
||||||
continue
|
}
|
||||||
|
|
||||||
|
HandleError(ctx, w, r, http.StatusInternalServerError, errors.Wrap(err, "could not retrieve proxy and layers from context"))
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
httpMiddlewares = append(httpMiddlewares, middleware.Middleware(layer))
|
httpMiddlewares := make([]proxy.Middleware, 0)
|
||||||
}
|
for _, layer := range layers {
|
||||||
|
middleware, ok := d.layerRegistry.GetMiddleware(layer.Type)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
handler := createMiddlewareChain(next, httpMiddlewares)
|
httpMiddlewares = append(httpMiddlewares, middleware.Middleware(layer))
|
||||||
|
}
|
||||||
|
|
||||||
handler.ServeHTTP(w, r)
|
handler := createMiddlewareChain(next, httpMiddlewares)
|
||||||
|
|
||||||
|
handler.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return http.HandlerFunc(fn)
|
return http.HandlerFunc(fn)
|
||||||
|
@ -10,6 +10,9 @@ import (
|
|||||||
"forge.cadoles.com/Cadoles/go-proxy"
|
"forge.cadoles.com/Cadoles/go-proxy"
|
||||||
"forge.cadoles.com/Cadoles/go-proxy/wildcard"
|
"forge.cadoles.com/Cadoles/go-proxy/wildcard"
|
||||||
"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/util"
|
||||||
|
"forge.cadoles.com/cadoles/bouncer/internal/rule"
|
||||||
|
ruleHTTP "forge.cadoles.com/cadoles/bouncer/internal/rule/http"
|
||||||
"forge.cadoles.com/cadoles/bouncer/internal/store"
|
"forge.cadoles.com/cadoles/bouncer/internal/store"
|
||||||
"github.com/Masterminds/sprig/v3"
|
"github.com/Masterminds/sprig/v3"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
@ -21,6 +24,8 @@ type Layer struct {
|
|||||||
auth Authenticator
|
auth Authenticator
|
||||||
debug bool
|
debug bool
|
||||||
|
|
||||||
|
ruleEngineCache *util.RuleEngineCache[*Vars, *LayerOptions]
|
||||||
|
|
||||||
templateDir string
|
templateDir string
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -74,7 +79,7 @@ func (l *Layer) Middleware(layer *store.Layer) proxy.Middleware {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := l.applyRules(ctx, r, options, user); err != nil {
|
if err := l.applyRules(ctx, r, layer, options, user); err != nil {
|
||||||
if errors.Is(err, ErrForbidden) {
|
if errors.Is(err, ErrForbidden) {
|
||||||
l.renderForbiddenPage(w, r, layer, options, user)
|
l.renderForbiddenPage(w, r, layer, options, user)
|
||||||
return
|
return
|
||||||
@ -189,6 +194,18 @@ func NewLayer(layerType store.LayerType, auth Authenticator, funcs ...OptionFunc
|
|||||||
opts := NewOptions(funcs...)
|
opts := NewOptions(funcs...)
|
||||||
|
|
||||||
return &Layer{
|
return &Layer{
|
||||||
|
ruleEngineCache: util.NewInMemoryRuleEngineCache[*Vars, *LayerOptions](func(options *LayerOptions) (*rule.Engine[*Vars], error) {
|
||||||
|
engine, err := rule.NewEngine[*Vars](
|
||||||
|
rule.WithRules(options.Rules...),
|
||||||
|
rule.WithExpr(getAuthnAPI()...),
|
||||||
|
ruleHTTP.WithRequestFuncs(),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithStack(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return engine, nil
|
||||||
|
}),
|
||||||
layerType: layerType,
|
layerType: layerType,
|
||||||
auth: auth,
|
auth: auth,
|
||||||
templateDir: opts.TemplateDir,
|
templateDir: opts.TemplateDir,
|
||||||
|
@ -28,12 +28,13 @@ func DefaultLayerOptions() LayerOptions {
|
|||||||
return LayerOptions{
|
return LayerOptions{
|
||||||
MatchURLs: []string{"*"},
|
MatchURLs: []string{"*"},
|
||||||
Rules: []string{
|
Rules: []string{
|
||||||
"del_headers('Remote-*')",
|
"del_headers(ctx, 'Remote-*')",
|
||||||
"set_header('Remote-User', user.subject)",
|
"set_header(ctx,'Remote-User', vars.user.subject)",
|
||||||
`map(
|
`map(
|
||||||
toPairs(user.attrs), {
|
toPairs(vars.user.attrs), {
|
||||||
let name = replace(lower(string(get(#, 0))), '_', '-');
|
let name = replace(lower(string(get(#, 0))), '_', '-');
|
||||||
set_header(
|
set_header(
|
||||||
|
ctx,
|
||||||
'Remote-User-Attr-' + name,
|
'Remote-User-Attr-' + name,
|
||||||
get(#, 1)
|
get(#, 1)
|
||||||
)
|
)
|
||||||
|
@ -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,15 +380,23 @@ func (a *Authenticator) getClient(options *LayerOptions, redirectURL string) (*C
|
|||||||
Transport: transport,
|
Transport: transport,
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx = oidc.ClientContext(ctx, httpClient)
|
provider, exists := a.oidcProviderCache.Get(options.OIDC.IssuerURL)
|
||||||
|
if !exists {
|
||||||
|
var err error
|
||||||
|
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))
|
||||||
if err != nil {
|
|
||||||
return nil, errors.Wrap(err, "could not create oidc provider")
|
provider, err = oidc.NewProvider(ctx, options.OIDC.IssuerURL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "could not create oidc provider")
|
||||||
|
}
|
||||||
|
|
||||||
|
a.oidcProviderCache.Set(options.OIDC.IssuerURL, provider)
|
||||||
}
|
}
|
||||||
|
|
||||||
client := NewClient(
|
client := NewClient(
|
||||||
|
@ -69,7 +69,7 @@ func (c *Client) login(w http.ResponseWriter, r *http.Request, sess *sessions.Se
|
|||||||
sess.Values[sessionKeyPostLoginRedirectURL] = postLoginRedirectURL
|
sess.Values[sessionKeyPostLoginRedirectURL] = postLoginRedirectURL
|
||||||
|
|
||||||
if err := sess.Save(r, w); err != nil {
|
if err := sess.Save(r, w); err != nil {
|
||||||
director.HandleError(ctx, w, r, http.StatusInternalServerError, errors.New("could not save session"))
|
director.HandleError(ctx, w, r, http.StatusInternalServerError, errors.Wrap(err, "could not save session"))
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -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...)
|
||||||
}
|
}
|
||||||
|
@ -8,9 +8,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Options struct {
|
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 {
|
||||||
|
@ -4,8 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"forge.cadoles.com/cadoles/bouncer/internal/rule"
|
|
||||||
ruleHTTP "forge.cadoles.com/cadoles/bouncer/internal/rule/http"
|
ruleHTTP "forge.cadoles.com/cadoles/bouncer/internal/rule/http"
|
||||||
|
"forge.cadoles.com/cadoles/bouncer/internal/store"
|
||||||
"github.com/expr-lang/expr"
|
"github.com/expr-lang/expr"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
@ -14,17 +14,11 @@ type Vars struct {
|
|||||||
User *User `expr:"user"`
|
User *User `expr:"user"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *Layer) applyRules(ctx context.Context, r *http.Request, options *LayerOptions, user *User) error {
|
func (l *Layer) applyRules(ctx context.Context, r *http.Request, layer *store.Layer, options *LayerOptions, user *User) error {
|
||||||
rules := options.Rules
|
key := string(layer.Proxy) + "-" + string(layer.Name)
|
||||||
if len(rules) == 0 {
|
revisionedEngine := l.ruleEngineCache.Get(key)
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
engine, err := rule.NewEngine[*Vars](
|
engine, err := revisionedEngine.Get(ctx, layer.Revision, options)
|
||||||
rule.WithRules(options.Rules...),
|
|
||||||
rule.WithExpr(getAuthnAPI()...),
|
|
||||||
ruleHTTP.WithRequestFuncs(),
|
|
||||||
)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithStack(err)
|
return errors.WithStack(err)
|
||||||
}
|
}
|
||||||
|
@ -54,7 +54,7 @@ func (q *Queue) Middleware(layer *store.Layer) proxy.Middleware {
|
|||||||
|
|
||||||
options, err := fromStoreOptions(layer.Options, q.defaultKeepAlive)
|
options, err := fromStoreOptions(layer.Options, q.defaultKeepAlive)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
director.HandleError(ctx, w, r, http.StatusInternalServerError, errors.New("could not parse layer options"))
|
director.HandleError(ctx, w, r, http.StatusInternalServerError, errors.Wrap(err, "could not parse layer options"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -89,7 +89,7 @@ func (q *Queue) Middleware(layer *store.Layer) proxy.Middleware {
|
|||||||
|
|
||||||
rank, err := q.adapter.Touch(ctx, queueName, sessionID)
|
rank, err := q.adapter.Touch(ctx, queueName, sessionID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
director.HandleError(ctx, w, r, http.StatusInternalServerError, errors.New("could not retrieve session rank"))
|
director.HandleError(ctx, w, r, http.StatusInternalServerError, errors.Wrap(err, "could not update queue session rank"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -142,7 +142,7 @@ func (q *Queue) renderQueuePage(w http.ResponseWriter, r *http.Request, queueNam
|
|||||||
|
|
||||||
status, err := q.adapter.Status(ctx, queueName)
|
status, err := q.adapter.Status(ctx, queueName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
director.HandleError(ctx, w, r, http.StatusInternalServerError, errors.New("could not retrieve queue status"))
|
director.HandleError(ctx, w, r, http.StatusInternalServerError, errors.Wrap(err, "could not retrieve queue status"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -191,7 +191,7 @@ func (q *Queue) renderQueuePage(w http.ResponseWriter, r *http.Request, queueNam
|
|||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
|
|
||||||
if err := q.tmpl.ExecuteTemplate(&buf, "queue", templateData); err != nil {
|
if err := q.tmpl.ExecuteTemplate(&buf, "queue", templateData); err != nil {
|
||||||
director.HandleError(ctx, w, r, http.StatusInternalServerError, errors.New("could not render queue page"))
|
director.HandleError(ctx, w, r, http.StatusInternalServerError, errors.Wrap(err, "could not render queue page"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -16,8 +16,8 @@ import (
|
|||||||
const LayerType store.LayerType = "rewriter"
|
const LayerType store.LayerType = "rewriter"
|
||||||
|
|
||||||
type Layer struct {
|
type Layer struct {
|
||||||
requestRuleEngine *util.RevisionedRuleEngine[*RequestVars, *LayerOptions]
|
requestRuleEngineCache *util.RuleEngineCache[*RequestVars, *LayerOptions]
|
||||||
responseRuleEngine *util.RevisionedRuleEngine[*ResponseVars, *LayerOptions]
|
responseRuleEngineCache *util.RuleEngineCache[*ResponseVars, *LayerOptions]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *Layer) LayerType() store.LayerType {
|
func (l *Layer) LayerType() store.LayerType {
|
||||||
@ -31,7 +31,7 @@ func (l *Layer) Middleware(layer *store.Layer) proxy.Middleware {
|
|||||||
|
|
||||||
options, err := fromStoreOptions(layer.Options)
|
options, err := fromStoreOptions(layer.Options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
director.HandleError(ctx, w, r, http.StatusInternalServerError, errors.New("could not parse layer options"))
|
director.HandleError(ctx, w, r, http.StatusInternalServerError, errors.Wrap(err, "could not parse layer options"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -42,7 +42,7 @@ func (l *Layer) Middleware(layer *store.Layer) proxy.Middleware {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := l.applyRequestRules(ctx, r, layer.Revision, options); err != nil {
|
if err := l.applyRequestRules(ctx, r, layer, options); err != nil {
|
||||||
var redirect *errRedirect
|
var redirect *errRedirect
|
||||||
if errors.As(err, &redirect) {
|
if errors.As(err, &redirect) {
|
||||||
http.Redirect(w, r, redirect.URL(), redirect.StatusCode())
|
http.Redirect(w, r, redirect.URL(), redirect.StatusCode())
|
||||||
@ -76,7 +76,7 @@ func (l *Layer) ResponseTransformer(layer *store.Layer) proxy.ResponseTransforme
|
|||||||
|
|
||||||
ctx := r.Request.Context()
|
ctx := r.Request.Context()
|
||||||
|
|
||||||
if err := l.applyResponseRules(ctx, r, layer.Revision, options); err != nil {
|
if err := l.applyResponseRules(ctx, r, layer, options); err != nil {
|
||||||
return errors.WithStack(err)
|
return errors.WithStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -86,7 +86,7 @@ func (l *Layer) ResponseTransformer(layer *store.Layer) proxy.ResponseTransforme
|
|||||||
|
|
||||||
func New(funcs ...OptionFunc) *Layer {
|
func New(funcs ...OptionFunc) *Layer {
|
||||||
return &Layer{
|
return &Layer{
|
||||||
requestRuleEngine: util.NewRevisionedRuleEngine(func(options *LayerOptions) (*rule.Engine[*RequestVars], error) {
|
requestRuleEngineCache: util.NewInMemoryRuleEngineCache(func(options *LayerOptions) (*rule.Engine[*RequestVars], error) {
|
||||||
engine, err := rule.NewEngine[*RequestVars](
|
engine, err := rule.NewEngine[*RequestVars](
|
||||||
rule.WithRules(options.Rules.Request...),
|
rule.WithRules(options.Rules.Request...),
|
||||||
ruleHTTP.WithRequestFuncs(),
|
ruleHTTP.WithRequestFuncs(),
|
||||||
@ -98,7 +98,7 @@ func New(funcs ...OptionFunc) *Layer {
|
|||||||
|
|
||||||
return engine, nil
|
return engine, nil
|
||||||
}),
|
}),
|
||||||
responseRuleEngine: util.NewRevisionedRuleEngine(func(options *LayerOptions) (*rule.Engine[*ResponseVars], error) {
|
responseRuleEngineCache: util.NewInMemoryRuleEngineCache(func(options *LayerOptions) (*rule.Engine[*ResponseVars], error) {
|
||||||
engine, err := rule.NewEngine[*ResponseVars](
|
engine, err := rule.NewEngine[*ResponseVars](
|
||||||
rule.WithRules(options.Rules.Response...),
|
rule.WithRules(options.Rules.Response...),
|
||||||
ruleHTTP.WithResponseFuncs(),
|
ruleHTTP.WithResponseFuncs(),
|
||||||
|
@ -8,6 +8,7 @@ import (
|
|||||||
"forge.cadoles.com/cadoles/bouncer/internal/proxy/director"
|
"forge.cadoles.com/cadoles/bouncer/internal/proxy/director"
|
||||||
"forge.cadoles.com/cadoles/bouncer/internal/rule"
|
"forge.cadoles.com/cadoles/bouncer/internal/rule"
|
||||||
ruleHTTP "forge.cadoles.com/cadoles/bouncer/internal/rule/http"
|
ruleHTTP "forge.cadoles.com/cadoles/bouncer/internal/rule/http"
|
||||||
|
"forge.cadoles.com/cadoles/bouncer/internal/store"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -87,13 +88,13 @@ func fromRequest(r *http.Request) RequestVar {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *Layer) applyRequestRules(ctx context.Context, r *http.Request, layerRevision int, options *LayerOptions) error {
|
func (l *Layer) applyRequestRules(ctx context.Context, r *http.Request, layer *store.Layer, options *LayerOptions) error {
|
||||||
rules := options.Rules.Request
|
rules := options.Rules.Request
|
||||||
if len(rules) == 0 {
|
if len(rules) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
engine, err := l.getRequestRuleEngine(ctx, layerRevision, options)
|
engine, err := l.getRequestRuleEngine(ctx, layer, options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithStack(err)
|
return errors.WithStack(err)
|
||||||
}
|
}
|
||||||
@ -117,8 +118,11 @@ func (l *Layer) applyRequestRules(ctx context.Context, r *http.Request, layerRev
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *Layer) getRequestRuleEngine(ctx context.Context, layerRevision int, options *LayerOptions) (*rule.Engine[*RequestVars], error) {
|
func (l *Layer) getRequestRuleEngine(ctx context.Context, layer *store.Layer, options *LayerOptions) (*rule.Engine[*RequestVars], error) {
|
||||||
engine, err := l.requestRuleEngine.Get(ctx, layerRevision, options)
|
key := string(layer.Proxy) + "-" + string(layer.Name)
|
||||||
|
revisionedEngine := l.requestRuleEngineCache.Get(key)
|
||||||
|
|
||||||
|
engine, err := revisionedEngine.Get(ctx, layer.Revision, options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithStack(err)
|
return nil, errors.WithStack(err)
|
||||||
}
|
}
|
||||||
@ -145,13 +149,13 @@ type ResponseVar struct {
|
|||||||
Trailer map[string][]string `expr:"trailer"`
|
Trailer map[string][]string `expr:"trailer"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *Layer) applyResponseRules(ctx context.Context, r *http.Response, layerRevision int, options *LayerOptions) error {
|
func (l *Layer) applyResponseRules(ctx context.Context, r *http.Response, layer *store.Layer, options *LayerOptions) error {
|
||||||
rules := options.Rules.Response
|
rules := options.Rules.Response
|
||||||
if len(rules) == 0 {
|
if len(rules) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
engine, err := l.getResponseRuleEngine(ctx, layerRevision, options)
|
engine, err := l.getResponseRuleEngine(ctx, layer, options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithStack(err)
|
return errors.WithStack(err)
|
||||||
}
|
}
|
||||||
@ -187,8 +191,11 @@ func (l *Layer) applyResponseRules(ctx context.Context, r *http.Response, layerR
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *Layer) getResponseRuleEngine(ctx context.Context, layerRevision int, options *LayerOptions) (*rule.Engine[*ResponseVars], error) {
|
func (l *Layer) getResponseRuleEngine(ctx context.Context, layer *store.Layer, options *LayerOptions) (*rule.Engine[*ResponseVars], error) {
|
||||||
engine, err := l.responseRuleEngine.Get(ctx, layerRevision, options)
|
key := string(layer.Proxy) + "-" + string(layer.Name)
|
||||||
|
revisionedEngine := l.responseRuleEngineCache.Get(key)
|
||||||
|
|
||||||
|
engine, err := revisionedEngine.Get(ctx, layer.Revision, options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithStack(err)
|
return nil, errors.WithStack(err)
|
||||||
}
|
}
|
||||||
|
28
internal/proxy/director/layer/util/rule_engine_cache.go
Normal file
28
internal/proxy/director/layer/util/rule_engine_cache.go
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
package util
|
||||||
|
|
||||||
|
import (
|
||||||
|
"forge.cadoles.com/cadoles/bouncer/internal/cache"
|
||||||
|
"forge.cadoles.com/cadoles/bouncer/internal/cache/memory"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RuleEngineCache[V any, O any] struct {
|
||||||
|
cache cache.Cache[string, *RevisionedRuleEngine[V, O]]
|
||||||
|
factory RuleEngineFactoryFunc[V, O]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *RuleEngineCache[V, O]) Get(key string) *RevisionedRuleEngine[V, O] {
|
||||||
|
revisionedRuleEngine, exists := c.cache.Get(key)
|
||||||
|
if !exists {
|
||||||
|
revisionedRuleEngine = NewRevisionedRuleEngine(c.factory)
|
||||||
|
c.cache.Set(key, revisionedRuleEngine)
|
||||||
|
}
|
||||||
|
|
||||||
|
return revisionedRuleEngine
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewInMemoryRuleEngineCache[V any, O any](factory RuleEngineFactoryFunc[V, O]) *RuleEngineCache[V, O] {
|
||||||
|
return &RuleEngineCache[V, O]{
|
||||||
|
factory: factory,
|
||||||
|
cache: memory.NewCache[string, *RevisionedRuleEngine[V, O]](),
|
||||||
|
}
|
||||||
|
}
|
@ -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))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -10,6 +10,7 @@ import (
|
|||||||
type Options struct {
|
type Options struct {
|
||||||
Session sessions.Options
|
Session sessions.Options
|
||||||
KeyPrefix string
|
KeyPrefix string
|
||||||
|
TTL time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
type OptionFunc func(opts *Options)
|
type OptionFunc func(opts *Options)
|
||||||
@ -25,6 +26,7 @@ func NewOptions(funcs ...OptionFunc) *Options {
|
|||||||
SameSite: http.SameSiteDefaultMode,
|
SameSite: http.SameSiteDefaultMode,
|
||||||
},
|
},
|
||||||
KeyPrefix: "session:",
|
KeyPrefix: "session:",
|
||||||
|
TTL: time.Hour,
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, fn := range funcs {
|
for _, fn := range funcs {
|
||||||
@ -45,3 +47,9 @@ func WithKeyPrefix(prefix string) OptionFunc {
|
|||||||
opts.KeyPrefix = prefix
|
opts.KeyPrefix = prefix
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func WithTTL(ttl time.Duration) OptionFunc {
|
||||||
|
return func(opts *Options) {
|
||||||
|
opts.TTL = ttl
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -31,6 +31,7 @@ type Store struct {
|
|||||||
keyPrefix string
|
keyPrefix string
|
||||||
keyGen KeyGenFunc
|
keyGen KeyGenFunc
|
||||||
serializer SessionSerializer
|
serializer SessionSerializer
|
||||||
|
ttl time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
type KeyGenFunc func() (string, error)
|
type KeyGenFunc func() (string, error)
|
||||||
@ -43,6 +44,7 @@ func NewStore(adapter StoreAdapter, funcs ...OptionFunc) *Store {
|
|||||||
keyPrefix: opts.KeyPrefix,
|
keyPrefix: opts.KeyPrefix,
|
||||||
keyGen: generateRandomKey,
|
keyGen: generateRandomKey,
|
||||||
serializer: GobSerializer{},
|
serializer: GobSerializer{},
|
||||||
|
ttl: opts.TTL,
|
||||||
}
|
}
|
||||||
|
|
||||||
return rs
|
return rs
|
||||||
@ -62,20 +64,21 @@ func (s *Store) New(r *http.Request, name string) (*sessions.Session, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return session, nil
|
return session, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
session.ID = c.Value
|
session.ID = c.Value
|
||||||
|
|
||||||
err = s.load(r.Context(), session)
|
err = s.load(r.Context(), session)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
session.IsNew = false
|
session.IsNew = false
|
||||||
} else if !errors.Is(err, ErrNotFound) {
|
} else if !errors.Is(err, ErrNotFound) {
|
||||||
return nil, errors.WithStack(err)
|
return session, errors.WithStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return session, nil
|
return session, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
|
func (s *Store) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
|
||||||
if session.Options.MaxAge <= 0 {
|
if session.Options.MaxAge < 0 {
|
||||||
if err := s.delete(r.Context(), session); err != nil {
|
if err := s.delete(r.Context(), session); err != nil {
|
||||||
return errors.WithStack(err)
|
return errors.WithStack(err)
|
||||||
}
|
}
|
||||||
@ -120,7 +123,12 @@ func (s *Store) save(ctx context.Context, session *sessions.Session) error {
|
|||||||
return errors.WithStack(err)
|
return errors.WithStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := s.adapter.Set(ctx, s.keyPrefix+session.ID, b, time.Duration(session.Options.MaxAge)*time.Second); err != nil {
|
ttl := time.Duration(session.Options.MaxAge) * time.Second
|
||||||
|
if s.ttl < ttl || ttl == 0 {
|
||||||
|
ttl = s.ttl
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.adapter.Set(ctx, s.keyPrefix+session.ID, b, ttl); err != nil {
|
||||||
return errors.WithStack(err)
|
return errors.WithStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -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
|
||||||
}
|
}
|
||||||
|
@ -55,6 +55,8 @@
|
|||||||
border-radius: 5px;
|
border-radius: 5px;
|
||||||
box-shadow: 2px 2px #cccccc1c;
|
box-shadow: 2px 2px #cccccc1c;
|
||||||
color: #810000 !important;
|
color: #810000 !important;
|
||||||
|
max-width: 80%;
|
||||||
|
overflow-x: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
.title {
|
.title {
|
||||||
@ -81,7 +83,7 @@
|
|||||||
<div id="card">
|
<div id="card">
|
||||||
<h2 class="title">Une erreur est survenue !</h2>
|
<h2 class="title">Une erreur est survenue !</h2>
|
||||||
{{ if .Debug }}
|
{{ if .Debug }}
|
||||||
<pre>{{ .Err }}</pre>
|
<pre style="overflow-x: auto">{{ .Err }}</pre>
|
||||||
{{ end }}
|
{{ end }}
|
||||||
{{/* if a public base url is provided, show navigation link */}}
|
{{/* if a public base url is provided, show navigation link */}}
|
||||||
{{ $oidc := ( index .Layer.Options "oidc" ) }}
|
{{ $oidc := ( index .Layer.Options "oidc" ) }}
|
||||||
|
@ -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)
|
||||||
@ -218,6 +224,11 @@ layers:
|
|||||||
authn:
|
authn:
|
||||||
# Répertoire contenant les templates
|
# Répertoire contenant les templates
|
||||||
templateDir: "/etc/bouncer/layers/authn/templates"
|
templateDir: "/etc/bouncer/layers/authn/templates"
|
||||||
|
# Configuration des sessions
|
||||||
|
sessions:
|
||||||
|
# Temps de persistence sans actualisation des sessions dans le store
|
||||||
|
# (prévalent sur le MaxAge de la session)
|
||||||
|
ttl: "1h"
|
||||||
|
|
||||||
# Configuration d'une série de proxy/layers
|
# Configuration d'une série de proxy/layers
|
||||||
# à créer par défaut par le serveur d'administration
|
# à créer par défaut par le serveur d'administration
|
||||||
|
Reference in New Issue
Block a user