feat: federated logout for SAML IdPs (#9931)

# Which Problems Are Solved

Currently if a user signs in using an IdP, once they sign out of
Zitadel, the corresponding IdP session is not terminated. This can be
the desired behavior. In some cases, e.g. when using a shared computer
it results in a potential security risk, since a follower user might be
able to sign in as the previous using the still open IdP session.

# How the Problems Are Solved

- Admins can enabled a federated logout option on SAML IdPs through the
Admin and Management APIs.
- During the termination of a login V1 session using OIDC end_session
endpoint, Zitadel will check if an IdP was used to authenticate that
session.
- In case there was a SAML IdP used with Federated Logout enabled, it
will intercept the logout process, store the information into the shared
cache and redirect to the federated logout endpoint in the V1 login.
- The V1 login federated logout endpoint checks every request on an
existing cache entry. On success it will create a SAML logout request
for the used IdP and either redirect or POST to the configured SLO
endpoint. The cache entry is updated with a `redirected` state.
- A SLO endpoint is added to the `/idp` handlers, which will handle the
SAML logout responses. At the moment it will check again for an existing
federated logout entry (with state `redirected`) in the cache. On
success, the user is redirected to the initially provided
`post_logout_redirect_uri` from the end_session request.

# Additional Changes

None

# Additional Context

- This PR merges the https://github.com/zitadel/zitadel/pull/9841 and
https://github.com/zitadel/zitadel/pull/9854 to main, additionally
updating the docs on Entra ID SAML.
- closes #9228 
- backport to 3.x

---------

Co-authored-by: Silvan <27845747+adlerhurst@users.noreply.github.com>
Co-authored-by: Zach Hirschtritt <zachary.hirschtritt@klaviyo.com>
This commit is contained in:
Livio Spring
2025-05-23 13:52:25 +02:00
committed by GitHub
parent 7eb45c6cfd
commit 2cf3ef4de4
69 changed files with 633 additions and 51 deletions

View File

@@ -3,11 +3,13 @@ package login
import (
"context"
"errors"
"html/template"
"net/http"
"net/url"
"slices"
"strings"
crewjam_saml "github.com/crewjam/saml"
"github.com/crewjam/saml/samlsp"
"github.com/zitadel/logging"
"github.com/zitadel/oidc/v3/pkg/client/rp"
@@ -20,6 +22,7 @@ import (
http_mw "github.com/zitadel/zitadel/internal/api/http/middleware"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/domain/federatedlogout"
"github.com/zitadel/zitadel/internal/eventstore/v1/models"
"github.com/zitadel/zitadel/internal/idp"
"github.com/zitadel/zitadel/internal/idp/providers/apple"
@@ -1422,6 +1425,124 @@ func (l *Login) getUserLinks(ctx context.Context, userID, idpID string) (*query.
)
}
type federatedLogoutData struct {
SessionID string `schema:"sessionID"`
}
const (
federatedLogoutDataSessionID = "sessionID"
)
func ExternalLogoutPath(sessionID string) string {
v := url.Values{}
v.Set(federatedLogoutDataSessionID, sessionID)
return HandlerPrefix + EndpointExternalLogout + "?" + v.Encode()
}
// handleExternalLogout is called when a user signed out of ZITADEL with a federated logout
func (l *Login) handleExternalLogout(w http.ResponseWriter, r *http.Request) {
data := new(federatedLogoutData)
err := l.parser.Parse(r, data)
if err != nil {
l.renderError(w, r, nil, err)
return
}
logoutRequest, ok := l.caches.federatedLogouts.Get(r.Context(), federatedlogout.IndexRequestID, federatedlogout.Key(authz.GetInstance(r.Context()).InstanceID(), data.SessionID))
if !ok || logoutRequest.State != federatedlogout.StateCreated || logoutRequest.FingerPrintID != authz.GetCtxData(r.Context()).AgentID {
l.renderError(w, r, nil, zerrors.ThrowNotFound(nil, "LOGIN-ADK21", "Errors.ExternalIDP.LogoutRequestNotFound"))
return
}
provider, err := l.externalLogoutProvider(r, logoutRequest.IDPID)
if err != nil {
l.renderError(w, r, nil, err)
return
}
nameID, err := l.externalUserID(r.Context(), logoutRequest.UserID, logoutRequest.IDPID)
if err != nil {
l.renderError(w, r, nil, err)
return
}
err = samlLogoutRequest(w, r, provider, nameID, logoutRequest.SessionID)
if err != nil {
l.renderError(w, r, nil, err)
return
}
logoutRequest.State = federatedlogout.StateRedirected
l.caches.federatedLogouts.Set(r.Context(), logoutRequest)
}
func (l *Login) externalLogoutProvider(r *http.Request, providerID string) (*saml.Provider, error) {
identityProvider, err := l.getIDPByID(r, providerID)
if err != nil {
return nil, err
}
if identityProvider.Type != domain.IDPTypeSAML {
return nil, zerrors.ThrowInvalidArgument(nil, "LOGIN-ADK21", "Errors.ExternalIDP.IDPTypeNotImplemented")
}
return l.samlProvider(r.Context(), identityProvider)
}
func samlLogoutRequest(w http.ResponseWriter, r *http.Request, provider *saml.Provider, nameID, sessionID string) error {
mw, err := provider.GetSP()
if err != nil {
return err
}
// We ignore the configured binding and only check the available SLO endpoints from the metadata.
// For example, Azure documents that only redirect binding is possible and also only provides a redirect SLO in the metadata.
slo := mw.ServiceProvider.GetSLOBindingLocation(crewjam_saml.HTTPRedirectBinding)
if slo != "" {
return samlRedirectLogoutRequest(w, r, mw.ServiceProvider, slo, nameID, sessionID)
}
slo = mw.ServiceProvider.GetSLOBindingLocation(crewjam_saml.HTTPPostBinding)
return samlPostLogoutRequest(w, mw.ServiceProvider, slo, nameID, sessionID)
}
func samlRedirectLogoutRequest(w http.ResponseWriter, r *http.Request, sp crewjam_saml.ServiceProvider, slo, nameID, sessionID string) error {
lr, err := sp.MakeLogoutRequest(slo, nameID)
if err != nil {
return err
}
http.Redirect(w, r, lr.Redirect(sessionID).String(), http.StatusFound)
return nil
}
var (
samlSLOPostTemplate = template.Must(template.New("samlSLOPost").Parse(`<!DOCTYPE html><html><body>{{.Form}}</body></html>`))
)
type samlSLOPostData struct {
Form template.HTML
}
func samlPostLogoutRequest(w http.ResponseWriter, sp crewjam_saml.ServiceProvider, slo, nameID, sessionID string) error {
lr, err := sp.MakeLogoutRequest(slo, nameID)
if err != nil {
return err
}
return samlSLOPostTemplate.Execute(w, &samlSLOPostData{Form: template.HTML(lr.Post(sessionID))})
}
func (l *Login) externalUserID(ctx context.Context, userID, idpID string) (string, error) {
userIDQuery, err := query.NewIDPUserLinksUserIDSearchQuery(userID)
if err != nil {
return "", err
}
idpIDQuery, err := query.NewIDPUserLinkIDPIDSearchQuery(idpID)
if err != nil {
return "", err
}
links, err := l.query.IDPUserLinks(ctx, &query.IDPUserLinksSearchQuery{Queries: []query.SearchQuery{userIDQuery, idpIDQuery}}, nil)
if err != nil || len(links.Links) != 1 {
return "", zerrors.ThrowPreconditionFailed(err, "LOGIN-ADK21", "Errors.User.ExternalIDP.NotFound")
}
return links.Links[0].ProvidedUserID, nil
}
// IdPError wraps an error from an external IDP to be able to distinguish it from other errors and to display it
// more prominent (popup style) .
// It's used if an error occurs during the login process with an external IDP and local authentication is allowed,

View File

@@ -21,6 +21,7 @@ import (
"github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/domain/federatedlogout"
"github.com/zitadel/zitadel/internal/form"
"github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/static"
@@ -60,25 +61,20 @@ const (
DefaultLoggedOutPath = HandlerPrefix + EndpointLogoutDone
)
func CreateLogin(config Config,
func CreateLogin(
config Config,
command *command.Commands,
query *query.Queries,
authRepo *eventsourcing.EsRepository,
staticStorage static.Storage,
consolePath string,
oidcAuthCallbackURL func(context.Context, string) string,
samlAuthCallbackURL func(context.Context, string) string,
oidcAuthCallbackURL, samlAuthCallbackURL func(context.Context, string) string,
externalSecure bool,
userAgentCookie,
issuerInterceptor,
oidcInstanceHandler,
samlInstanceHandler,
assetCache,
accessHandler mux.MiddlewareFunc,
userCodeAlg crypto.EncryptionAlgorithm,
idpConfigAlg crypto.EncryptionAlgorithm,
userAgentCookie, issuerInterceptor, oidcInstanceHandler, samlInstanceHandler, assetCache, accessHandler mux.MiddlewareFunc,
userCodeAlg, idpConfigAlg crypto.EncryptionAlgorithm,
csrfCookieKey []byte,
cacheConnectors connector.Connectors,
federateLogoutCache cache.Cache[federatedlogout.Index, string, *federatedlogout.FederatedLogout],
) (*Login, error) {
login := &Login{
oidcAuthCallbackURL: oidcAuthCallbackURL,
@@ -101,7 +97,7 @@ func CreateLogin(config Config,
login.parser = form.NewParser()
var err error
login.caches, err = startCaches(context.Background(), cacheConnectors)
login.caches, err = startCaches(context.Background(), cacheConnectors, federateLogoutCache)
if err != nil {
return nil, err
}
@@ -112,7 +108,11 @@ func csp() *middleware.CSP {
csp := middleware.DefaultSCP
csp.ObjectSrc = middleware.CSPSourceOptsSelf()
csp.StyleSrc = csp.StyleSrc.AddNonce()
csp.ScriptSrc = csp.ScriptSrc.AddNonce().AddHash("sha256", "AjPdJSbZmeWHnEc5ykvJFay8FTWeTeRbs9dutfZ0HqE=")
csp.ScriptSrc = csp.ScriptSrc.AddNonce().
// SAML POST ACS
AddHash("sha256", "AjPdJSbZmeWHnEc5ykvJFay8FTWeTeRbs9dutfZ0HqE=").
// SAML POST SLO
AddHash("sha256", "4Su6mBWzEIFnH4pAGMOuaeBrstwJN4Z3pq/s1Kn4/KQ=")
return &csp
}
@@ -215,14 +215,16 @@ func (l *Login) baseURL(ctx context.Context) string {
type Caches struct {
idpFormCallbacks cache.Cache[idpFormCallbackIndex, string, *idpFormCallback]
federatedLogouts cache.Cache[federatedlogout.Index, string, *federatedlogout.FederatedLogout]
}
func startCaches(background context.Context, connectors connector.Connectors) (_ *Caches, err error) {
func startCaches(background context.Context, connectors connector.Connectors, federateLogoutCache cache.Cache[federatedlogout.Index, string, *federatedlogout.FederatedLogout]) (_ *Caches, err error) {
caches := new(Caches)
caches.idpFormCallbacks, err = connector.StartCache[idpFormCallbackIndex, string, *idpFormCallback](background, []idpFormCallbackIndex{idpFormCallbackIndexRequestID}, cache.PurposeIdPFormCallback, connectors.Config.IdPFormCallbacks, connectors)
if err != nil {
return nil, err
}
caches.federatedLogouts = federateLogoutCache
return caches, nil
}

View File

@@ -14,6 +14,7 @@ const (
EndpointExternalLogin = "/login/externalidp"
EndpointExternalLoginCallback = "/login/externalidp/callback"
EndpointExternalLoginCallbackFormPost = "/login/externalidp/callback/form"
EndpointExternalLogout = "/logout/externalidp"
EndpointSAMLACS = "/login/externalidp/saml/acs"
EndpointJWTAuthorize = "/login/jwt/authorize"
EndpointJWTCallback = "/login/jwt/callback"
@@ -77,6 +78,7 @@ func CreateRouter(login *Login, interceptors ...mux.MiddlewareFunc) *mux.Router
router.HandleFunc(EndpointExternalLogin, login.handleExternalLogin).Methods(http.MethodGet)
router.HandleFunc(EndpointExternalLoginCallback, login.handleExternalLoginCallback).Methods(http.MethodGet)
router.HandleFunc(EndpointExternalLoginCallbackFormPost, login.handleExternalLoginCallbackForm).Methods(http.MethodPost)
router.HandleFunc(EndpointExternalLogout, login.handleExternalLogout).Methods(http.MethodGet)
router.HandleFunc(EndpointSAMLACS, login.handleExternalLoginCallback).Methods(http.MethodGet)
router.HandleFunc(EndpointSAMLACS, login.handleExternalLoginCallbackForm).Methods(http.MethodPost)
router.HandleFunc(EndpointJWTAuthorize, login.handleJWTRequest).Methods(http.MethodGet)