feat(authn-oidc): allow for dynamic post-logout redirection
Cadoles/bouncer/pipeline/head This commit looks good Details

This commit is contained in:
wpetit 2024-05-24 16:40:19 +02:00
parent 26a9ad0e2e
commit a50f2386d5
4 changed files with 118 additions and 66 deletions

View File

@ -7,6 +7,8 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"net/url" "net/url"
"slices"
"strings"
"text/template" "text/template"
"time" "time"
@ -35,9 +37,7 @@ func (a *Authenticator) PreAuthentication(w http.ResponseWriter, r *http.Request
return errors.WithStack(err) return errors.WithStack(err)
} }
baseURL := originalURL.Scheme + "://" + originalURL.Host options, err := fromStoreOptions(layer.Options)
options, err := fromStoreOptions(layer.Options, baseURL)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
@ -47,7 +47,7 @@ func (a *Authenticator) PreAuthentication(w http.ResponseWriter, r *http.Request
logger.Error(ctx, "could not retrieve session", logger.E(errors.WithStack(err))) logger.Error(ctx, "could not retrieve session", logger.E(errors.WithStack(err)))
} }
loginCallbackURL, err := a.getLoginCallbackURL(layer.Proxy, layer.Name, options) loginCallbackURL, err := a.getLoginCallbackURL(originalURL, layer.Proxy, layer.Name, options)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
@ -57,20 +57,20 @@ func (a *Authenticator) PreAuthentication(w http.ResponseWriter, r *http.Request
return errors.WithStack(err) return errors.WithStack(err)
} }
loginCallbackURLPattern, err := a.templatize(options.OIDC.MatchLoginCallbackURL, layer.Proxy, layer.Name) loginCallbackPathPattern, err := a.templatize(options.OIDC.MatchLoginCallbackPath, layer.Proxy, layer.Name)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
logoutURLPattern, err := a.templatize(options.OIDC.MatchLogoutURL, layer.Proxy, layer.Name) logoutPathPattern, err := a.templatize(options.OIDC.MatchLogoutPath, layer.Proxy, layer.Name)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
logger.Debug(ctx, "checking url", logger.F("loginCallbackURLPattern", loginCallbackURLPattern), logger.F("logoutURLPattern", logoutURLPattern)) logger.Debug(ctx, "checking url", logger.F("loginCallbackPathPattern", loginCallbackPathPattern), logger.F("logoutPathPattern", logoutPathPattern))
switch { switch {
case wildcard.Match(originalURL.String(), loginCallbackURLPattern): case wildcard.Match(originalURL.Path, loginCallbackPathPattern):
if err := client.HandleCallback(w, r, sess); err != nil { if err := client.HandleCallback(w, r, sess); err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
@ -80,10 +80,23 @@ func (a *Authenticator) PreAuthentication(w http.ResponseWriter, r *http.Request
metricLabelProxy: string(layer.Proxy), metricLabelProxy: string(layer.Proxy),
}).Add(1) }).Add(1)
case wildcard.Match(originalURL.String(), logoutURLPattern): case wildcard.Match(originalURL.Path, logoutPathPattern):
postLogoutRedirectURL := options.OIDC.PostLogoutRedirectURL postLogoutRedirectURL := r.URL.Query().Get("redirect")
if options.OIDC.PostLogoutRedirectURL == "" {
postLogoutRedirectURL = originalURL.Scheme + "://" + originalURL.Host if postLogoutRedirectURL != "" {
isAuthorized := slices.Contains(options.OIDC.PostLogoutRedirectURLs, postLogoutRedirectURL)
if !isAuthorized {
http.Error(w, "unauthorized post-logout redirect", http.StatusBadRequest)
return errors.WithStack(authn.ErrSkipRequest)
}
}
if postLogoutRedirectURL == "" {
if options.OIDC.PublicBaseURL != "" {
postLogoutRedirectURL = options.OIDC.PublicBaseURL
} else {
postLogoutRedirectURL = originalURL.Scheme + "://" + originalURL.Host
}
} }
if err := client.HandleLogout(w, r, sess, postLogoutRedirectURL); err != nil { if err := client.HandleLogout(w, r, sess, postLogoutRedirectURL); err != nil {
@ -103,14 +116,7 @@ func (a *Authenticator) PreAuthentication(w http.ResponseWriter, r *http.Request
func (a *Authenticator) Authenticate(w http.ResponseWriter, r *http.Request, layer *store.Layer) (*authn.User, error) { func (a *Authenticator) Authenticate(w http.ResponseWriter, r *http.Request, layer *store.Layer) (*authn.User, error) {
ctx := r.Context() ctx := r.Context()
originalURL, err := director.OriginalURL(ctx) options, err := fromStoreOptions(layer.Options)
if err != nil {
return nil, errors.WithStack(err)
}
baseURL := originalURL.Scheme + "://" + originalURL.Host
options, err := fromStoreOptions(layer.Options, baseURL)
if err != nil { if err != nil {
return nil, errors.WithStack(err) return nil, errors.WithStack(err)
} }
@ -142,7 +148,12 @@ func (a *Authenticator) Authenticate(w http.ResponseWriter, r *http.Request, lay
sess.Options.SameSite = http.SameSiteDefaultMode sess.Options.SameSite = http.SameSiteDefaultMode
} }
loginCallbackURL, err := a.getLoginCallbackURL(layer.Proxy, layer.Name, options) originalURL, err := director.OriginalURL(ctx)
if err != nil {
return nil, errors.WithStack(err)
}
loginCallbackURL, err := a.getLoginCallbackURL(originalURL, layer.Proxy, layer.Name, options)
if err != nil { if err != nil {
return nil, errors.WithStack(err) return nil, errors.WithStack(err)
} }
@ -166,7 +177,7 @@ func (a *Authenticator) Authenticate(w http.ResponseWriter, r *http.Request, lay
return nil, errors.WithStack(err) return nil, errors.WithStack(err)
} }
user, err := a.toUser(idToken, layer.Proxy, layer.Name, options, sess) user, err := a.toUser(originalURL, idToken, layer.Proxy, layer.Name, options, sess)
if err != nil { if err != nil {
return nil, errors.WithStack(err) return nil, errors.WithStack(err)
} }
@ -224,7 +235,7 @@ func (c claims) AsAttrs() map[string]any {
return attrs return attrs
} }
func (a *Authenticator) toUser(idToken *oidc.IDToken, proxyName store.ProxyName, layerName store.LayerName, options *LayerOptions, sess *sessions.Session) (*authn.User, error) { func (a *Authenticator) toUser(originalURL *url.URL, idToken *oidc.IDToken, proxyName store.ProxyName, layerName store.LayerName, options *LayerOptions, sess *sessions.Session) (*authn.User, error) {
var claims claims var claims claims
if err := idToken.Claims(&claims); err != nil { if err := idToken.Claims(&claims); err != nil {
@ -237,7 +248,7 @@ func (a *Authenticator) toUser(idToken *oidc.IDToken, proxyName store.ProxyName,
attrs := claims.AsAttrs() attrs := claims.AsAttrs()
logoutURL, err := a.getLogoutURL(proxyName, layerName, options) logoutURL, err := a.getLogoutURL(originalURL, proxyName, layerName, options)
if err != nil { if err != nil {
return nil, errors.WithStack(err) return nil, errors.WithStack(err)
} }
@ -261,36 +272,65 @@ func (a *Authenticator) toUser(idToken *oidc.IDToken, proxyName store.ProxyName,
return user, nil return user, nil
} }
func (a *Authenticator) getLoginCallbackURL(proxyName store.ProxyName, layerName store.LayerName, options *LayerOptions) (*url.URL, error) { func (a *Authenticator) getLoginCallbackURL(originalURL *url.URL, proxyName store.ProxyName, layerName store.LayerName, options *LayerOptions) (*url.URL, error) {
url, err := a.generateURL(options.OIDC.LoginCallbackURL, proxyName, layerName) path, err := a.templatize(options.OIDC.LoginCallbackPath, proxyName, layerName)
if err != nil { if err != nil {
return nil, errors.WithStack(err) return nil, errors.WithStack(err)
} }
return url, nil merged, err := a.mergeURL(originalURL, path, options.OIDC.PublicBaseURL, false)
if err != nil {
return nil, errors.WithStack(err)
}
return merged, nil
} }
func (a *Authenticator) getLogoutURL(proxyName store.ProxyName, layerName store.LayerName, options *LayerOptions) (*url.URL, error) { func (a *Authenticator) getLogoutURL(originalURL *url.URL, proxyName store.ProxyName, layerName store.LayerName, options *LayerOptions) (*url.URL, error) {
url, err := a.generateURL(options.OIDC.LogoutURL, proxyName, layerName) path, err := a.templatize(options.OIDC.LogoutPath, proxyName, layerName)
if err != nil { if err != nil {
return nil, errors.WithStack(err) return nil, errors.WithStack(err)
} }
return url, nil merged, err := a.mergeURL(originalURL, path, options.OIDC.PublicBaseURL, true)
if err != nil {
return nil, errors.WithStack(err)
}
return merged, nil
} }
func (a *Authenticator) generateURL(rawURLTemplate string, proxyName store.ProxyName, layerName store.LayerName) (*url.URL, error) { func (a *Authenticator) mergeURL(base *url.URL, path string, overlay string, withQuery bool) (*url.URL, error) {
rawURL, err := a.templatize(rawURLTemplate, proxyName, layerName) merged := &url.URL{
if err != nil { Scheme: base.Scheme,
return nil, errors.WithStack(err) Host: base.Host,
Path: path,
} }
url, err := url.Parse(rawURL) if withQuery {
if err != nil { merged.RawQuery = base.RawQuery
return nil, errors.WithStack(err)
} }
return url, nil if overlay != "" {
overlayURL, err := url.Parse(overlay)
if err != nil {
return nil, errors.WithStack(err)
}
merged.Scheme = overlayURL.Scheme
merged.Host = overlayURL.Host
merged.Path = overlayURL.Path + strings.TrimPrefix(path, "/")
for key, values := range overlayURL.Query() {
query := merged.Query()
for _, v := range values {
query.Add(key, v)
}
merged.RawQuery = query.Encode()
}
}
return merged, nil
} }
func (a *Authenticator) templatize(rawTemplate string, proxyName store.ProxyName, layerName store.LayerName) (string, error) { func (a *Authenticator) templatize(rawTemplate string, proxyName store.ProxyName, layerName store.LayerName) (string, error) {

View File

@ -49,7 +49,7 @@ func (c *Client) Provider() *oidc.Provider {
func (c *Client) Authenticate(w http.ResponseWriter, r *http.Request, sess *sessions.Session) (*oidc.IDToken, error) { func (c *Client) Authenticate(w http.ResponseWriter, r *http.Request, sess *sessions.Session) (*oidc.IDToken, error) {
idToken, err := c.getIDToken(r, sess) idToken, err := c.getIDToken(r, sess)
if err != nil { if err != nil {
logger.Error(r.Context(), "could not retrieve idtoken", logger.E(errors.WithStack(err))) logger.Warn(r.Context(), "could not retrieve idtoken", logger.E(errors.WithStack(err)))
c.login(w, r, sess) c.login(w, r, sess)
@ -249,7 +249,7 @@ func (c *Client) validate(r *http.Request, sess *sessions.Session) (*oauth2.Toke
func (c *Client) getRawIDToken(sess *sessions.Session) (string, error) { func (c *Client) getRawIDToken(sess *sessions.Session) (string, error) {
rawIDToken, ok := sess.Values[sessionKeyIDToken].(string) rawIDToken, ok := sess.Values[sessionKeyIDToken].(string)
if !ok || rawIDToken == "" { if !ok || rawIDToken == "" {
return "", errors.New("invalid id token") return "", errors.New("id token not found")
} }
return rawIDToken, nil return rawIDToken, nil

View File

@ -17,9 +17,13 @@
"title": "URL de base du fournisseur OpenID Connect (racine du .well-known/openid-configuration)", "title": "URL de base du fournisseur OpenID Connect (racine du .well-known/openid-configuration)",
"type": "string" "type": "string"
}, },
"postLogoutRedirectURL": { "postLogoutRedirectURLs": {
"title": "URL de redirection après déconnexion", "title": "URLs de redirection après déconnexion autorisées",
"type": "string" "description": "La variable d'URL 'redirect=<url>' peut être utilisée pour spécifier une redirection après déconnexion.",
"type": "array",
"item": {
"type": "string"
}
}, },
"scopes": { "scopes": {
"title": "Scopes associés au client OpenID Connect", "title": "Scopes associés au client OpenID Connect",
@ -42,27 +46,33 @@
} }
} }
}, },
"loginCallbackURL": { "loginCallbackPath": {
"title": "Chemin associé à l'URL de callback OpenID Connect", "title": "Chemin associé à l'URL de callback OpenID Connect",
"default": "<scheme>://<host>/.bouncer/authn/oidc/{{ .ProxyName }}/{{ .LayerName }}/callback", "default": "/.bouncer/authn/oidc/{{ .ProxyName }}/{{ .LayerName }}/callback",
"description": "Les marqueurs '{{ .ProxyName }}' et '{{ .LayerName }}' peuvent être utilisés pour injecter le nom du proxy ainsi que celui du layer.", "description": "Les marqueurs '{{ .ProxyName }}' et '{{ .LayerName }}' peuvent être utilisés pour injecter le nom du proxy ainsi que celui du layer.",
"type": "string" "type": "string"
}, },
"matchLoginCallbackURL": { "matchLoginCallbackPath": {
"title": "Patron de correspondance de l'URL interne de callback OpenID Connect", "title": "Patron de correspondance du chemin interne de callback OpenID Connect",
"default": "*/.bouncer/authn/oidc/{{ .ProxyName }}/{{ .LayerName }}/callback", "default": "*.bouncer/authn/oidc/{{ .ProxyName }}/{{ .LayerName }}/callback",
"description": "Les marqueurs '{{ .ProxyName }}' et '{{ .LayerName }}' peuvent être utilisés pour injecter le nom du proxy ainsi que celui du layer.", "description": "Les marqueurs '{{ .ProxyName }}' et '{{ .LayerName }}' peuvent être utilisés pour injecter le nom du proxy ainsi que celui du layer.",
"type": "string" "type": "string"
}, },
"logoutURL": { "logoutPath": {
"title": "Chemin associé à l'URL de déconnexion", "title": "Chemin associé à l'URL de déconnexion",
"default": "<scheme>://<host>/.bouncer/authn/oidc/{{ .ProxyName }}/{{ .LayerName }}/logout", "default": "/.bouncer/authn/oidc/{{ .ProxyName }}/{{ .LayerName }}/logout",
"description": "Les marqueurs '{{ .ProxyName }}' et '{{ .LayerName }}' peuvent être utilisés pour injecter le nom du proxy ainsi que celui du layer.", "description": "Les marqueurs '{{ .ProxyName }}' et '{{ .LayerName }}' peuvent être utilisés pour injecter le nom du proxy ainsi que celui du layer.",
"type": "string" "type": "string"
}, },
"matchLogoutURL": { "publicBaseURL": {
"title": "Patron de correspondance l'URL interne de déconnexion", "title": "URL publique de base associée au service distant",
"default": "*/.bouncer/authn/oidc/{{ .ProxyName }}/{{ .LayerName }}/logout", "default": "",
"description": "Peut être utilisé par exemple si il y a discordance de nom d'hôte ou de chemin sur les URLs publiques/internes.",
"type": "string"
},
"matchLogoutPath": {
"title": "Patron de correspondance du chemin interne de déconnexion",
"default": "*.bouncer/authn/oidc/{{ .ProxyName }}/{{ .LayerName }}/logout",
"description": "Les marqueurs '{{ .ProxyName }}' et '{{ .LayerName }}' peuvent être utilisés pour injecter le nom du proxy ainsi que celui du layer.", "description": "Les marqueurs '{{ .ProxyName }}' et '{{ .LayerName }}' peuvent être utilisés pour injecter le nom du proxy ainsi que celui du layer.",
"type": "string" "type": "string"
}, },

View File

@ -19,13 +19,14 @@ type LayerOptions struct {
type OIDCOptions struct { type OIDCOptions struct {
ClientID string `mapstructure:"clientId"` ClientID string `mapstructure:"clientId"`
ClientSecret string `mapstructure:"clientSecret"` ClientSecret string `mapstructure:"clientSecret"`
LoginCallbackURL string `mapstructure:"loginCallbackURL"` PublicBaseURL string `mapstructure:"publicBaseURL"`
MatchLoginCallbackURL string `mapstructure:"matchLoginCallbackURL"` LoginCallbackPath string `mapstructure:"loginCallbackPath"`
LogoutURL string `mapstructure:"logoutURL"` MatchLoginCallbackPath string `mapstructure:"matchLoginCallbackPath"`
MatchLogoutURL string `mapstructure:"matchLogoutURL"` LogoutPath string `mapstructure:"logoutPath"`
MatchLogoutPath string `mapstructure:"matchLogoutPath"`
IssuerURL string `mapstructure:"issuerURL"` IssuerURL string `mapstructure:"issuerURL"`
SkipIssuerVerification bool `mapstructure:"skipIssuerVerification"` SkipIssuerVerification bool `mapstructure:"skipIssuerVerification"`
PostLogoutRedirectURL string `mapstructure:"postLogoutRedirectURL"` PostLogoutRedirectURLs []string `mapstructure:"postLogoutRedirectURLs"`
TLSInsecureSkipVerify bool `mapstructure:"tlsInsecureSkipVerify"` TLSInsecureSkipVerify bool `mapstructure:"tlsInsecureSkipVerify"`
Scopes []string `mapstructure:"scopes"` Scopes []string `mapstructure:"scopes"`
AuthParams map[string]string `mapstructure:"authParams"` AuthParams map[string]string `mapstructure:"authParams"`
@ -41,18 +42,19 @@ type CookieOptions struct {
MaxAge time.Duration `mapstructure:"maxAge"` MaxAge time.Duration `mapstructure:"maxAge"`
} }
func fromStoreOptions(storeOptions store.LayerOptions, baseURL string) (*LayerOptions, error) { func fromStoreOptions(storeOptions store.LayerOptions) (*LayerOptions, error) {
loginCallbackPath := "/.bouncer/authn/oidc/{{ .ProxyName }}/{{ .LayerName }}/callback" loginCallbackPath := ".bouncer/authn/oidc/{{ .ProxyName }}/{{ .LayerName }}/callback"
logoutPath := "/.bouncer/authn/oidc/{{ .ProxyName }}/{{ .LayerName }}/logout" logoutPath := ".bouncer/authn/oidc/{{ .ProxyName }}/{{ .LayerName }}/logout"
layerOptions := LayerOptions{ layerOptions := LayerOptions{
LayerOptions: authn.DefaultLayerOptions(), LayerOptions: authn.DefaultLayerOptions(),
OIDC: OIDCOptions{ OIDC: OIDCOptions{
LoginCallbackURL: baseURL + loginCallbackPath, PublicBaseURL: "",
MatchLoginCallbackURL: "*" + loginCallbackPath + "*", LoginCallbackPath: loginCallbackPath,
LogoutURL: baseURL + logoutPath, MatchLoginCallbackPath: "*" + loginCallbackPath,
MatchLogoutURL: "*" + logoutPath + "*", LogoutPath: logoutPath,
Scopes: []string{"openid"}, MatchLogoutPath: "*" + logoutPath,
Scopes: []string{"openid"},
}, },
Cookie: CookieOptions{ Cookie: CookieOptions{
Name: defaultCookieName, Name: defaultCookieName,