Files
zitadel/internal/api/ui/login/login.go
T
Tim MöhlmannandGitHub eb22b58756 feat(telemetry): improved instrumentation for observability (#11159)
# Which Problems Are Solved

Zitadel did not provide easy correlation between errors, logs, traces
and metrics. The configuration for those instrumentations was also not
consistent, with some supporting different exporters then others.
Implementation and parsing of config was also spaghettified over
multiple packages, with awkward parsing and inconsistent naming of
options.

# How the Problems Are Solved

All telemetry is now merged under the name "instrumentation". Why?
1. We thought it was a good idea in the past to call the milestone
exporter `Telemtry` in the runtime config. Calling this `TelemetryV2`
looks weird.
2. Not everything is a meter and not everything is sent (tele...). 
3. It's also
[defined](https://opentelemetry.io/docs/concepts/instrumentation/) as
such by the OTEL documentation.

## New features

- Adds structured, context based logging with trace-ID awareness
- Static log fields are added to the context, such as service and
request path
- Static log fields are injected in each logline emitted by the
application
- Structured logs can also be send to an otel exporter
- Structured logs can be printed to StdErr in text and JSON format
- Error sinks make sure every error is logged at the correct level:
- Warnings for client side errors (HTTP 400 range, Invalid request etc)
  - Error for server side errors (Internal server errors)
- Metrics can now also be send to a OTEL collector. (previously they
could only be scraped from `/debug/metrics` with prometheus)

## Exporters

This change adds all the exporters supported by OTEL upstream and some
google specific exporters for our cloud deployment.

- StdOut / StdErr: all instrumentations
- OTEL gRPC / HTTP: all instrumentations
- Google: all instrumentations except logging
- Prometheus (pull-based): only metrics

The exception is profiling, which only supports the google exporting due
to lack of support by OTEL upstream.

## Configuration and structure 

- All instrumentation is moved into the new `backend/v3/instrumentation`
package. It reuses configuration types, so both code and runtime
configuration are easier to understand.
- The `internal/telemetry` packages are removed.
- Instrumentation is started with a single function and a proper
shutdown function is now provided.
- Legacy configuration is still parsed from the runtime config, as long
as the new configuration is disabled. This allows backporting this
feature to v4 without breaking existing configurations.

# Additional Changes

- Devcontainer: set `$PATH` variable so installed go binaries can be run
individually, without NX.
- NX: install GCI tool to fix imports

# Additional Context

- Closes https://github.com/zitadel/zitadel/issues/8408
- Closes https://github.com/zitadel/zitadel/issues/6664
- Backport to v4
2026-01-12 05:51:39 +00:00

290 lines
9.4 KiB
Go

package login
import (
"context"
"net/http"
"net/url"
"strings"
"time"
"github.com/gorilla/csrf"
"github.com/gorilla/mux"
"github.com/zitadel/zitadel/internal/api/authz"
http_utils "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/api/http/middleware"
_ "github.com/zitadel/zitadel/internal/api/ui/login/statik"
auth_repository "github.com/zitadel/zitadel/internal/auth/repository"
"github.com/zitadel/zitadel/internal/auth/repository/eventsourcing"
"github.com/zitadel/zitadel/internal/cache"
"github.com/zitadel/zitadel/internal/cache/connector"
"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"
)
type Login struct {
endpoint string
router http.Handler
renderer *Renderer
parser *form.Parser
command *command.Commands
query *query.Queries
staticStorage static.Storage
authRepo auth_repository.Repository
externalSecure bool
consolePath string
oidcAuthCallbackURL func(context.Context, string) string
samlAuthCallbackURL func(context.Context, string) string
idpConfigAlg crypto.EncryptionAlgorithm
userCodeAlg crypto.EncryptionAlgorithm
caches *Caches
}
type Config struct {
LanguageCookieName string
CSRFCookieName string
Cache middleware.CacheConfig
AssetCache middleware.CacheConfig
// LoginV2
DefaultPaths *DefaultPaths
}
type DefaultPaths struct {
BasePath string
PasswordSetPath string
EmailCodePath string
OTPEmailPath string
}
func (c *Config) defaultBaseURL(ctx context.Context) string {
loginV2 := authz.GetInstance(ctx).Features().LoginV2
if loginV2.Required {
// use the origin as default
baseURI := http_utils.DomainContext(ctx).Origin()
// use custom base URI if defined
if loginV2.BaseURI != nil && loginV2.BaseURI.String() != "" {
baseURI = loginV2.BaseURI.String()
}
return baseURI + c.DefaultPaths.BasePath
}
return ""
}
func (c *Config) DefaultEmailCodeURLTemplate(ctx context.Context) string {
basePath := c.defaultBaseURL(ctx)
if basePath == "" {
return ""
}
return basePath + c.DefaultPaths.EmailCodePath
}
func (c *Config) DefaultPasswordSetURLTemplate(ctx context.Context) string {
basePath := c.defaultBaseURL(ctx)
if basePath == "" {
return ""
}
return c.defaultBaseURL(ctx) + c.DefaultPaths.PasswordSetPath
}
const (
login = "LOGIN"
HandlerPrefix = "/ui/login"
DefaultLoggedOutPath = HandlerPrefix + EndpointLogoutDone
)
func CreateLogin(
config Config,
command *command.Commands,
query *query.Queries,
authRepo *eventsourcing.EsRepository,
staticStorage static.Storage,
consolePath string,
oidcAuthCallbackURL, samlAuthCallbackURL func(context.Context, string) string,
externalSecure bool,
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,
samlAuthCallbackURL: samlAuthCallbackURL,
externalSecure: externalSecure,
consolePath: consolePath,
command: command,
query: query,
staticStorage: staticStorage,
authRepo: authRepo,
idpConfigAlg: idpConfigAlg,
userCodeAlg: userCodeAlg,
}
csrfInterceptor := createCSRFInterceptor(config.CSRFCookieName, csrfCookieKey, externalSecure, login.csrfErrorHandler())
cacheInterceptor := createCacheInterceptor(config.Cache.MaxAge, config.Cache.SharedMaxAge, assetCache)
security := middleware.SecurityHeaders(csp(), login.cspErrorHandler)
login.router = CreateRouter(login,
middleware.TraceHandler(IgnoreInstanceEndpoints...),
middleware.LogHandler("login_v1", IgnoreInstanceEndpoints...),
oidcInstanceHandler,
samlInstanceHandler,
csrfInterceptor,
cacheInterceptor,
security,
userAgentCookie,
issuerInterceptor,
accessHandler,
)
login.renderer = CreateRenderer(HandlerPrefix, staticStorage, config.LanguageCookieName)
login.parser = form.NewParser()
var err error
login.caches, err = startCaches(context.Background(), cacheConnectors, federateLogoutCache)
if err != nil {
return nil, err
}
return login, nil
}
func csp() *middleware.CSP {
csp := middleware.DefaultSCP
csp.ObjectSrc = middleware.CSPSourceOptsSelf()
csp.StyleSrc = csp.StyleSrc.AddNonce()
csp.ScriptSrc = csp.ScriptSrc.AddNonce().
// SAML POST ACS
AddHash("sha256", "AjPdJSbZmeWHnEc5ykvJFay8FTWeTeRbs9dutfZ0HqE=").
// SAML POST SLO
AddHash("sha256", "4Su6mBWzEIFnH4pAGMOuaeBrstwJN4Z3pq/s1Kn4/KQ=")
return &csp
}
func createCSRFInterceptor(cookieName string, csrfCookieKey []byte, externalSecure bool, errorHandler http.Handler) func(http.Handler) http.Handler {
path := "/"
return func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, EndpointResources) {
handler.ServeHTTP(w, r)
return
}
// ignore form post callback
// it will redirect to the "normal" callback, where the cookie is set again
if (r.URL.Path == EndpointExternalLoginCallbackFormPost || r.URL.Path == EndpointSAMLACS) && r.Method == http.MethodPost {
handler.ServeHTTP(w, r)
return
}
// by default we use SameSite Lax and the externalSecure (TLS) for the secure flag
sameSiteMode := csrf.SameSiteLaxMode
secureOnly := externalSecure
instance := authz.GetInstance(r.Context())
// in case of `allow iframe`...
if len(instance.SecurityPolicyAllowedOrigins()) > 0 {
// ... we need to change to SameSite none ...
sameSiteMode = csrf.SameSiteNoneMode
// ... and since SameSite none requires the secure flag, we'll set it for TLS and for localhost
// (regardless of the TLS / externalSecure settings)
secureOnly = externalSecure || http_utils.DomainContext(r.Context()).RequestedDomain() == "localhost"
}
csrf.Protect(csrfCookieKey,
csrf.Secure(secureOnly),
csrf.CookieName(http_utils.SetCookiePrefix(cookieName, externalSecure, http_utils.PrefixHost)),
csrf.Path(path),
csrf.ErrorHandler(errorHandler),
csrf.SameSite(sameSiteMode),
)(handler).ServeHTTP(w, r)
})
}
}
func createCacheInterceptor(maxAge, sharedMaxAge time.Duration, assetCache mux.MiddlewareFunc) func(http.Handler) http.Handler {
return func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, EndpointDynamicResources) {
assetCache.Middleware(handler).ServeHTTP(w, r)
return
}
if strings.HasPrefix(r.URL.Path, EndpointResources) {
middleware.AssetsCacheInterceptor(maxAge, sharedMaxAge).Handler(handler).ServeHTTP(w, r)
return
}
middleware.NoCacheInterceptor().Handler(handler).ServeHTTP(w, r)
})
}
}
func (l *Login) Handler() http.Handler {
return l.router
}
func (l *Login) getClaimedUserIDsOfOrgDomain(ctx context.Context, orgName string) ([]string, error) {
orgDomain, err := domain.NewIAMDomainName(orgName, http_utils.DomainContext(ctx).RequestedDomain())
if err != nil {
return nil, err
}
return l.query.SearchClaimedUserIDsOfOrgDomain(ctx, orgDomain, "")
}
func setContext(ctx context.Context, resourceOwner string) context.Context {
data := authz.CtxData{
UserID: login,
OrgID: resourceOwner,
}
return authz.SetCtxData(ctx, data)
}
func setUserContext(ctx context.Context, userID, resourceOwner string) context.Context {
data := authz.CtxData{
UserID: userID,
OrgID: resourceOwner,
}
return authz.SetCtxData(ctx, data)
}
func (l *Login) baseURL(ctx context.Context) string {
return http_utils.DomainContext(ctx).Origin() + HandlerPrefix
}
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, 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
}
type idpFormCallbackIndex int
const (
idpFormCallbackIndexUnspecified idpFormCallbackIndex = iota
idpFormCallbackIndexRequestID
)
type idpFormCallback struct {
InstanceID string
State string
Form url.Values
}
// Keys implements cache.Entry
func (c *idpFormCallback) Keys(i idpFormCallbackIndex) []string {
if i == idpFormCallbackIndexRequestID {
return []string{idpFormCallbackKey(c.InstanceID, c.State)}
}
return nil
}
func idpFormCallbackKey(instanceID, state string) string {
return instanceID + "-" + state
}