2023-05-24 20:29:58 +02:00
|
|
|
package idp
|
|
|
|
|
|
|
|
import (
|
2023-09-29 11:26:14 +02:00
|
|
|
"bytes"
|
2023-05-24 20:29:58 +02:00
|
|
|
"context"
|
2025-05-27 16:26:46 +02:00
|
|
|
"encoding/base64"
|
2023-09-29 11:26:14 +02:00
|
|
|
"encoding/xml"
|
2023-05-24 20:29:58 +02:00
|
|
|
"errors"
|
2023-09-29 11:26:14 +02:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2023-05-24 20:29:58 +02:00
|
|
|
"net/http"
|
2024-11-15 07:19:43 +01:00
|
|
|
"strconv"
|
2023-05-24 20:29:58 +02:00
|
|
|
|
2024-07-24 14:29:05 +02:00
|
|
|
"github.com/crewjam/saml"
|
2023-05-24 20:29:58 +02:00
|
|
|
"github.com/gorilla/mux"
|
2024-11-15 07:19:43 +01:00
|
|
|
"github.com/muhlemmer/gu"
|
2023-05-24 20:29:58 +02:00
|
|
|
"github.com/zitadel/logging"
|
|
|
|
|
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>
2025-05-23 13:52:25 +02:00
|
|
|
"github.com/zitadel/zitadel/internal/api/authz"
|
2023-05-24 20:29:58 +02:00
|
|
|
http_utils "github.com/zitadel/zitadel/internal/api/http"
|
2024-07-24 14:29:05 +02:00
|
|
|
"github.com/zitadel/zitadel/internal/api/ui/login"
|
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>
2025-05-23 13:52:25 +02:00
|
|
|
"github.com/zitadel/zitadel/internal/cache"
|
2023-05-24 20:29:58 +02:00
|
|
|
"github.com/zitadel/zitadel/internal/command"
|
|
|
|
"github.com/zitadel/zitadel/internal/crypto"
|
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>
2025-05-23 13:52:25 +02:00
|
|
|
"github.com/zitadel/zitadel/internal/domain/federatedlogout"
|
2023-05-24 20:29:58 +02:00
|
|
|
"github.com/zitadel/zitadel/internal/form"
|
|
|
|
"github.com/zitadel/zitadel/internal/idp"
|
2023-08-31 08:39:16 +02:00
|
|
|
"github.com/zitadel/zitadel/internal/idp/providers/apple"
|
2023-05-24 20:29:58 +02:00
|
|
|
"github.com/zitadel/zitadel/internal/idp/providers/azuread"
|
|
|
|
"github.com/zitadel/zitadel/internal/idp/providers/github"
|
|
|
|
"github.com/zitadel/zitadel/internal/idp/providers/gitlab"
|
|
|
|
"github.com/zitadel/zitadel/internal/idp/providers/google"
|
|
|
|
"github.com/zitadel/zitadel/internal/idp/providers/jwt"
|
|
|
|
"github.com/zitadel/zitadel/internal/idp/providers/ldap"
|
|
|
|
"github.com/zitadel/zitadel/internal/idp/providers/oauth"
|
|
|
|
openid "github.com/zitadel/zitadel/internal/idp/providers/oidc"
|
2023-09-29 11:26:14 +02:00
|
|
|
saml2 "github.com/zitadel/zitadel/internal/idp/providers/saml"
|
2023-05-24 20:29:58 +02:00
|
|
|
"github.com/zitadel/zitadel/internal/query"
|
2023-12-08 16:30:55 +02:00
|
|
|
"github.com/zitadel/zitadel/internal/zerrors"
|
2023-05-24 20:29:58 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2023-09-29 11:26:14 +02:00
|
|
|
HandlerPrefix = "/idps"
|
|
|
|
|
|
|
|
idpPrefix = "/{" + varIDPID + ":[0-9]+}"
|
|
|
|
|
|
|
|
callbackPath = "/callback"
|
|
|
|
metadataPath = idpPrefix + "/saml/metadata"
|
|
|
|
acsPath = idpPrefix + "/saml/acs"
|
|
|
|
certificatePath = idpPrefix + "/saml/certificate"
|
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>
2025-05-23 13:52:25 +02:00
|
|
|
sloPath = idpPrefix + "/saml/slo"
|
2025-05-27 16:26:46 +02:00
|
|
|
jwtPath = "/jwt"
|
2023-05-24 20:29:58 +02:00
|
|
|
|
|
|
|
paramIntentID = "id"
|
|
|
|
paramToken = "token"
|
|
|
|
paramUserID = "user"
|
|
|
|
paramError = "error"
|
|
|
|
paramErrorDescription = "error_description"
|
2023-09-29 11:26:14 +02:00
|
|
|
varIDPID = "idpid"
|
2024-11-15 07:19:43 +01:00
|
|
|
paramInternalUI = "internalUI"
|
2023-05-24 20:29:58 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type Handler struct {
|
2024-07-24 14:29:05 +02:00
|
|
|
commands *command.Commands
|
|
|
|
queries *query.Queries
|
|
|
|
parser *form.Parser
|
|
|
|
encryptionAlgorithm crypto.EncryptionAlgorithm
|
|
|
|
callbackURL func(ctx context.Context) string
|
|
|
|
samlRootURL func(ctx context.Context, idpID string) string
|
|
|
|
loginSAMLRootURL func(ctx context.Context) string
|
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>
2025-05-23 13:52:25 +02:00
|
|
|
caches *Caches
|
2023-05-24 20:29:58 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type externalIDPCallbackData struct {
|
|
|
|
State string `schema:"state"`
|
|
|
|
Code string `schema:"code"`
|
|
|
|
Error string `schema:"error"`
|
|
|
|
ErrorDescription string `schema:"error_description"`
|
2023-08-31 08:39:16 +02:00
|
|
|
|
|
|
|
// Apple returns a user on first registration
|
|
|
|
User string `schema:"user"`
|
2023-05-24 20:29:58 +02:00
|
|
|
}
|
|
|
|
|
2023-09-29 11:26:14 +02:00
|
|
|
type externalSAMLIDPCallbackData struct {
|
|
|
|
IDPID string
|
|
|
|
Response string
|
|
|
|
RelayState string
|
|
|
|
}
|
|
|
|
|
2023-05-24 20:29:58 +02:00
|
|
|
// CallbackURL generates the instance specific URL to the IDP callback handler
|
feat: trusted (instance) domains (#8369)
# Which Problems Are Solved
ZITADEL currently selects the instance context based on a HTTP header
(see https://github.com/zitadel/zitadel/issues/8279#issue-2399959845 and
checks it against the list of instance domains. Let's call it instance
or API domain.
For any context based URL (e.g. OAuth, OIDC, SAML endpoints, links in
emails, ...) the requested domain (instance domain) will be used. Let's
call it the public domain.
In cases of proxied setups, all exposed domains (public domains) require
the domain to be managed as instance domain.
This can either be done using the "ExternalDomain" in the runtime config
or via system API, which requires a validation through CustomerPortal on
zitadel.cloud.
# How the Problems Are Solved
- Two new headers / header list are added:
- `InstanceHostHeaders`: an ordered list (first sent wins), which will
be used to match the instance.
(For backward compatibility: the `HTTP1HostHeader`, `HTTP2HostHeader`
and `forwarded`, `x-forwarded-for`, `x-forwarded-host` are checked
afterwards as well)
- `PublicHostHeaders`: an ordered list (first sent wins), which will be
used as public host / domain. This will be checked against a list of
trusted domains on the instance.
- The middleware intercepts all requests to the API and passes a
`DomainCtx` object with the hosts and protocol into the context
(previously only a computed `origin` was passed)
- HTTP / GRPC server do not longer try to match the headers to instances
themself, but use the passed `http.DomainContext` in their interceptors.
- The `RequestedHost` and `RequestedDomain` from authz.Instance are
removed in favor of the `http.DomainContext`
- When authenticating to or signing out from Console UI, the current
`http.DomainContext(ctx).Origin` (already checked by instance
interceptor for validity) is used to compute and dynamically add a
`redirect_uri` and `post_logout_redirect_uri`.
- Gateway passes all configured host headers (previously only did
`x-zitadel-*`)
- Admin API allows to manage trusted domain
# Additional Changes
None
# Additional Context
- part of #8279
- open topics:
- "single-instance" mode
- Console UI
2024-07-31 17:00:38 +02:00
|
|
|
func CallbackURL() func(ctx context.Context) string {
|
2023-05-24 20:29:58 +02:00
|
|
|
return func(ctx context.Context) string {
|
feat: trusted (instance) domains (#8369)
# Which Problems Are Solved
ZITADEL currently selects the instance context based on a HTTP header
(see https://github.com/zitadel/zitadel/issues/8279#issue-2399959845 and
checks it against the list of instance domains. Let's call it instance
or API domain.
For any context based URL (e.g. OAuth, OIDC, SAML endpoints, links in
emails, ...) the requested domain (instance domain) will be used. Let's
call it the public domain.
In cases of proxied setups, all exposed domains (public domains) require
the domain to be managed as instance domain.
This can either be done using the "ExternalDomain" in the runtime config
or via system API, which requires a validation through CustomerPortal on
zitadel.cloud.
# How the Problems Are Solved
- Two new headers / header list are added:
- `InstanceHostHeaders`: an ordered list (first sent wins), which will
be used to match the instance.
(For backward compatibility: the `HTTP1HostHeader`, `HTTP2HostHeader`
and `forwarded`, `x-forwarded-for`, `x-forwarded-host` are checked
afterwards as well)
- `PublicHostHeaders`: an ordered list (first sent wins), which will be
used as public host / domain. This will be checked against a list of
trusted domains on the instance.
- The middleware intercepts all requests to the API and passes a
`DomainCtx` object with the hosts and protocol into the context
(previously only a computed `origin` was passed)
- HTTP / GRPC server do not longer try to match the headers to instances
themself, but use the passed `http.DomainContext` in their interceptors.
- The `RequestedHost` and `RequestedDomain` from authz.Instance are
removed in favor of the `http.DomainContext`
- When authenticating to or signing out from Console UI, the current
`http.DomainContext(ctx).Origin` (already checked by instance
interceptor for validity) is used to compute and dynamically add a
`redirect_uri` and `post_logout_redirect_uri`.
- Gateway passes all configured host headers (previously only did
`x-zitadel-*`)
- Admin API allows to manage trusted domain
# Additional Changes
None
# Additional Context
- part of #8279
- open topics:
- "single-instance" mode
- Console UI
2024-07-31 17:00:38 +02:00
|
|
|
return http_utils.DomainContext(ctx).Origin() + HandlerPrefix + callbackPath
|
2023-05-24 20:29:58 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
feat: trusted (instance) domains (#8369)
# Which Problems Are Solved
ZITADEL currently selects the instance context based on a HTTP header
(see https://github.com/zitadel/zitadel/issues/8279#issue-2399959845 and
checks it against the list of instance domains. Let's call it instance
or API domain.
For any context based URL (e.g. OAuth, OIDC, SAML endpoints, links in
emails, ...) the requested domain (instance domain) will be used. Let's
call it the public domain.
In cases of proxied setups, all exposed domains (public domains) require
the domain to be managed as instance domain.
This can either be done using the "ExternalDomain" in the runtime config
or via system API, which requires a validation through CustomerPortal on
zitadel.cloud.
# How the Problems Are Solved
- Two new headers / header list are added:
- `InstanceHostHeaders`: an ordered list (first sent wins), which will
be used to match the instance.
(For backward compatibility: the `HTTP1HostHeader`, `HTTP2HostHeader`
and `forwarded`, `x-forwarded-for`, `x-forwarded-host` are checked
afterwards as well)
- `PublicHostHeaders`: an ordered list (first sent wins), which will be
used as public host / domain. This will be checked against a list of
trusted domains on the instance.
- The middleware intercepts all requests to the API and passes a
`DomainCtx` object with the hosts and protocol into the context
(previously only a computed `origin` was passed)
- HTTP / GRPC server do not longer try to match the headers to instances
themself, but use the passed `http.DomainContext` in their interceptors.
- The `RequestedHost` and `RequestedDomain` from authz.Instance are
removed in favor of the `http.DomainContext`
- When authenticating to or signing out from Console UI, the current
`http.DomainContext(ctx).Origin` (already checked by instance
interceptor for validity) is used to compute and dynamically add a
`redirect_uri` and `post_logout_redirect_uri`.
- Gateway passes all configured host headers (previously only did
`x-zitadel-*`)
- Admin API allows to manage trusted domain
# Additional Changes
None
# Additional Context
- part of #8279
- open topics:
- "single-instance" mode
- Console UI
2024-07-31 17:00:38 +02:00
|
|
|
func SAMLRootURL() func(ctx context.Context, idpID string) string {
|
2023-09-29 11:26:14 +02:00
|
|
|
return func(ctx context.Context, idpID string) string {
|
feat: trusted (instance) domains (#8369)
# Which Problems Are Solved
ZITADEL currently selects the instance context based on a HTTP header
(see https://github.com/zitadel/zitadel/issues/8279#issue-2399959845 and
checks it against the list of instance domains. Let's call it instance
or API domain.
For any context based URL (e.g. OAuth, OIDC, SAML endpoints, links in
emails, ...) the requested domain (instance domain) will be used. Let's
call it the public domain.
In cases of proxied setups, all exposed domains (public domains) require
the domain to be managed as instance domain.
This can either be done using the "ExternalDomain" in the runtime config
or via system API, which requires a validation through CustomerPortal on
zitadel.cloud.
# How the Problems Are Solved
- Two new headers / header list are added:
- `InstanceHostHeaders`: an ordered list (first sent wins), which will
be used to match the instance.
(For backward compatibility: the `HTTP1HostHeader`, `HTTP2HostHeader`
and `forwarded`, `x-forwarded-for`, `x-forwarded-host` are checked
afterwards as well)
- `PublicHostHeaders`: an ordered list (first sent wins), which will be
used as public host / domain. This will be checked against a list of
trusted domains on the instance.
- The middleware intercepts all requests to the API and passes a
`DomainCtx` object with the hosts and protocol into the context
(previously only a computed `origin` was passed)
- HTTP / GRPC server do not longer try to match the headers to instances
themself, but use the passed `http.DomainContext` in their interceptors.
- The `RequestedHost` and `RequestedDomain` from authz.Instance are
removed in favor of the `http.DomainContext`
- When authenticating to or signing out from Console UI, the current
`http.DomainContext(ctx).Origin` (already checked by instance
interceptor for validity) is used to compute and dynamically add a
`redirect_uri` and `post_logout_redirect_uri`.
- Gateway passes all configured host headers (previously only did
`x-zitadel-*`)
- Admin API allows to manage trusted domain
# Additional Changes
None
# Additional Context
- part of #8279
- open topics:
- "single-instance" mode
- Console UI
2024-07-31 17:00:38 +02:00
|
|
|
return http_utils.DomainContext(ctx).Origin() + HandlerPrefix + "/" + idpID + "/"
|
2023-09-29 11:26:14 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
feat: trusted (instance) domains (#8369)
# Which Problems Are Solved
ZITADEL currently selects the instance context based on a HTTP header
(see https://github.com/zitadel/zitadel/issues/8279#issue-2399959845 and
checks it against the list of instance domains. Let's call it instance
or API domain.
For any context based URL (e.g. OAuth, OIDC, SAML endpoints, links in
emails, ...) the requested domain (instance domain) will be used. Let's
call it the public domain.
In cases of proxied setups, all exposed domains (public domains) require
the domain to be managed as instance domain.
This can either be done using the "ExternalDomain" in the runtime config
or via system API, which requires a validation through CustomerPortal on
zitadel.cloud.
# How the Problems Are Solved
- Two new headers / header list are added:
- `InstanceHostHeaders`: an ordered list (first sent wins), which will
be used to match the instance.
(For backward compatibility: the `HTTP1HostHeader`, `HTTP2HostHeader`
and `forwarded`, `x-forwarded-for`, `x-forwarded-host` are checked
afterwards as well)
- `PublicHostHeaders`: an ordered list (first sent wins), which will be
used as public host / domain. This will be checked against a list of
trusted domains on the instance.
- The middleware intercepts all requests to the API and passes a
`DomainCtx` object with the hosts and protocol into the context
(previously only a computed `origin` was passed)
- HTTP / GRPC server do not longer try to match the headers to instances
themself, but use the passed `http.DomainContext` in their interceptors.
- The `RequestedHost` and `RequestedDomain` from authz.Instance are
removed in favor of the `http.DomainContext`
- When authenticating to or signing out from Console UI, the current
`http.DomainContext(ctx).Origin` (already checked by instance
interceptor for validity) is used to compute and dynamically add a
`redirect_uri` and `post_logout_redirect_uri`.
- Gateway passes all configured host headers (previously only did
`x-zitadel-*`)
- Admin API allows to manage trusted domain
# Additional Changes
None
# Additional Context
- part of #8279
- open topics:
- "single-instance" mode
- Console UI
2024-07-31 17:00:38 +02:00
|
|
|
func LoginSAMLRootURL() func(ctx context.Context) string {
|
2024-07-24 14:29:05 +02:00
|
|
|
return func(ctx context.Context) string {
|
feat: trusted (instance) domains (#8369)
# Which Problems Are Solved
ZITADEL currently selects the instance context based on a HTTP header
(see https://github.com/zitadel/zitadel/issues/8279#issue-2399959845 and
checks it against the list of instance domains. Let's call it instance
or API domain.
For any context based URL (e.g. OAuth, OIDC, SAML endpoints, links in
emails, ...) the requested domain (instance domain) will be used. Let's
call it the public domain.
In cases of proxied setups, all exposed domains (public domains) require
the domain to be managed as instance domain.
This can either be done using the "ExternalDomain" in the runtime config
or via system API, which requires a validation through CustomerPortal on
zitadel.cloud.
# How the Problems Are Solved
- Two new headers / header list are added:
- `InstanceHostHeaders`: an ordered list (first sent wins), which will
be used to match the instance.
(For backward compatibility: the `HTTP1HostHeader`, `HTTP2HostHeader`
and `forwarded`, `x-forwarded-for`, `x-forwarded-host` are checked
afterwards as well)
- `PublicHostHeaders`: an ordered list (first sent wins), which will be
used as public host / domain. This will be checked against a list of
trusted domains on the instance.
- The middleware intercepts all requests to the API and passes a
`DomainCtx` object with the hosts and protocol into the context
(previously only a computed `origin` was passed)
- HTTP / GRPC server do not longer try to match the headers to instances
themself, but use the passed `http.DomainContext` in their interceptors.
- The `RequestedHost` and `RequestedDomain` from authz.Instance are
removed in favor of the `http.DomainContext`
- When authenticating to or signing out from Console UI, the current
`http.DomainContext(ctx).Origin` (already checked by instance
interceptor for validity) is used to compute and dynamically add a
`redirect_uri` and `post_logout_redirect_uri`.
- Gateway passes all configured host headers (previously only did
`x-zitadel-*`)
- Admin API allows to manage trusted domain
# Additional Changes
None
# Additional Context
- part of #8279
- open topics:
- "single-instance" mode
- Console UI
2024-07-31 17:00:38 +02:00
|
|
|
return http_utils.DomainContext(ctx).Origin() + login.HandlerPrefix + login.EndpointSAMLACS
|
2024-07-24 14:29:05 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-24 20:29:58 +02:00
|
|
|
func NewHandler(
|
|
|
|
commands *command.Commands,
|
|
|
|
queries *query.Queries,
|
|
|
|
encryptionAlgorithm crypto.EncryptionAlgorithm,
|
|
|
|
instanceInterceptor func(next http.Handler) http.Handler,
|
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>
2025-05-23 13:52:25 +02:00
|
|
|
federatedLogoutCache cache.Cache[federatedlogout.Index, string, *federatedlogout.FederatedLogout],
|
2023-05-24 20:29:58 +02:00
|
|
|
) http.Handler {
|
|
|
|
h := &Handler{
|
2024-07-24 14:29:05 +02:00
|
|
|
commands: commands,
|
|
|
|
queries: queries,
|
|
|
|
parser: form.NewParser(),
|
|
|
|
encryptionAlgorithm: encryptionAlgorithm,
|
feat: trusted (instance) domains (#8369)
# Which Problems Are Solved
ZITADEL currently selects the instance context based on a HTTP header
(see https://github.com/zitadel/zitadel/issues/8279#issue-2399959845 and
checks it against the list of instance domains. Let's call it instance
or API domain.
For any context based URL (e.g. OAuth, OIDC, SAML endpoints, links in
emails, ...) the requested domain (instance domain) will be used. Let's
call it the public domain.
In cases of proxied setups, all exposed domains (public domains) require
the domain to be managed as instance domain.
This can either be done using the "ExternalDomain" in the runtime config
or via system API, which requires a validation through CustomerPortal on
zitadel.cloud.
# How the Problems Are Solved
- Two new headers / header list are added:
- `InstanceHostHeaders`: an ordered list (first sent wins), which will
be used to match the instance.
(For backward compatibility: the `HTTP1HostHeader`, `HTTP2HostHeader`
and `forwarded`, `x-forwarded-for`, `x-forwarded-host` are checked
afterwards as well)
- `PublicHostHeaders`: an ordered list (first sent wins), which will be
used as public host / domain. This will be checked against a list of
trusted domains on the instance.
- The middleware intercepts all requests to the API and passes a
`DomainCtx` object with the hosts and protocol into the context
(previously only a computed `origin` was passed)
- HTTP / GRPC server do not longer try to match the headers to instances
themself, but use the passed `http.DomainContext` in their interceptors.
- The `RequestedHost` and `RequestedDomain` from authz.Instance are
removed in favor of the `http.DomainContext`
- When authenticating to or signing out from Console UI, the current
`http.DomainContext(ctx).Origin` (already checked by instance
interceptor for validity) is used to compute and dynamically add a
`redirect_uri` and `post_logout_redirect_uri`.
- Gateway passes all configured host headers (previously only did
`x-zitadel-*`)
- Admin API allows to manage trusted domain
# Additional Changes
None
# Additional Context
- part of #8279
- open topics:
- "single-instance" mode
- Console UI
2024-07-31 17:00:38 +02:00
|
|
|
callbackURL: CallbackURL(),
|
|
|
|
samlRootURL: SAMLRootURL(),
|
|
|
|
loginSAMLRootURL: LoginSAMLRootURL(),
|
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>
2025-05-23 13:52:25 +02:00
|
|
|
caches: &Caches{federatedLogouts: federatedLogoutCache},
|
2023-05-24 20:29:58 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
router := mux.NewRouter()
|
|
|
|
router.Use(instanceInterceptor)
|
|
|
|
router.HandleFunc(callbackPath, h.handleCallback)
|
2023-09-29 11:26:14 +02:00
|
|
|
router.HandleFunc(metadataPath, h.handleMetadata)
|
|
|
|
router.HandleFunc(certificatePath, h.handleCertificate)
|
|
|
|
router.HandleFunc(acsPath, h.handleACS)
|
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>
2025-05-23 13:52:25 +02:00
|
|
|
router.HandleFunc(sloPath, h.handleSLO)
|
2025-05-27 16:26:46 +02:00
|
|
|
router.HandleFunc(jwtPath, h.handleJWT)
|
2023-05-24 20:29:58 +02:00
|
|
|
return router
|
|
|
|
}
|
|
|
|
|
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>
2025-05-23 13:52:25 +02:00
|
|
|
type Caches struct {
|
|
|
|
federatedLogouts cache.Cache[federatedlogout.Index, string, *federatedlogout.FederatedLogout]
|
|
|
|
}
|
|
|
|
|
2023-09-29 11:26:14 +02:00
|
|
|
func parseSAMLRequest(r *http.Request) *externalSAMLIDPCallbackData {
|
|
|
|
vars := mux.Vars(r)
|
|
|
|
return &externalSAMLIDPCallbackData{
|
|
|
|
IDPID: vars[varIDPID],
|
|
|
|
Response: r.FormValue("SAMLResponse"),
|
|
|
|
RelayState: r.FormValue("RelayState"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Handler) getProvider(ctx context.Context, idpID string) (idp.Provider, error) {
|
|
|
|
return h.commands.GetProvider(ctx, idpID, h.callbackURL(ctx), h.samlRootURL(ctx, idpID))
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Handler) handleCertificate(w http.ResponseWriter, r *http.Request) {
|
|
|
|
ctx := r.Context()
|
|
|
|
data := parseSAMLRequest(r)
|
|
|
|
|
|
|
|
provider, err := h.getProvider(ctx, data.IDPID)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
samlProvider, ok := provider.(*saml2.Provider)
|
|
|
|
if !ok {
|
2023-12-08 16:30:55 +02:00
|
|
|
http.Error(w, zerrors.ThrowInvalidArgument(nil, "SAML-lrud8s9coi", "Errors.Intent.IDPInvalid").Error(), http.StatusBadRequest)
|
2023-09-29 11:26:14 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
certPem := new(bytes.Buffer)
|
|
|
|
if _, err := certPem.Write(samlProvider.Certificate); err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Header().Set("Content-Disposition", "attachment; filename=idp.crt")
|
|
|
|
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
|
|
|
|
_, err = io.Copy(w, certPem)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, fmt.Errorf("failed to response with certificate: %w", err).Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Handler) handleMetadata(w http.ResponseWriter, r *http.Request) {
|
|
|
|
ctx := r.Context()
|
|
|
|
data := parseSAMLRequest(r)
|
|
|
|
|
|
|
|
provider, err := h.getProvider(ctx, data.IDPID)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
samlProvider, ok := provider.(*saml2.Provider)
|
|
|
|
if !ok {
|
2023-12-08 16:30:55 +02:00
|
|
|
http.Error(w, zerrors.ThrowInvalidArgument(nil, "SAML-lrud8s9coi", "Errors.Intent.IDPInvalid").Error(), http.StatusBadRequest)
|
2023-09-29 11:26:14 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
sp, err := samlProvider.GetSP()
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
metadata := sp.ServiceProvider.Metadata()
|
|
|
|
|
2024-11-15 07:19:43 +01:00
|
|
|
internalUI, _ := strconv.ParseBool(r.URL.Query().Get(paramInternalUI))
|
|
|
|
h.assertionConsumerServices(ctx, metadata, internalUI)
|
2024-07-24 14:29:05 +02:00
|
|
|
|
2023-09-29 11:26:14 +02:00
|
|
|
buf, _ := xml.MarshalIndent(metadata, "", " ")
|
|
|
|
w.Header().Set("Content-Type", "application/samlmetadata+xml")
|
|
|
|
_, err = w.Write(buf)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-15 07:19:43 +01:00
|
|
|
func (h *Handler) assertionConsumerServices(ctx context.Context, metadata *saml.EntityDescriptor, internalUI bool) {
|
|
|
|
if !internalUI {
|
|
|
|
for i, spDesc := range metadata.SPSSODescriptors {
|
|
|
|
spDesc.AssertionConsumerServices = append(
|
|
|
|
spDesc.AssertionConsumerServices,
|
|
|
|
saml.IndexedEndpoint{
|
|
|
|
Binding: saml.HTTPPostBinding,
|
|
|
|
Location: h.loginSAMLRootURL(ctx),
|
|
|
|
Index: len(spDesc.AssertionConsumerServices) + 1,
|
|
|
|
}, saml.IndexedEndpoint{
|
|
|
|
Binding: saml.HTTPArtifactBinding,
|
|
|
|
Location: h.loginSAMLRootURL(ctx),
|
|
|
|
Index: len(spDesc.AssertionConsumerServices) + 2,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
metadata.SPSSODescriptors[i] = spDesc
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
for i, spDesc := range metadata.SPSSODescriptors {
|
|
|
|
acs := make([]saml.IndexedEndpoint, 0, len(spDesc.AssertionConsumerServices)+2)
|
|
|
|
acs = append(acs,
|
|
|
|
saml.IndexedEndpoint{
|
|
|
|
Binding: saml.HTTPPostBinding,
|
|
|
|
Location: h.loginSAMLRootURL(ctx),
|
|
|
|
Index: 0,
|
|
|
|
IsDefault: gu.Ptr(true),
|
|
|
|
},
|
|
|
|
saml.IndexedEndpoint{
|
|
|
|
Binding: saml.HTTPArtifactBinding,
|
|
|
|
Location: h.loginSAMLRootURL(ctx),
|
|
|
|
Index: 1,
|
|
|
|
})
|
|
|
|
for i := 0; i < len(spDesc.AssertionConsumerServices); i++ {
|
|
|
|
spDesc.AssertionConsumerServices[i].Index = 2 + i
|
|
|
|
acs = append(acs, spDesc.AssertionConsumerServices[i])
|
|
|
|
}
|
|
|
|
spDesc.AssertionConsumerServices = acs
|
|
|
|
metadata.SPSSODescriptors[i] = spDesc
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-29 11:26:14 +02:00
|
|
|
func (h *Handler) handleACS(w http.ResponseWriter, r *http.Request) {
|
|
|
|
ctx := r.Context()
|
|
|
|
data := parseSAMLRequest(r)
|
|
|
|
|
|
|
|
provider, err := h.getProvider(ctx, data.IDPID)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
samlProvider, ok := provider.(*saml2.Provider)
|
|
|
|
if !ok {
|
2023-12-08 16:30:55 +02:00
|
|
|
err := zerrors.ThrowInvalidArgument(nil, "SAML-ui9wyux0hp", "Errors.Intent.IDPInvalid")
|
2023-09-29 11:26:14 +02:00
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
intent, err := h.commands.GetActiveIntent(ctx, data.RelayState)
|
|
|
|
if err != nil {
|
2023-12-08 16:30:55 +02:00
|
|
|
if zerrors.IsNotFound(err) {
|
2023-09-29 11:26:14 +02:00
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
redirectToFailureURLErr(w, r, intent, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-05-23 07:04:07 +02:00
|
|
|
session, err := saml2.NewSession(samlProvider, intent.RequestID, r)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
2023-09-29 11:26:14 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
idpUser, err := session.FetchUser(r.Context())
|
|
|
|
if err != nil {
|
|
|
|
cmdErr := h.commands.FailIDPIntent(ctx, intent, err.Error())
|
|
|
|
logging.WithFields("intent", intent.AggregateID).OnError(cmdErr).Error("failed to push failed event on idp intent")
|
|
|
|
redirectToFailureURLErr(w, r, intent, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
userID, err := h.checkExternalUser(ctx, intent.IDPID, idpUser.GetID())
|
|
|
|
logging.WithFields("intent", intent.AggregateID).OnError(err).Error("could not check if idp user already exists")
|
|
|
|
|
2025-05-02 13:44:24 +02:00
|
|
|
token, err := h.commands.SucceedSAMLIDPIntent(ctx, intent, idpUser, userID, session)
|
2023-09-29 11:26:14 +02:00
|
|
|
if err != nil {
|
2023-12-08 16:30:55 +02:00
|
|
|
redirectToFailureURLErr(w, r, intent, zerrors.ThrowInternal(err, "IDP-JdD3g", "Errors.Intent.TokenCreationFailed"))
|
2023-09-29 11:26:14 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
redirectToSuccessURL(w, r, intent, token, userID)
|
|
|
|
}
|
|
|
|
|
2025-05-27 16:26:46 +02:00
|
|
|
func (h *Handler) handleJWT(w http.ResponseWriter, r *http.Request) {
|
|
|
|
intentID, err := h.intentIDFromJWTRequest(r)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
intent, err := h.commands.GetActiveIntent(r.Context(), intentID)
|
|
|
|
if err != nil {
|
|
|
|
if zerrors.IsNotFound(err) {
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
redirectToFailureURLErr(w, r, intent, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
idpConfig, err := h.getProvider(r.Context(), intent.IDPID)
|
|
|
|
if err != nil {
|
|
|
|
cmdErr := h.commands.FailIDPIntent(r.Context(), intent, err.Error())
|
|
|
|
logging.WithFields("intent", intent.AggregateID).OnError(cmdErr).Error("failed to push failed event on idp intent")
|
|
|
|
redirectToFailureURLErr(w, r, intent, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
jwtIDP, ok := idpConfig.(*jwt.Provider)
|
|
|
|
if !ok {
|
|
|
|
err := zerrors.ThrowInvalidArgument(nil, "IDP-JK23ed", "Errors.ExternalIDP.IDPTypeNotImplemented")
|
|
|
|
cmdErr := h.commands.FailIDPIntent(r.Context(), intent, err.Error())
|
|
|
|
logging.WithFields("intent", intent.AggregateID).OnError(cmdErr).Error("failed to push failed event on idp intent")
|
|
|
|
redirectToFailureURLErr(w, r, intent, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
h.handleJWTExtraction(w, r, intent, jwtIDP)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Handler) intentIDFromJWTRequest(r *http.Request) (string, error) {
|
|
|
|
// for compatibility of the old JWT provider we use the auth request id parameter to pass the intent id
|
|
|
|
intentID := r.FormValue(jwt.QueryAuthRequestID)
|
|
|
|
// for compatibility of the old JWT provider we use the user agent id parameter to pass the encrypted intent id
|
|
|
|
encryptedIntentID := r.FormValue(jwt.QueryUserAgentID)
|
|
|
|
if err := h.checkIntentID(intentID, encryptedIntentID); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return intentID, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Handler) checkIntentID(intentID, encryptedIntentID string) error {
|
|
|
|
if intentID == "" || encryptedIntentID == "" {
|
|
|
|
return zerrors.ThrowInvalidArgument(nil, "LOGIN-adfzz", "Errors.AuthRequest.MissingParameters")
|
|
|
|
}
|
|
|
|
id, err := base64.RawURLEncoding.DecodeString(encryptedIntentID)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
decryptedIntentID, err := h.encryptionAlgorithm.DecryptString(id, h.encryptionAlgorithm.EncryptionKeyID())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if intentID != decryptedIntentID {
|
|
|
|
return zerrors.ThrowInvalidArgument(nil, "LOGIN-adfzz", "Errors.AuthRequest.MissingParameters")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Handler) handleJWTExtraction(w http.ResponseWriter, r *http.Request, intent *command.IDPIntentWriteModel, identityProvider *jwt.Provider) {
|
|
|
|
session := jwt.NewSessionFromRequest(identityProvider, r)
|
|
|
|
user, err := session.FetchUser(r.Context())
|
|
|
|
if err != nil {
|
|
|
|
cmdErr := h.commands.FailIDPIntent(r.Context(), intent, err.Error())
|
|
|
|
logging.WithFields("intent", intent.AggregateID).OnError(cmdErr).Error("failed to push failed event on idp intent")
|
|
|
|
redirectToFailureURLErr(w, r, intent, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
userID, err := h.checkExternalUser(r.Context(), intent.IDPID, user.GetID())
|
|
|
|
logging.WithFields("intent", intent.AggregateID).OnError(err).Error("could not check if idp user already exists")
|
|
|
|
|
|
|
|
token, err := h.commands.SucceedIDPIntent(r.Context(), intent, user, session, userID)
|
|
|
|
if err != nil {
|
|
|
|
redirectToFailureURLErr(w, r, intent, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
redirectToSuccessURL(w, r, intent, token, userID)
|
|
|
|
}
|
|
|
|
|
2023-05-24 20:29:58 +02:00
|
|
|
func (h *Handler) handleCallback(w http.ResponseWriter, r *http.Request) {
|
2023-08-16 13:29:57 +02:00
|
|
|
ctx := r.Context()
|
2023-05-24 20:29:58 +02:00
|
|
|
data, err := h.parseCallbackRequest(r)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
2023-08-16 13:29:57 +02:00
|
|
|
intent, err := h.commands.GetActiveIntent(ctx, data.State)
|
|
|
|
if err != nil {
|
2023-12-08 16:30:55 +02:00
|
|
|
if zerrors.IsNotFound(err) {
|
2023-08-16 13:29:57 +02:00
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
redirectToFailureURLErr(w, r, intent, err)
|
2023-05-24 20:29:58 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// the provider might have returned an error
|
|
|
|
if data.Error != "" {
|
|
|
|
cmdErr := h.commands.FailIDPIntent(ctx, intent, reason(data.Error, data.ErrorDescription))
|
|
|
|
logging.WithFields("intent", intent.AggregateID).OnError(cmdErr).Error("failed to push failed event on idp intent")
|
|
|
|
redirectToFailureURL(w, r, intent, data.Error, data.ErrorDescription)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-09-29 11:26:14 +02:00
|
|
|
provider, err := h.getProvider(ctx, intent.IDPID)
|
2023-05-24 20:29:58 +02:00
|
|
|
if err != nil {
|
|
|
|
cmdErr := h.commands.FailIDPIntent(ctx, intent, err.Error())
|
|
|
|
logging.WithFields("intent", intent.AggregateID).OnError(cmdErr).Error("failed to push failed event on idp intent")
|
|
|
|
redirectToFailureURLErr(w, r, intent, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2025-02-26 13:20:47 +01:00
|
|
|
idpUser, idpSession, err := h.fetchIDPUserFromCode(ctx, provider, data.Code, data.User, intent.IDPArguments)
|
2023-05-24 20:29:58 +02:00
|
|
|
if err != nil {
|
|
|
|
cmdErr := h.commands.FailIDPIntent(ctx, intent, err.Error())
|
|
|
|
logging.WithFields("intent", intent.AggregateID).OnError(cmdErr).Error("failed to push failed event on idp intent")
|
|
|
|
redirectToFailureURLErr(w, r, intent, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
userID, err := h.checkExternalUser(ctx, intent.IDPID, idpUser.GetID())
|
|
|
|
logging.WithFields("intent", intent.AggregateID).OnError(err).Error("could not check if idp user already exists")
|
|
|
|
|
2023-08-04 11:35:36 +02:00
|
|
|
if userID == "" {
|
|
|
|
userID, err = h.tryMigrateExternalUser(ctx, intent.IDPID, idpUser, idpSession)
|
|
|
|
logging.WithFields("intent", intent.AggregateID).OnError(err).Error("migration check failed")
|
|
|
|
}
|
|
|
|
|
2023-05-24 20:29:58 +02:00
|
|
|
token, err := h.commands.SucceedIDPIntent(ctx, intent, idpUser, idpSession, userID)
|
|
|
|
if err != nil {
|
2023-12-08 16:30:55 +02:00
|
|
|
redirectToFailureURLErr(w, r, intent, zerrors.ThrowInternal(err, "IDP-JdD3g", "Errors.Intent.TokenCreationFailed"))
|
2023-05-24 20:29:58 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
redirectToSuccessURL(w, r, intent, token, userID)
|
|
|
|
}
|
|
|
|
|
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>
2025-05-23 13:52:25 +02:00
|
|
|
func (h *Handler) handleSLO(w http.ResponseWriter, r *http.Request) {
|
|
|
|
ctx := r.Context()
|
|
|
|
data := parseSAMLRequest(r)
|
|
|
|
|
|
|
|
logoutState, ok := h.caches.federatedLogouts.Get(ctx, federatedlogout.IndexRequestID, federatedlogout.Key(authz.GetInstance(ctx).InstanceID(), data.RelayState))
|
|
|
|
if !ok || logoutState.State != federatedlogout.StateRedirected {
|
|
|
|
err := zerrors.ThrowNotFound(nil, "SAML-3uor2", "Errors.Intent.NotFound")
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// For the moment we just make sure the callback matches the IDP it was started on / intended for.
|
|
|
|
|
|
|
|
provider, err := h.getProvider(ctx, data.IDPID)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if _, ok = provider.(*saml2.Provider); !ok {
|
|
|
|
err := zerrors.ThrowInvalidArgument(nil, "SAML-ui9wyux0hp", "Errors.Intent.IDPInvalid")
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// We could also parse and validate the response here, but for example Azure does not sign it and thus would already fail.
|
|
|
|
// Also we can't really act on it if it fails.
|
|
|
|
|
|
|
|
err = h.caches.federatedLogouts.Delete(ctx, federatedlogout.IndexRequestID, federatedlogout.Key(logoutState.InstanceID, logoutState.SessionID))
|
|
|
|
logging.WithFields("instanceID", logoutState.InstanceID, "sessionID", logoutState.SessionID).OnError(err).Error("could not delete federated logout")
|
|
|
|
http.Redirect(w, r, logoutState.PostLogoutRedirectURI, http.StatusFound)
|
|
|
|
}
|
|
|
|
|
2023-08-04 11:35:36 +02:00
|
|
|
func (h *Handler) tryMigrateExternalUser(ctx context.Context, idpID string, idpUser idp.User, idpSession idp.Session) (userID string, err error) {
|
|
|
|
migration, ok := idpSession.(idp.SessionSupportsMigration)
|
|
|
|
if !ok {
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
previousID, err := migration.RetrievePreviousID()
|
|
|
|
if err != nil || previousID == "" {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
userID, err = h.checkExternalUser(ctx, idpID, previousID)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return userID, h.commands.MigrateUserIDP(ctx, userID, "", idpID, previousID, idpUser.GetID())
|
|
|
|
}
|
|
|
|
|
2023-05-24 20:29:58 +02:00
|
|
|
func (h *Handler) parseCallbackRequest(r *http.Request) (*externalIDPCallbackData, error) {
|
|
|
|
data := new(externalIDPCallbackData)
|
|
|
|
err := h.parser.Parse(r, data)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if data.State == "" {
|
2023-12-08 16:30:55 +02:00
|
|
|
return nil, zerrors.ThrowInvalidArgument(nil, "IDP-Hk38e", "Errors.Intent.StateMissing")
|
2023-05-24 20:29:58 +02:00
|
|
|
}
|
|
|
|
return data, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func redirectToSuccessURL(w http.ResponseWriter, r *http.Request, intent *command.IDPIntentWriteModel, token, userID string) {
|
|
|
|
queries := intent.SuccessURL.Query()
|
|
|
|
queries.Set(paramIntentID, intent.AggregateID)
|
|
|
|
queries.Set(paramToken, token)
|
|
|
|
if userID != "" {
|
|
|
|
queries.Set(paramUserID, userID)
|
|
|
|
}
|
|
|
|
intent.SuccessURL.RawQuery = queries.Encode()
|
|
|
|
http.Redirect(w, r, intent.SuccessURL.String(), http.StatusFound)
|
|
|
|
}
|
|
|
|
|
|
|
|
func redirectToFailureURLErr(w http.ResponseWriter, r *http.Request, i *command.IDPIntentWriteModel, err error) {
|
|
|
|
msg := err.Error()
|
|
|
|
var description string
|
2023-12-08 16:30:55 +02:00
|
|
|
zErr := new(zerrors.ZitadelError)
|
2023-05-24 20:29:58 +02:00
|
|
|
if errors.As(err, &zErr) {
|
|
|
|
msg = zErr.GetID()
|
|
|
|
description = zErr.GetMessage() // TODO: i18n?
|
|
|
|
}
|
|
|
|
redirectToFailureURL(w, r, i, msg, description)
|
|
|
|
}
|
|
|
|
|
|
|
|
func redirectToFailureURL(w http.ResponseWriter, r *http.Request, i *command.IDPIntentWriteModel, err, description string) {
|
|
|
|
queries := i.FailureURL.Query()
|
|
|
|
queries.Set(paramIntentID, i.AggregateID)
|
|
|
|
queries.Set(paramError, err)
|
|
|
|
queries.Set(paramErrorDescription, description)
|
|
|
|
i.FailureURL.RawQuery = queries.Encode()
|
|
|
|
http.Redirect(w, r, i.FailureURL.String(), http.StatusFound)
|
|
|
|
}
|
|
|
|
|
2025-02-26 13:20:47 +01:00
|
|
|
func (h *Handler) fetchIDPUserFromCode(ctx context.Context, identityProvider idp.Provider, code string, appleUser string, idpArguments map[string]any) (user idp.User, idpTokens idp.Session, err error) {
|
2023-05-24 20:29:58 +02:00
|
|
|
var session idp.Session
|
|
|
|
switch provider := identityProvider.(type) {
|
|
|
|
case *oauth.Provider:
|
2025-02-26 13:20:47 +01:00
|
|
|
session = oauth.NewSession(provider, code, idpArguments)
|
2023-05-24 20:29:58 +02:00
|
|
|
case *openid.Provider:
|
2025-02-26 13:20:47 +01:00
|
|
|
session = openid.NewSession(provider, code, idpArguments)
|
2023-05-24 20:29:58 +02:00
|
|
|
case *azuread.Provider:
|
2025-02-26 13:20:47 +01:00
|
|
|
session = azuread.NewSession(provider, code)
|
2023-05-24 20:29:58 +02:00
|
|
|
case *github.Provider:
|
2025-02-26 13:20:47 +01:00
|
|
|
session = oauth.NewSession(provider.Provider, code, idpArguments)
|
2023-05-24 20:29:58 +02:00
|
|
|
case *gitlab.Provider:
|
2025-02-26 13:20:47 +01:00
|
|
|
session = openid.NewSession(provider.Provider, code, idpArguments)
|
2023-05-24 20:29:58 +02:00
|
|
|
case *google.Provider:
|
2025-02-26 13:20:47 +01:00
|
|
|
session = openid.NewSession(provider.Provider, code, idpArguments)
|
2023-08-31 08:39:16 +02:00
|
|
|
case *apple.Provider:
|
2025-02-26 13:20:47 +01:00
|
|
|
session = apple.NewSession(provider, code, appleUser)
|
2023-09-29 11:26:14 +02:00
|
|
|
case *jwt.Provider, *ldap.Provider, *saml2.Provider:
|
2023-12-08 16:30:55 +02:00
|
|
|
return nil, nil, zerrors.ThrowInvalidArgument(nil, "IDP-52jmn", "Errors.ExternalIDP.IDPTypeNotImplemented")
|
2023-05-24 20:29:58 +02:00
|
|
|
default:
|
2023-12-08 16:30:55 +02:00
|
|
|
return nil, nil, zerrors.ThrowUnimplemented(nil, "IDP-SSDg", "Errors.ExternalIDP.IDPTypeNotImplemented")
|
2023-05-24 20:29:58 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
user, err = session.FetchUser(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
return user, session, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Handler) checkExternalUser(ctx context.Context, idpID, externalUserID string) (userID string, err error) {
|
|
|
|
idQuery, err := query.NewIDPUserLinkIDPIDSearchQuery(idpID)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
externalIDQuery, err := query.NewIDPUserLinksExternalIDSearchQuery(externalUserID)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
queries := []query.SearchQuery{
|
|
|
|
idQuery, externalIDQuery,
|
|
|
|
}
|
2024-08-23 08:44:18 +02:00
|
|
|
links, err := h.queries.IDPUserLinks(ctx, &query.IDPUserLinksSearchQuery{Queries: queries}, nil)
|
2023-05-24 20:29:58 +02:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
if len(links.Links) != 1 {
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
return links.Links[0].UserID, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func reason(err, description string) string {
|
|
|
|
if description == "" {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return err + ": " + description
|
|
|
|
}
|