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
This commit is contained in:
Livio Spring
2024-07-31 17:00:38 +02:00
committed by GitHub
parent cc3ec1e2a7
commit 3d071fc505
94 changed files with 1693 additions and 674 deletions

View File

@@ -32,7 +32,7 @@ type API struct {
verifier internal_authz.APITokenVerifier
health healthCheck
router *mux.Router
http1HostName string
hostHeaders []string
grpcGateway *server.Gateway
healthServer *health.Server
accessInterceptor *http_mw.AccessInterceptor
@@ -75,7 +75,8 @@ func New(
verifier internal_authz.APITokenVerifier,
authZ internal_authz.Config,
tlsConfig *tls.Config,
http2HostName, http1HostName, externalDomain string,
externalDomain string,
hostHeaders []string,
accessInterceptor *http_mw.AccessInterceptor,
) (_ *API, err error) {
api := &API{
@@ -83,13 +84,13 @@ func New(
verifier: verifier,
health: queries,
router: router,
http1HostName: http1HostName,
queries: queries,
accessInterceptor: accessInterceptor,
hostHeaders: hostHeaders,
}
api.grpcServer = server.CreateServer(api.verifier, authZ, queries, http2HostName, externalDomain, tlsConfig, accessInterceptor.AccessService())
api.grpcGateway, err = server.CreateGateway(ctx, port, http1HostName, accessInterceptor, tlsConfig)
api.grpcServer = server.CreateServer(api.verifier, authZ, queries, externalDomain, tlsConfig, accessInterceptor.AccessService())
api.grpcGateway, err = server.CreateGateway(ctx, port, hostHeaders, accessInterceptor, tlsConfig)
if err != nil {
return nil, err
}
@@ -112,9 +113,8 @@ func (a *API) RegisterServer(ctx context.Context, grpcServer server.WithGatewayP
ctx,
grpcServer,
a.port,
a.http1HostName,
a.hostHeaders,
a.accessInterceptor,
a.queries,
tlsConfig,
)
if err != nil {

View File

@@ -55,9 +55,9 @@ func (h *Handler) Storage() static.Storage {
return h.storage
}
func AssetAPI(externalSecure bool) func(context.Context) string {
func AssetAPI() func(context.Context) string {
return func(ctx context.Context) string {
return http_util.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), externalSecure) + HandlerPrefix
return http_util.DomainContext(ctx).Origin() + HandlerPrefix
}
}

View File

@@ -18,8 +18,6 @@ type Instance interface {
ProjectID() string
ConsoleClientID() string
ConsoleApplicationID() string
RequestedDomain() string
RequestedHost() string
DefaultLanguage() language.Tag
DefaultOrganisationID() string
SecurityPolicyAllowedOrigins() []string
@@ -30,7 +28,7 @@ type Instance interface {
}
type InstanceVerifier interface {
InstanceByHost(ctx context.Context, host string) (Instance, error)
InstanceByHost(ctx context.Context, host, publicDomain string) (Instance, error)
InstanceByID(ctx context.Context) (Instance, error)
}
@@ -68,14 +66,6 @@ func (i *instance) ConsoleApplicationID() string {
return i.appID
}
func (i *instance) RequestedDomain() string {
return i.domain
}
func (i *instance) RequestedHost() string {
return i.domain
}
func (i *instance) DefaultLanguage() language.Tag {
return language.Und
}
@@ -116,16 +106,6 @@ func WithInstanceID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, instanceKey, &instance{id: id})
}
func WithRequestedDomain(ctx context.Context, domain string) context.Context {
i, ok := ctx.Value(instanceKey).(*instance)
if !ok {
i = new(instance)
}
i.domain = domain
return context.WithValue(ctx, instanceKey, i)
}
func WithConsole(ctx context.Context, projectID, appID string) context.Context {
i, ok := ctx.Value(instanceKey).(*instance)
if !ok {

View File

@@ -118,14 +118,6 @@ func (m *mockInstance) DefaultOrganisationID() string {
return "orgID"
}
func (m *mockInstance) RequestedDomain() string {
return "zitadel.cloud"
}
func (m *mockInstance) RequestedHost() string {
return "zitadel.cloud:443"
}
func (m *mockInstance) SecurityPolicyAllowedOrigins() []string {
return nil
}

View File

@@ -37,3 +37,42 @@ func (s *Server) ListInstanceDomains(ctx context.Context, req *admin_pb.ListInst
),
}, nil
}
func (s *Server) ListInstanceTrustedDomains(ctx context.Context, req *admin_pb.ListInstanceTrustedDomainsRequest) (*admin_pb.ListInstanceTrustedDomainsResponse, error) {
queries, err := ListInstanceTrustedDomainsRequestToModel(req)
if err != nil {
return nil, err
}
domains, err := s.query.SearchInstanceTrustedDomains(ctx, queries)
if err != nil {
return nil, err
}
return &admin_pb.ListInstanceTrustedDomainsResponse{
Result: instance_grpc.TrustedDomainsToPb(domains.Domains),
Details: object.ToListDetails(
domains.Count,
domains.Sequence,
domains.LastRun,
),
}, nil
}
func (s *Server) AddInstanceTrustedDomain(ctx context.Context, req *admin_pb.AddInstanceTrustedDomainRequest) (*admin_pb.AddInstanceTrustedDomainResponse, error) {
details, err := s.command.AddTrustedDomain(ctx, req.Domain)
if err != nil {
return nil, err
}
return &admin_pb.AddInstanceTrustedDomainResponse{
Details: object.DomainToAddDetailsPb(details),
}, nil
}
func (s *Server) RemoveInstanceTrustedDomain(ctx context.Context, req *admin_pb.RemoveInstanceTrustedDomainRequest) (*admin_pb.RemoveInstanceTrustedDomainResponse, error) {
details, err := s.command.RemoveTrustedDomain(ctx, req.Domain)
if err != nil {
return nil, err
}
return &admin_pb.RemoveInstanceTrustedDomainResponse{
Details: object.DomainToChangeDetailsPb(details),
}, nil
}

View File

@@ -39,3 +39,20 @@ func fieldNameToInstanceDomainColumn(fieldName instance.DomainFieldName) query.C
return query.Column{}
}
}
func ListInstanceTrustedDomainsRequestToModel(req *admin_pb.ListInstanceTrustedDomainsRequest) (*query.InstanceTrustedDomainSearchQueries, error) {
offset, limit, asc := object.ListQueryToModel(req.Query)
queries, err := instance_grpc.TrustedDomainQueriesToModel(req.Queries)
if err != nil {
return nil, err
}
return &query.InstanceTrustedDomainSearchQueries{
SearchRequest: query.SearchRequest{
Offset: offset,
Limit: limit,
Asc: asc,
SortingColumn: fieldNameToInstanceDomainColumn(req.SortingColumn),
},
Queries: queries,
}, nil
}

View File

@@ -6,6 +6,7 @@ import (
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/grpc/object"
org_grpc "github.com/zitadel/zitadel/internal/api/grpc/org"
http_utils "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/query"
@@ -69,7 +70,7 @@ func (s *Server) ListOrgs(ctx context.Context, req *admin_pb.ListOrgsRequest) (*
}
func (s *Server) SetUpOrg(ctx context.Context, req *admin_pb.SetUpOrgRequest) (*admin_pb.SetUpOrgResponse, error) {
orgDomain, err := domain.NewIAMDomainName(req.Org.Name, authz.GetInstance(ctx).RequestedDomain())
orgDomain, err := domain.NewIAMDomainName(req.Org.Name, http_utils.DomainContext(ctx).RequestedDomain())
if err != nil {
return nil, err
}

View File

@@ -11,7 +11,6 @@ import (
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/grpc/server"
"github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/config/systemdefaults"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/pkg/grpc/admin"
@@ -41,8 +40,6 @@ func CreateServer(
database string,
command *command.Commands,
query *query.Queries,
sd systemdefaults.SystemDefaults,
externalSecure bool,
userCodeAlg crypto.EncryptionAlgorithm,
auditLogRetention time.Duration,
) *Server {
@@ -50,7 +47,7 @@ func CreateServer(
database: database,
command: command,
query: query,
assetsAPIDomain: assets.AssetAPI(externalSecure),
assetsAPIDomain: assets.AssetAPI(),
userCodeAlg: userCodeAlg,
auditLogRetention: auditLogRetention,
}

View File

@@ -67,10 +67,9 @@ func (s *Server) AddMyPasswordlessLink(ctx context.Context, _ *auth_pb.AddMyPass
if err != nil {
return nil, err
}
origin := http.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), s.externalSecure)
return &auth_pb.AddMyPasswordlessLinkResponse{
Details: object.AddToDetailsPb(initCode.Sequence, initCode.ChangeDate, initCode.ResourceOwner),
Link: initCode.Link(origin + login.HandlerPrefix + login.EndpointPasswordlessRegistration),
Link: initCode.Link(http.DomainContext(ctx).Origin() + login.HandlerPrefix + login.EndpointPasswordlessRegistration),
Expiration: durationpb.New(initCode.Expiration),
}, nil
}

View File

@@ -31,7 +31,6 @@ type Server struct {
defaults systemdefaults.SystemDefaults
assetsAPIDomain func(context.Context) string
userCodeAlg crypto.EncryptionAlgorithm
externalSecure bool
}
type Config struct {
@@ -43,16 +42,14 @@ func CreateServer(command *command.Commands,
authRepo repository.Repository,
defaults systemdefaults.SystemDefaults,
userCodeAlg crypto.EncryptionAlgorithm,
externalSecure bool,
) *Server {
return &Server{
command: command,
query: query,
repo: authRepo,
defaults: defaults,
assetsAPIDomain: assets.AssetAPI(externalSecure),
assetsAPIDomain: assets.AssetAPI(),
userCodeAlg: userCodeAlg,
externalSecure: externalSecure,
}
}

View File

@@ -115,3 +115,43 @@ func DomainToPb(d *query.InstanceDomain) *instance_pb.Domain {
),
}
}
func TrustedDomainQueriesToModel(queries []*instance_pb.TrustedDomainSearchQuery) (_ []query.SearchQuery, err error) {
q := make([]query.SearchQuery, len(queries))
for i, query := range queries {
q[i], err = TrustedDomainQueryToModel(query)
if err != nil {
return nil, err
}
}
return q, nil
}
func TrustedDomainQueryToModel(searchQuery *instance_pb.TrustedDomainSearchQuery) (query.SearchQuery, error) {
switch q := searchQuery.Query.(type) {
case *instance_pb.TrustedDomainSearchQuery_DomainQuery:
return query.NewInstanceTrustedDomainDomainSearchQuery(object.TextMethodToQuery(q.DomainQuery.Method), q.DomainQuery.Domain)
default:
return nil, zerrors.ThrowInvalidArgument(nil, "INST-Ags42", "List.Query.Invalid")
}
}
func TrustedDomainsToPb(domains []*query.InstanceTrustedDomain) []*instance_pb.TrustedDomain {
d := make([]*instance_pb.TrustedDomain, len(domains))
for i, domain := range domains {
d[i] = TrustedDomainToPb(domain)
}
return d
}
func TrustedDomainToPb(d *query.InstanceTrustedDomain) *instance_pb.TrustedDomain {
return &instance_pb.TrustedDomain{
Domain: d.Domain,
Details: object.ToViewDetailsPb(
d.Sequence,
d.CreationDate,
d.ChangeDate,
d.InstanceID,
),
}
}

View File

@@ -5,7 +5,6 @@ import (
"github.com/zitadel/oidc/v3/pkg/oidc"
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/http"
mgmt_pb "github.com/zitadel/zitadel/pkg/grpc/management"
)
@@ -15,7 +14,7 @@ func (s *Server) Healthz(context.Context, *mgmt_pb.HealthzRequest) (*mgmt_pb.Hea
}
func (s *Server) GetOIDCInformation(ctx context.Context, _ *mgmt_pb.GetOIDCInformationRequest) (*mgmt_pb.GetOIDCInformationResponse, error) {
issuer := http.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), s.externalSecure)
issuer := http.DomainContext(ctx).Origin()
return &mgmt_pb.GetOIDCInformationResponse{
Issuer: issuer,
DiscoveryEndpoint: issuer + oidc.DiscoveryEndpoint,

View File

@@ -11,6 +11,7 @@ import (
obj_grpc "github.com/zitadel/zitadel/internal/api/grpc/object"
org_grpc "github.com/zitadel/zitadel/internal/api/grpc/org"
policy_grpc "github.com/zitadel/zitadel/internal/api/grpc/policy"
http_utils "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/eventstore/v1/models"
@@ -73,7 +74,7 @@ func (s *Server) ListOrgChanges(ctx context.Context, req *mgmt_pb.ListOrgChanges
}
func (s *Server) AddOrg(ctx context.Context, req *mgmt_pb.AddOrgRequest) (*mgmt_pb.AddOrgResponse, error) {
orgDomain, err := domain.NewIAMDomainName(req.Name, authz.GetInstance(ctx).RequestedDomain())
orgDomain, err := domain.NewIAMDomainName(req.Name, http_utils.DomainContext(ctx).RequestedDomain())
if err != nil {
return nil, err
}

View File

@@ -28,7 +28,6 @@ type Server struct {
systemDefaults systemdefaults.SystemDefaults
assetAPIPrefix func(context.Context) string
userCodeAlg crypto.EncryptionAlgorithm
externalSecure bool
}
func CreateServer(
@@ -36,15 +35,13 @@ func CreateServer(
query *query.Queries,
sd systemdefaults.SystemDefaults,
userCodeAlg crypto.EncryptionAlgorithm,
externalSecure bool,
) *Server {
return &Server{
command: command,
query: query,
systemDefaults: sd,
assetAPIPrefix: assets.AssetAPI(externalSecure),
assetAPIPrefix: assets.AssetAPI(),
userCodeAlg: userCodeAlg,
externalSecure: externalSecure,
}
}

View File

@@ -286,9 +286,8 @@ func (s *Server) ImportHumanUser(ctx context.Context, req *mgmt_pb.ImportHumanUs
),
}
if code != nil {
origin := http.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), s.externalSecure)
resp.PasswordlessRegistration = &mgmt_pb.ImportHumanUserResponse_PasswordlessRegistration{
Link: code.Link(origin + login.HandlerPrefix + login.EndpointPasswordlessRegistration),
Link: code.Link(http.DomainContext(ctx).Origin() + login.HandlerPrefix + login.EndpointPasswordlessRegistration),
Lifetime: durationpb.New(code.Expiration),
Expiration: durationpb.New(code.Expiration),
}
@@ -691,10 +690,9 @@ func (s *Server) AddPasswordlessRegistration(ctx context.Context, req *mgmt_pb.A
if err != nil {
return nil, err
}
origin := http.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), s.externalSecure)
return &mgmt_pb.AddPasswordlessRegistrationResponse{
Details: obj_grpc.AddToDetailsPb(initCode.Sequence, initCode.ChangeDate, initCode.ResourceOwner),
Link: initCode.Link(origin + login.HandlerPrefix + login.EndpointPasswordlessRegistration),
Link: initCode.Link(http.DomainContext(ctx).Origin() + login.HandlerPrefix + login.EndpointPasswordlessRegistration),
Expiration: durationpb.New(initCode.Expiration),
}, nil
}

View File

@@ -8,7 +8,6 @@ import (
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/grpc/object/v2"
"github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/api/oidc"
@@ -107,7 +106,7 @@ func (s *Server) linkSessionToAuthRequest(ctx context.Context, authRequestID str
return nil, err
}
authReq := &oidc.AuthRequestV2{CurrentAuthRequest: aar}
ctx = op.ContextWithIssuer(ctx, http.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), s.externalSecure))
ctx = op.ContextWithIssuer(ctx, http.DomainContext(ctx).Origin())
var callback string
if aar.ResponseType == domain.OIDCResponseTypeCode {
callback, err = oidc.CreateCodeCallbackURL(ctx, authReq, s.op.Provider())

View File

@@ -8,7 +8,6 @@ import (
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/api/authz"
object "github.com/zitadel/zitadel/internal/api/grpc/object/v2beta"
"github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/api/oidc"
@@ -107,7 +106,7 @@ func (s *Server) linkSessionToAuthRequest(ctx context.Context, authRequestID str
return nil, err
}
authReq := &oidc.AuthRequestV2{CurrentAuthRequest: aar}
ctx = op.ContextWithIssuer(ctx, http.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), s.externalSecure))
ctx = op.ContextWithIssuer(ctx, http.DomainContext(ctx).Origin())
var callback string
if aar.ResponseType == domain.OIDCResponseTypeCode {
callback, err = oidc.CreateCodeCallbackURL(ctx, authReq, s.op.Provider())

View File

@@ -5,6 +5,7 @@ import (
"crypto/tls"
"fmt"
"net/http"
"slices"
"strings"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
@@ -19,10 +20,8 @@ import (
"google.golang.org/protobuf/proto"
client_middleware "github.com/zitadel/zitadel/internal/api/grpc/client/middleware"
"github.com/zitadel/zitadel/internal/api/grpc/server/middleware"
http_utils "github.com/zitadel/zitadel/internal/api/http"
http_mw "github.com/zitadel/zitadel/internal/api/http/middleware"
"github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/telemetry/metrics"
)
@@ -57,26 +56,29 @@ var (
},
)
serveMuxOptions = []runtime.ServeMuxOption{
runtime.WithMarshalerOption(jsonMarshaler.ContentType(nil), jsonMarshaler),
runtime.WithMarshalerOption(mimeWildcard, jsonMarshaler),
runtime.WithMarshalerOption(runtime.MIMEWildcard, jsonMarshaler),
runtime.WithIncomingHeaderMatcher(headerMatcher),
runtime.WithOutgoingHeaderMatcher(runtime.DefaultHeaderMatcher),
runtime.WithForwardResponseOption(responseForwarder),
runtime.WithRoutingErrorHandler(httpErrorHandler),
serveMuxOptions = func(hostHeaders []string) []runtime.ServeMuxOption {
return []runtime.ServeMuxOption{
runtime.WithMarshalerOption(jsonMarshaler.ContentType(nil), jsonMarshaler),
runtime.WithMarshalerOption(mimeWildcard, jsonMarshaler),
runtime.WithMarshalerOption(runtime.MIMEWildcard, jsonMarshaler),
runtime.WithIncomingHeaderMatcher(headerMatcher(hostHeaders)),
runtime.WithOutgoingHeaderMatcher(runtime.DefaultHeaderMatcher),
runtime.WithForwardResponseOption(responseForwarder),
runtime.WithRoutingErrorHandler(httpErrorHandler),
}
}
headerMatcher = runtime.HeaderMatcherFunc(
func(header string) (string, bool) {
headerMatcher = func(hostHeaders []string) runtime.HeaderMatcherFunc {
customHeaders = slices.Compact(append(customHeaders, hostHeaders...))
return func(header string) (string, bool) {
for _, customHeader := range customHeaders {
if strings.HasPrefix(strings.ToLower(header), customHeader) {
return header, true
}
}
return runtime.DefaultHeaderMatcher(header)
},
)
}
}
responseForwarder = func(ctx context.Context, w http.ResponseWriter, resp proto.Message) error {
t, ok := resp.(CustomHTTPResponse)
@@ -90,14 +92,12 @@ var (
type Gateway struct {
mux *runtime.ServeMux
http1HostName string
connection *grpc.ClientConn
accessInterceptor *http_mw.AccessInterceptor
queries *query.Queries
}
func (g *Gateway) Handler() http.Handler {
return addInterceptors(g.mux, g.http1HostName, g.accessInterceptor, g.queries)
return addInterceptors(g.mux, g.accessInterceptor)
}
type CustomHTTPResponse interface {
@@ -110,12 +110,11 @@ func CreateGatewayWithPrefix(
ctx context.Context,
g WithGatewayPrefix,
port uint16,
http1HostName string,
hostHeaders []string,
accessInterceptor *http_mw.AccessInterceptor,
queries *query.Queries,
tlsConfig *tls.Config,
) (http.Handler, string, error) {
runtimeMux := runtime.NewServeMux(serveMuxOptions...)
runtimeMux := runtime.NewServeMux(serveMuxOptions(hostHeaders)...)
opts := []grpc.DialOption{
grpc.WithTransportCredentials(grpcCredentials(tlsConfig)),
grpc.WithChainUnaryInterceptor(
@@ -131,13 +130,13 @@ func CreateGatewayWithPrefix(
if err != nil {
return nil, "", fmt.Errorf("failed to register grpc gateway: %w", err)
}
return addInterceptors(runtimeMux, http1HostName, accessInterceptor, queries), g.GatewayPathPrefix(), nil
return addInterceptors(runtimeMux, accessInterceptor), g.GatewayPathPrefix(), nil
}
func CreateGateway(
ctx context.Context,
port uint16,
http1HostName string,
hostHeaders []string,
accessInterceptor *http_mw.AccessInterceptor,
tlsConfig *tls.Config,
) (*Gateway, error) {
@@ -153,10 +152,9 @@ func CreateGateway(
if err != nil {
return nil, err
}
runtimeMux := runtime.NewServeMux(append(serveMuxOptions, runtime.WithHealthzEndpoint(healthpb.NewHealthClient(connection)))...)
runtimeMux := runtime.NewServeMux(append(serveMuxOptions(hostHeaders), runtime.WithHealthzEndpoint(healthpb.NewHealthClient(connection)))...)
return &Gateway{
mux: runtimeMux,
http1HostName: http1HostName,
connection: connection,
accessInterceptor: accessInterceptor,
}, nil
@@ -195,12 +193,9 @@ func dial(ctx context.Context, port uint16, opts []grpc.DialOption) (*grpc.Clien
func addInterceptors(
handler http.Handler,
http1HostName string,
accessInterceptor *http_mw.AccessInterceptor,
queries *query.Queries,
) http.Handler {
handler = http_mw.CallDurationHandler(handler)
handler = http1Host(handler, http1HostName)
handler = http_mw.CORSInterceptor(handler)
handler = http_mw.RobotsTagHandler(handler)
handler = http_mw.DefaultTelemetryHandler(handler)
@@ -215,18 +210,6 @@ func addInterceptors(
return handler
}
func http1Host(next http.Handler, http1HostName string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
host, err := http_mw.HostFromRequest(r, http1HostName)
if err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
r.Header.Set(middleware.HTTP1Host, host)
next.ServeHTTP(w, r)
})
}
func exhaustedCookieInterceptor(
next http.Handler,
accessInterceptor *http_mw.AccessInterceptor,

View File

@@ -9,6 +9,7 @@ import (
"google.golang.org/grpc/status"
"github.com/zitadel/zitadel/internal/api/authz"
http_util "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/logstore"
"github.com/zitadel/zitadel/internal/logstore/record"
"github.com/zitadel/zitadel/internal/telemetry/tracing"
@@ -35,6 +36,7 @@ func AccessStorageInterceptor(svc *logstore.Service[*record.AccessLog]) grpc.Una
resMd, _ := metadata.FromOutgoingContext(ctx)
instance := authz.GetInstance(ctx)
domainCtx := http_util.DomainContext(ctx)
r := &record.AccessLog{
LogDate: time.Now(),
@@ -45,8 +47,8 @@ func AccessStorageInterceptor(svc *logstore.Service[*record.AccessLog]) grpc.Una
ResponseHeaders: resMd,
InstanceID: instance.InstanceID(),
ProjectID: instance.ProjectID(),
RequestedDomain: instance.RequestedDomain(),
RequestedHost: instance.RequestedHost(),
RequestedDomain: domainCtx.RequestedDomain(),
RequestedHost: domainCtx.RequestedHost(),
}
svc.Handle(interceptorCtx, r)

View File

@@ -10,7 +10,6 @@ import (
"golang.org/x/text/language"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"github.com/zitadel/zitadel/internal/api/authz"
@@ -24,15 +23,15 @@ const (
HTTP1Host = "x-zitadel-http1-host"
)
func InstanceInterceptor(verifier authz.InstanceVerifier, headerName, externalDomain string, explicitInstanceIdServices ...string) grpc.UnaryServerInterceptor {
func InstanceInterceptor(verifier authz.InstanceVerifier, externalDomain string, explicitInstanceIdServices ...string) grpc.UnaryServerInterceptor {
translator, err := i18n.NewZitadelTranslator(language.English)
logging.OnError(err).Panic("unable to get translator")
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
return setInstance(ctx, req, info, handler, verifier, headerName, externalDomain, translator, explicitInstanceIdServices...)
return setInstance(ctx, req, info, handler, verifier, externalDomain, translator, explicitInstanceIdServices...)
}
}
func setInstance(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, verifier authz.InstanceVerifier, headerName, externalDomain string, translator *i18n.Translator, idFromRequestsServices ...string) (_ interface{}, err error) {
func setInstance(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, verifier authz.InstanceVerifier, externalDomain string, translator *i18n.Translator, idFromRequestsServices ...string) (_ interface{}, err error) {
interceptorCtx, span := tracing.NewServerInterceptorSpan(ctx)
defer func() { span.EndWithError(err) }()
for _, service := range idFromRequestsServices {
@@ -56,14 +55,15 @@ func setInstance(ctx context.Context, req interface{}, info *grpc.UnaryServerInf
return handler(authz.WithInstance(ctx, instance), req)
}
}
host, err := hostFromContext(interceptorCtx, headerName)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
requestContext := zitadel_http.DomainContext(ctx)
if requestContext.InstanceHost == "" {
logging.WithFields("origin", requestContext.Origin(), "externalDomain", externalDomain).WithError(err).Error("unable to set instance")
return nil, status.Error(codes.NotFound, "no instanceHost specified")
}
instance, err := verifier.InstanceByHost(interceptorCtx, host)
instance, err := verifier.InstanceByHost(interceptorCtx, requestContext.InstanceHost, requestContext.PublicHost)
if err != nil {
origin := zitadel_http.ComposedOrigin(ctx)
logging.WithFields("origin", origin, "externalDomain", externalDomain).WithError(err).Error("unable to set instance")
origin := zitadel_http.DomainContext(ctx)
logging.WithFields("origin", requestContext.Origin(), "externalDomain", externalDomain).WithError(err).Error("unable to set instance")
zErr := new(zerrors.ZitadelError)
if errors.As(err, &zErr) {
zErr.SetMessage(translator.LocalizeFromCtx(ctx, zErr.GetMessage(), nil))
@@ -75,33 +75,3 @@ func setInstance(ctx context.Context, req interface{}, info *grpc.UnaryServerInf
span.End()
return handler(authz.WithInstance(ctx, instance), req)
}
func hostFromContext(ctx context.Context, headerName string) (string, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return "", fmt.Errorf("cannot read metadata")
}
host, ok := md[HTTP1Host]
if ok && len(host) == 1 {
if !isAllowedToSendHTTP1Header(md) {
return "", fmt.Errorf("no valid host header")
}
return host[0], nil
}
host, ok = md[headerName]
if !ok {
return "", fmt.Errorf("cannot find header: %v", headerName)
}
if len(host) != 1 {
return "", fmt.Errorf("invalid host header: %v", host)
}
return host[0], nil
}
// isAllowedToSendHTTP1Header check if the gRPC call was sent to `localhost`
// this is only possible when calling the server directly running on localhost
// or through the gRPC gateway
func isAllowedToSendHTTP1Header(md metadata.MD) bool {
authority, ok := md[":authority"]
return ok && len(authority) == 1 && strings.Split(authority[0], ":")[0] == "localhost"
}

View File

@@ -9,82 +9,19 @@ import (
"golang.org/x/text/language"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"github.com/zitadel/zitadel/internal/api/authz"
http_util "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/feature"
)
func Test_hostNameFromContext(t *testing.T) {
type args struct {
ctx context.Context
headerName string
}
type res struct {
want string
err bool
}
tests := []struct {
name string
args args
res res
}{
{
"empty context, error",
args{
ctx: context.Background(),
headerName: "header",
},
res{
want: "",
err: true,
},
},
{
"header not found",
args{
ctx: metadata.NewIncomingContext(context.Background(), nil),
headerName: "header",
},
res{
want: "",
err: true,
},
},
{
"header not found",
args{
ctx: metadata.NewIncomingContext(context.Background(), metadata.Pairs("header", "value")),
headerName: "header",
},
res{
want: "value",
err: false,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := hostFromContext(tt.args.ctx, tt.args.headerName)
if (err != nil) != tt.res.err {
t.Errorf("hostFromContext() error = %v, wantErr %v", err, tt.res.err)
return
}
if got != tt.res.want {
t.Errorf("hostFromContext() got = %v, want %v", got, tt.res.want)
}
})
}
}
func Test_setInstance(t *testing.T) {
type args struct {
ctx context.Context
req interface{}
info *grpc.UnaryServerInfo
handler grpc.UnaryHandler
verifier authz.InstanceVerifier
headerName string
ctx context.Context
req interface{}
info *grpc.UnaryServerInfo
handler grpc.UnaryHandler
verifier authz.InstanceVerifier
}
type res struct {
want interface{}
@@ -108,10 +45,9 @@ func Test_setInstance(t *testing.T) {
{
"invalid host, error",
args{
ctx: metadata.NewIncomingContext(context.Background(), metadata.Pairs("header", "host2")),
req: &mockRequest{},
verifier: &mockInstanceVerifier{"host"},
headerName: "header",
ctx: http_util.WithDomainContext(context.Background(), &http_util.DomainCtx{InstanceHost: "host2"}),
req: &mockRequest{},
verifier: &mockInstanceVerifier{instanceHost: "host"},
},
res{
want: nil,
@@ -121,10 +57,9 @@ func Test_setInstance(t *testing.T) {
{
"valid host",
args{
ctx: metadata.NewIncomingContext(context.Background(), metadata.Pairs("header", "host")),
req: &mockRequest{},
verifier: &mockInstanceVerifier{"host"},
headerName: "header",
ctx: http_util.WithDomainContext(context.Background(), &http_util.DomainCtx{InstanceHost: "host"}),
req: &mockRequest{},
verifier: &mockInstanceVerifier{instanceHost: "host"},
handler: func(ctx context.Context, req interface{}) (interface{}, error) {
return req, nil
},
@@ -137,7 +72,7 @@ func Test_setInstance(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := setInstance(tt.args.ctx, tt.args.req, tt.args.info, tt.args.handler, tt.args.verifier, tt.args.headerName, "", nil)
got, err := setInstance(tt.args.ctx, tt.args.req, tt.args.info, tt.args.handler, tt.args.verifier, "", nil)
if (err != nil) != tt.res.err {
t.Errorf("setInstance() error = %v, wantErr %v", err, tt.res.err)
return
@@ -152,11 +87,18 @@ func Test_setInstance(t *testing.T) {
type mockRequest struct{}
type mockInstanceVerifier struct {
host string
instanceHost string
publicHost string
}
func (m *mockInstanceVerifier) InstanceByHost(_ context.Context, host string) (authz.Instance, error) {
if host != m.host {
func (m *mockInstanceVerifier) InstanceByHost(_ context.Context, instanceHost, publicHost string) (authz.Instance, error) {
if instanceHost != m.instanceHost {
return nil, fmt.Errorf("invalid host")
}
if publicHost == "" {
return &mockInstance{}, nil
}
if publicHost != instanceHost && publicHost != m.publicHost {
return nil, fmt.Errorf("invalid host")
}
return &mockInstance{}, nil
@@ -198,14 +140,6 @@ func (m *mockInstance) DefaultOrganisationID() string {
return "orgID"
}
func (m *mockInstance) RequestedDomain() string {
return "localhost"
}
func (m *mockInstance) RequestedHost() string {
return "localhost:8080"
}
func (m *mockInstance) SecurityPolicyAllowedOrigins() []string {
return nil
}

View File

@@ -38,7 +38,6 @@ func CreateServer(
verifier authz.APITokenVerifier,
authConfig authz.Config,
queries *query.Queries,
hostHeaderName string,
externalDomain string,
tlsConfig *tls.Config,
accessSvc *logstore.Service[*record.AccessLog],
@@ -51,7 +50,7 @@ func CreateServer(
middleware.DefaultTracingServer(),
middleware.MetricsHandler(metricTypes, grpc_api.Probes...),
middleware.NoCacheInterceptor(),
middleware.InstanceInterceptor(queries, hostHeaderName, externalDomain, system_pb.SystemService_ServiceDesc.ServiceName, healthpb.Health_ServiceDesc.ServiceName),
middleware.InstanceInterceptor(queries, externalDomain, system_pb.SystemService_ServiceDesc.ServiceName, healthpb.Health_ServiceDesc.ServiceName),
middleware.AccessStorageInterceptor(accessSvc),
middleware.ErrorHandler(),
middleware.LimitsInterceptor(system_pb.SystemService_ServiceDesc.ServiceName),

View File

@@ -27,12 +27,11 @@ type Config struct{}
func CreateServer(
command *command.Commands,
query *query.Queries,
externalSecure bool,
) *Server {
return &Server{
command: command,
query: query,
assetsAPIDomain: assets.AssetAPI(externalSecure),
assetsAPIDomain: assets.AssetAPI(),
}
}

View File

@@ -27,12 +27,11 @@ type Config struct{}
func CreateServer(
command *command.Commands,
query *query.Queries,
externalSecure bool,
) *Server {
return &Server{
command: command,
query: query,
assetsAPIDomain: assets.AssetAPI(externalSecure),
assetsAPIDomain: assets.AssetAPI(),
}
}

View File

@@ -20,6 +20,9 @@ const (
Pragma = "pragma"
UserAgentHeader = "user-agent"
ForwardedFor = "x-forwarded-for"
ForwardedHost = "x-forwarded-host"
ForwardedProto = "x-forwarded-proto"
Forwarded = "forwarded"
XUserAgent = "x-user-agent"
XGrpcWeb = "x-grpc-web"
XRequestedWith = "x-requested-with"
@@ -45,7 +48,7 @@ type key int
const (
httpHeaders key = iota
remoteAddr
origin
domainCtx
)
func CopyHeadersToContext(h http.Handler) http.Handler {
@@ -70,18 +73,6 @@ func OriginHeader(ctx context.Context) string {
return headers.Get(Origin)
}
func ComposedOrigin(ctx context.Context) string {
o, ok := ctx.Value(origin).(string)
if !ok {
return ""
}
return o
}
func WithComposedOrigin(ctx context.Context, composed string) context.Context {
return context.WithValue(ctx, origin, composed)
}
func RemoteIPFromCtx(ctx context.Context) string {
ctxHeaders, ok := HeadersFromCtx(ctx)
if !ok {

View File

@@ -163,6 +163,7 @@ func (a *AccessInterceptor) writeLog(ctx context.Context, wrappedWriter *statusR
logging.WithError(err).WithField("url", requestURL).Warning("failed to unescape request url")
}
instance := authz.GetInstance(ctx)
domainCtx := http_utils.DomainContext(ctx)
a.logstoreSvc.Handle(ctx, &record.AccessLog{
LogDate: time.Now(),
Protocol: record.HTTP,
@@ -172,8 +173,8 @@ func (a *AccessInterceptor) writeLog(ctx context.Context, wrappedWriter *statusR
ResponseHeaders: writer.Header(),
InstanceID: instance.InstanceID(),
ProjectID: instance.ProjectID(),
RequestedDomain: instance.RequestedDomain(),
RequestedHost: instance.RequestedHost(),
RequestedDomain: domainCtx.RequestedDomain(),
RequestedHost: domainCtx.RequestedHost(),
NotCountable: notCountable,
})
}

View File

@@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/zitadel/logging"
@@ -19,16 +18,15 @@ import (
)
type instanceInterceptor struct {
verifier authz.InstanceVerifier
headerName, externalDomain string
ignoredPrefixes []string
translator *i18n.Translator
verifier authz.InstanceVerifier
externalDomain string
ignoredPrefixes []string
translator *i18n.Translator
}
func InstanceInterceptor(verifier authz.InstanceVerifier, headerName, externalDomain string, ignoredPrefixes ...string) *instanceInterceptor {
func InstanceInterceptor(verifier authz.InstanceVerifier, externalDomain string, ignoredPrefixes ...string) *instanceInterceptor {
return &instanceInterceptor{
verifier: verifier,
headerName: headerName,
externalDomain: externalDomain,
ignoredPrefixes: ignoredPrefixes,
translator: newZitadelTranslator(),
@@ -54,10 +52,10 @@ func (a *instanceInterceptor) handleInstance(w http.ResponseWriter, r *http.Requ
return
}
}
ctx, err := setInstance(r, a.verifier, a.headerName)
ctx, err := setInstance(r, a.verifier)
if err != nil {
origin := zitadel_http.ComposedOrigin(r.Context())
logging.WithFields("origin", origin, "externalDomain", a.externalDomain).WithError(err).Error("unable to set instance")
origin := zitadel_http.DomainContext(r.Context())
logging.WithFields("origin", origin.Origin(), "externalDomain", a.externalDomain).WithError(err).Error("unable to set instance")
zErr := new(zerrors.ZitadelError)
if errors.As(err, &zErr) {
zErr.SetMessage(a.translator.LocalizeFromRequest(r, zErr.GetMessage(), nil))
@@ -71,18 +69,16 @@ func (a *instanceInterceptor) handleInstance(w http.ResponseWriter, r *http.Requ
next.ServeHTTP(w, r)
}
func setInstance(r *http.Request, verifier authz.InstanceVerifier, headerName string) (_ context.Context, err error) {
func setInstance(r *http.Request, verifier authz.InstanceVerifier) (_ context.Context, err error) {
ctx := r.Context()
authCtx, span := tracing.NewServerInterceptorSpan(ctx)
defer func() { span.EndWithError(err) }()
host, err := HostFromRequest(r, headerName)
if err != nil {
requestContext := zitadel_http.DomainContext(ctx)
if requestContext.InstanceHost == "" {
return nil, zerrors.ThrowNotFound(err, "INST-zWq7X", "Errors.IAM.NotFound")
}
instance, err := verifier.InstanceByHost(authCtx, host)
instance, err := verifier.InstanceByHost(authCtx, requestContext.InstanceHost, requestContext.PublicHost)
if err != nil {
return nil, err
}
@@ -90,39 +86,6 @@ func setInstance(r *http.Request, verifier authz.InstanceVerifier, headerName st
return authz.WithInstance(ctx, instance), nil
}
func HostFromRequest(r *http.Request, headerName string) (host string, err error) {
if headerName != "host" {
return hostFromSpecialHeader(r, headerName)
}
return hostFromOrigin(r.Context())
}
func hostFromSpecialHeader(r *http.Request, headerName string) (host string, err error) {
host = r.Header.Get(headerName)
if host == "" {
return "", fmt.Errorf("host header `%s` not found", headerName)
}
return host, nil
}
func hostFromOrigin(ctx context.Context) (host string, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("invalid origin: %w", err)
}
}()
origin := zitadel_http.ComposedOrigin(ctx)
u, err := url.Parse(origin)
if err != nil {
return "", err
}
host = u.Host
if host == "" {
err = errors.New("empty host")
}
return host, err
}
func newZitadelTranslator() *i18n.Translator {
translator, err := i18n.NewZitadelTranslator(language.English)
logging.OnError(err).Panic("unable to get translator")

View File

@@ -19,8 +19,7 @@ import (
func Test_instanceInterceptor_Handler(t *testing.T) {
type fields struct {
verifier authz.InstanceVerifier
headerName string
verifier authz.InstanceVerifier
}
type args struct {
request *http.Request
@@ -38,8 +37,7 @@ func Test_instanceInterceptor_Handler(t *testing.T) {
{
"setInstance error",
fields{
verifier: &mockInstanceVerifier{},
headerName: "header",
verifier: &mockInstanceVerifier{},
},
args{
request: httptest.NewRequest("", "/url", nil),
@@ -52,19 +50,18 @@ func Test_instanceInterceptor_Handler(t *testing.T) {
{
"setInstance ok",
fields{
verifier: &mockInstanceVerifier{"host"},
headerName: "header",
verifier: &mockInstanceVerifier{instanceHost: "host"},
},
args{
request: func() *http.Request {
r := httptest.NewRequest("", "/url", nil)
r.Header.Set("header", "host")
r = r.WithContext(zitadel_http.WithDomainContext(r.Context(), &zitadel_http.DomainCtx{InstanceHost: "host"}))
return r
}(),
},
res{
statusCode: 200,
context: authz.WithInstance(context.Background(), &mockInstance{}),
context: authz.WithInstance(zitadel_http.WithDomainContext(context.Background(), &zitadel_http.DomainCtx{InstanceHost: "host"}), &mockInstance{}),
},
},
}
@@ -72,7 +69,6 @@ func Test_instanceInterceptor_Handler(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
a := &instanceInterceptor{
verifier: tt.fields.verifier,
headerName: tt.fields.headerName,
translator: newZitadelTranslator(),
}
next := &testHandler{}
@@ -87,8 +83,7 @@ func Test_instanceInterceptor_Handler(t *testing.T) {
func Test_instanceInterceptor_HandlerFunc(t *testing.T) {
type fields struct {
verifier authz.InstanceVerifier
headerName string
verifier authz.InstanceVerifier
}
type args struct {
request *http.Request
@@ -106,8 +101,7 @@ func Test_instanceInterceptor_HandlerFunc(t *testing.T) {
{
"setInstance error",
fields{
verifier: &mockInstanceVerifier{},
headerName: "header",
verifier: &mockInstanceVerifier{},
},
args{
request: httptest.NewRequest("", "/url", nil),
@@ -120,19 +114,18 @@ func Test_instanceInterceptor_HandlerFunc(t *testing.T) {
{
"setInstance ok",
fields{
verifier: &mockInstanceVerifier{"host"},
headerName: "header",
verifier: &mockInstanceVerifier{instanceHost: "host"},
},
args{
request: func() *http.Request {
r := httptest.NewRequest("", "/url", nil)
r.Header.Set("header", "host")
r = r.WithContext(zitadel_http.WithDomainContext(r.Context(), &zitadel_http.DomainCtx{InstanceHost: "host"}))
return r
}(),
},
res{
statusCode: 200,
context: authz.WithInstance(context.Background(), &mockInstance{}),
context: authz.WithInstance(zitadel_http.WithDomainContext(context.Background(), &zitadel_http.DomainCtx{InstanceHost: "host"}), &mockInstance{}),
},
},
}
@@ -140,7 +133,6 @@ func Test_instanceInterceptor_HandlerFunc(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
a := &instanceInterceptor{
verifier: tt.fields.verifier,
headerName: tt.fields.headerName,
translator: newZitadelTranslator(),
}
next := &testHandler{}
@@ -155,9 +147,8 @@ func Test_instanceInterceptor_HandlerFunc(t *testing.T) {
func Test_setInstance(t *testing.T) {
type args struct {
r *http.Request
verifier authz.InstanceVerifier
headerName string
r *http.Request
verifier authz.InstanceVerifier
}
type res struct {
want context.Context
@@ -169,14 +160,13 @@ func Test_setInstance(t *testing.T) {
res res
}{
{
"special host header not found, error",
"no domain context, not found error",
args{
r: func() *http.Request {
r := httptest.NewRequest("", "/url", nil)
return r
}(),
verifier: &mockInstanceVerifier{},
headerName: "",
verifier: &mockInstanceVerifier{},
},
res{
want: nil,
@@ -184,77 +174,27 @@ func Test_setInstance(t *testing.T) {
},
},
{
"special host header invalid, error",
"instanceHost found, ok",
args{
r: func() *http.Request {
r := httptest.NewRequest("", "/url", nil)
r.Header.Set("header", "host2")
return r
return r.WithContext(zitadel_http.WithDomainContext(r.Context(), &zitadel_http.DomainCtx{InstanceHost: "host", Protocol: "https"}))
}(),
verifier: &mockInstanceVerifier{"host"},
headerName: "header",
verifier: &mockInstanceVerifier{instanceHost: "host"},
},
res{
want: nil,
err: true,
},
},
{
"special host header valid, ok",
args{
r: func() *http.Request {
r := httptest.NewRequest("", "/url", nil)
r.Header.Set("header", "host")
return r
}(),
verifier: &mockInstanceVerifier{"host"},
headerName: "header",
},
res{
want: authz.WithInstance(context.Background(), &mockInstance{}),
want: authz.WithInstance(zitadel_http.WithDomainContext(context.Background(), &zitadel_http.DomainCtx{InstanceHost: "host", Protocol: "https"}), &mockInstance{}),
err: false,
},
},
{
"host from origin if header is not special, ok",
"instanceHost not found, error",
args{
r: func() *http.Request {
r := httptest.NewRequest("", "/url", nil)
r.Header.Set("host", "fromrequest")
return r.WithContext(zitadel_http.WithComposedOrigin(r.Context(), "https://fromorigin:9999"))
return r.WithContext(zitadel_http.WithDomainContext(r.Context(), &zitadel_http.DomainCtx{InstanceHost: "fromorigin:9999", Protocol: "https"}))
}(),
verifier: &mockInstanceVerifier{"fromorigin:9999"},
headerName: "host",
},
res{
want: authz.WithInstance(zitadel_http.WithComposedOrigin(context.Background(), "https://fromorigin:9999"), &mockInstance{}),
err: false,
},
},
{
"host from origin, instance not found",
args{
r: func() *http.Request {
r := httptest.NewRequest("", "/url", nil)
return r.WithContext(zitadel_http.WithComposedOrigin(r.Context(), "https://fromorigin:9999"))
}(),
verifier: &mockInstanceVerifier{"unknowndomain"},
headerName: "host",
},
res{
want: nil,
err: true,
},
},
{
"host from origin invalid, err",
args{
r: func() *http.Request {
r := httptest.NewRequest("", "/url", nil)
return r.WithContext(zitadel_http.WithComposedOrigin(r.Context(), "https://from origin:9999"))
}(),
verifier: &mockInstanceVerifier{"from origin"},
headerName: "host",
verifier: &mockInstanceVerifier{instanceHost: "unknowndomain"},
},
res{
want: nil,
@@ -264,7 +204,7 @@ func Test_setInstance(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := setInstance(tt.args.r, tt.args.verifier, tt.args.headerName)
got, err := setInstance(tt.args.r, tt.args.verifier)
if (err != nil) != tt.res.err {
t.Errorf("setInstance() error = %v, wantErr %v", err, tt.res.err)
return
@@ -285,11 +225,18 @@ func (t *testHandler) ServeHTTP(_ http.ResponseWriter, r *http.Request) {
}
type mockInstanceVerifier struct {
host string
instanceHost string
publicHost string
}
func (m *mockInstanceVerifier) InstanceByHost(_ context.Context, host string) (authz.Instance, error) {
if host != m.host {
func (m *mockInstanceVerifier) InstanceByHost(_ context.Context, instanceHost, publicHost string) (authz.Instance, error) {
if instanceHost != m.instanceHost {
return nil, fmt.Errorf("invalid host")
}
if publicHost == "" {
return &mockInstance{}, nil
}
if publicHost != instanceHost && publicHost != m.publicHost {
return nil, fmt.Errorf("invalid host")
}
return &mockInstance{}, nil
@@ -333,14 +280,6 @@ func (m *mockInstance) DefaultOrganisationID() string {
return "orgID"
}
func (m *mockInstance) RequestedDomain() string {
return "zitadel.cloud"
}
func (m *mockInstance) RequestedHost() string {
return "zitadel.cloud:443"
}
func (m *mockInstance) SecurityPolicyAllowedOrigins() []string {
return nil
}

View File

@@ -1,53 +1,82 @@
package middleware
import (
"fmt"
"net/http"
"slices"
"github.com/gorilla/mux"
"github.com/muhlemmer/httpforwarded"
"github.com/zitadel/logging"
http_util "github.com/zitadel/zitadel/internal/api/http"
)
func WithOrigin(fallBackToHttps bool) mux.MiddlewareFunc {
func WithOrigin(fallBackToHttps bool, http1Header, http2Header string, instanceHostHeaders, publicDomainHeaders []string) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := composeOrigin(r, fallBackToHttps)
if !http_util.IsOrigin(origin) {
logging.Debugf("extracted origin is not valid: %s", origin)
next.ServeHTTP(w, r)
return
}
next.ServeHTTP(w, r.WithContext(http_util.WithComposedOrigin(r.Context(), origin)))
origin := composeDomainContext(
r,
fallBackToHttps,
// to make sure we don't break existing configurations we append the existing checked headers as well
slices.Compact(append(instanceHostHeaders, http1Header, http2Header, http_util.Forwarded, http_util.ForwardedFor, http_util.ForwardedHost, http_util.ForwardedProto)),
publicDomainHeaders,
)
next.ServeHTTP(w, r.WithContext(http_util.WithDomainContext(r.Context(), origin)))
})
}
}
func composeOrigin(r *http.Request, fallBackToHttps bool) string {
var proto, host string
fwd, fwdErr := httpforwarded.ParseFromRequest(r)
if fwdErr == nil {
proto = oldestForwardedValue(fwd, "proto")
host = oldestForwardedValue(fwd, "host")
func composeDomainContext(r *http.Request, fallBackToHttps bool, instanceDomainHeaders, publicDomainHeaders []string) *http_util.DomainCtx {
instanceHost, instanceProto := hostFromRequest(r, instanceDomainHeaders)
publicHost, publicProto := hostFromRequest(r, publicDomainHeaders)
if publicProto == "" {
publicProto = instanceProto
}
if proto == "" {
proto = r.Header.Get("X-Forwarded-Proto")
}
if host == "" {
host = r.Header.Get("X-Forwarded-Host")
}
if proto == "" {
proto = "http"
if publicProto == "" {
publicProto = "http"
if fallBackToHttps {
proto = "https"
publicProto = "https"
}
}
if host == "" {
host = r.Host
if instanceHost == "" {
instanceHost = r.Host
}
return fmt.Sprintf("%s://%s", proto, host)
return &http_util.DomainCtx{
InstanceHost: instanceHost,
Protocol: publicProto,
PublicHost: publicHost,
}
}
func hostFromRequest(r *http.Request, headers []string) (host, proto string) {
var hostFromHeader, protoFromHeader string
for _, header := range headers {
switch http.CanonicalHeaderKey(header) {
case http.CanonicalHeaderKey(http_util.Forwarded),
http.CanonicalHeaderKey(http_util.ForwardedFor):
hostFromHeader, protoFromHeader = hostFromForwarded(r.Header.Values(header))
case http.CanonicalHeaderKey(http_util.ForwardedHost):
hostFromHeader = r.Header.Get(header)
case http.CanonicalHeaderKey(http_util.ForwardedProto):
protoFromHeader = r.Header.Get(header)
default:
hostFromHeader = r.Header.Get(header)
}
if host == "" {
host = hostFromHeader
}
if proto == "" {
proto = protoFromHeader
}
}
return host, proto
}
func hostFromForwarded(values []string) (string, string) {
fwd, fwdErr := httpforwarded.Parse(values)
if fwdErr == nil {
return oldestForwardedValue(fwd, "host"), oldestForwardedValue(fwd, "proto")
}
return "", ""
}
func oldestForwardedValue(forwarded map[string][]string, key string) string {

View File

@@ -5,6 +5,8 @@ import (
"testing"
"github.com/stretchr/testify/assert"
http_util "github.com/zitadel/zitadel/internal/api/http"
)
func Test_composeOrigin(t *testing.T) {
@@ -15,10 +17,13 @@ func Test_composeOrigin(t *testing.T) {
tests := []struct {
name string
args args
want string
want *http_util.DomainCtx
}{{
name: "no proxy headers",
want: "http://host.header",
want: &http_util.DomainCtx{
InstanceHost: "host.header",
Protocol: "http",
},
}, {
name: "forwarded proto",
args: args{
@@ -27,7 +32,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "https://host.header",
want: &http_util.DomainCtx{
InstanceHost: "host.header",
Protocol: "https",
},
}, {
name: "forwarded host",
args: args{
@@ -36,7 +44,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "http://forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "forwarded.host",
Protocol: "http",
},
}, {
name: "forwarded proto and host",
args: args{
@@ -45,7 +56,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "https://forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "forwarded.host",
Protocol: "https",
},
}, {
name: "forwarded proto and host with multiple complete entries",
args: args{
@@ -54,7 +68,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "https://forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "forwarded.host",
Protocol: "https",
},
}, {
name: "forwarded proto and host with multiple incomplete entries",
args: args{
@@ -63,7 +80,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "https://forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "forwarded.host",
Protocol: "https",
},
}, {
name: "forwarded proto and host with incomplete entries in different values",
args: args{
@@ -72,7 +92,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: true,
},
want: "http://forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "forwarded.host",
Protocol: "http",
},
}, {
name: "x-forwarded-proto https",
args: args{
@@ -81,7 +104,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "https://host.header",
want: &http_util.DomainCtx{
InstanceHost: "host.header",
Protocol: "https",
},
}, {
name: "x-forwarded-proto http",
args: args{
@@ -90,19 +116,28 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: true,
},
want: "http://host.header",
want: &http_util.DomainCtx{
InstanceHost: "host.header",
Protocol: "http",
},
}, {
name: "fallback to http",
args: args{
fallBackToHttps: false,
},
want: "http://host.header",
want: &http_util.DomainCtx{
InstanceHost: "host.header",
Protocol: "http",
},
}, {
name: "fallback to https",
args: args{
fallBackToHttps: true,
},
want: "https://host.header",
want: &http_util.DomainCtx{
InstanceHost: "host.header",
Protocol: "https",
},
}, {
name: "x-forwarded-host",
args: args{
@@ -111,7 +146,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "http://x-forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "x-forwarded.host",
Protocol: "http",
},
}, {
name: "x-forwarded-proto and x-forwarded-host",
args: args{
@@ -121,7 +159,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "https://x-forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "x-forwarded.host",
Protocol: "https",
},
}, {
name: "forwarded host and x-forwarded-host",
args: args{
@@ -131,7 +172,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "http://forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "forwarded.host",
Protocol: "http",
},
}, {
name: "forwarded host and x-forwarded-proto",
args: args{
@@ -141,17 +185,22 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "https://forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "forwarded.host",
Protocol: "https",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equalf(t, tt.want, composeOrigin(
assert.Equalf(t, tt.want, composeDomainContext(
&http.Request{
Host: "host.header",
Header: tt.args.h,
},
tt.args.fallBackToHttps,
[]string{http_util.Forwarded, http_util.ForwardedFor, http_util.ForwardedHost, http_util.ForwardedProto},
[]string{"x-zitadel-public-host"},
), "headers: %+v, fallBackToHttps: %t", tt.args.h, tt.args.fallBackToHttps)
})
}

View File

@@ -0,0 +1,60 @@
package http
import (
"context"
"fmt"
"strings"
)
type DomainCtx struct {
InstanceHost string
PublicHost string
Protocol string
}
// RequestedHost returns the host (hostname[:port]) for which the request was handled.
// The instance host is returned if not public host was set.
func (r *DomainCtx) RequestedHost() string {
if r.PublicHost != "" {
return r.PublicHost
}
return r.InstanceHost
}
// RequestedDomain returns the domain (hostname) for which the request was handled.
// The instance domain is returned if not public host / domain was set.
func (r *DomainCtx) RequestedDomain() string {
return strings.Split(r.RequestedHost(), ":")[0]
}
// Origin returns the origin (protocol://hostname[:port]) for which the request was handled.
// The instance host is used if not public host was set.
func (r *DomainCtx) Origin() string {
host := r.PublicHost
if host == "" {
host = r.InstanceHost
}
return fmt.Sprintf("%s://%s", r.Protocol, host)
}
func DomainContext(ctx context.Context) *DomainCtx {
o, ok := ctx.Value(domainCtx).(*DomainCtx)
if !ok {
return &DomainCtx{}
}
return o
}
func WithDomainContext(ctx context.Context, domainContext *DomainCtx) context.Context {
return context.WithValue(ctx, domainCtx, domainContext)
}
func WithRequestedHost(ctx context.Context, host string) context.Context {
i, ok := ctx.Value(domainCtx).(*DomainCtx)
if !ok {
i = new(DomainCtx)
}
i.PublicHost = host
return context.WithValue(ctx, domainCtx, i)
}

View File

@@ -13,7 +13,6 @@ import (
"github.com/gorilla/mux"
"github.com/zitadel/logging"
"github.com/zitadel/zitadel/internal/api/authz"
http_utils "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/api/ui/login"
"github.com/zitadel/zitadel/internal/command"
@@ -79,21 +78,21 @@ type externalSAMLIDPCallbackData struct {
}
// CallbackURL generates the instance specific URL to the IDP callback handler
func CallbackURL(externalSecure bool) func(ctx context.Context) string {
func CallbackURL() func(ctx context.Context) string {
return func(ctx context.Context) string {
return http_utils.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), externalSecure) + HandlerPrefix + callbackPath
return http_utils.DomainContext(ctx).Origin() + HandlerPrefix + callbackPath
}
}
func SAMLRootURL(externalSecure bool) func(ctx context.Context, idpID string) string {
func SAMLRootURL() func(ctx context.Context, idpID string) string {
return func(ctx context.Context, idpID string) string {
return http_utils.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), externalSecure) + HandlerPrefix + "/" + idpID + "/"
return http_utils.DomainContext(ctx).Origin() + HandlerPrefix + "/" + idpID + "/"
}
}
func LoginSAMLRootURL(externalSecure bool) func(ctx context.Context) string {
func LoginSAMLRootURL() func(ctx context.Context) string {
return func(ctx context.Context) string {
return http_utils.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), externalSecure) + login.HandlerPrefix + login.EndpointSAMLACS
return http_utils.DomainContext(ctx).Origin() + login.HandlerPrefix + login.EndpointSAMLACS
}
}
@@ -101,7 +100,6 @@ func NewHandler(
commands *command.Commands,
queries *query.Queries,
encryptionAlgorithm crypto.EncryptionAlgorithm,
externalSecure bool,
instanceInterceptor func(next http.Handler) http.Handler,
) http.Handler {
h := &Handler{
@@ -109,9 +107,9 @@ func NewHandler(
queries: queries,
parser: form.NewParser(),
encryptionAlgorithm: encryptionAlgorithm,
callbackURL: CallbackURL(externalSecure),
samlRootURL: SAMLRootURL(externalSecure),
loginSAMLRootURL: LoginSAMLRootURL(externalSecure),
callbackURL: CallbackURL(),
samlRootURL: SAMLRootURL(),
loginSAMLRootURL: LoginSAMLRootURL(),
}
router := mux.NewRouter()

View File

@@ -100,7 +100,7 @@ func NewServer(
if err != nil {
return nil, zerrors.ThrowInternal(err, "OIDC-EGrqd", "cannot create op config: %w")
}
storage := newStorage(config, command, query, repo, encryptionAlg, es, projections, externalSecure)
storage := newStorage(config, command, query, repo, encryptionAlg, es, projections)
keyCache := newPublicKeyCache(ctx, config.PublicKeyCacheMaxAge, query.GetPublicKeyByID)
accessTokenKeySet := newOidcKeySet(keyCache, withKeyExpiryCheck(true))
idTokenHintKeySet := newOidcKeySet(keyCache)
@@ -115,7 +115,7 @@ func NewServer(
provider, err := op.NewProvider(
opConfig,
storage,
op.IssuerFromForwardedOrHost("", op.WithIssuerFromCustomHeaders("forwarded", "x-zitadel-forwarded")),
IssuerFromContext,
options...,
)
if err != nil {
@@ -142,7 +142,7 @@ func NewServer(
signingKeyAlgorithm: config.SigningKeyAlgorithm,
encAlg: encryptionAlg,
opCrypto: op.NewAESCrypto(opConfig.CryptoKey),
assetAPIPrefix: assets.AssetAPI(externalSecure),
assetAPIPrefix: assets.AssetAPI(),
}
metricTypes := []metrics.MetricType{metrics.MetricTypeRequestCount, metrics.MetricTypeStatusCode, metrics.MetricTypeTotalCount}
server.Handler = op.RegisterLegacyServer(server,
@@ -162,6 +162,12 @@ func NewServer(
return server, nil
}
func IssuerFromContext(_ bool) (op.IssuerFromRequest, error) {
return func(r *http.Request) string {
return http_utils.DomainContext(r.Context()).Origin()
}, nil
}
func publicAuthPathPrefixes(endpoints *EndpointConfig) []string {
authURL := op.DefaultEndpoints.Authorization.Relative()
keysURL := op.DefaultEndpoints.JwksURI.Relative()
@@ -194,7 +200,7 @@ func createOPConfig(config Config, defaultLogoutRedirectURI string, cryptoKey []
return opConfig, nil
}
func newStorage(config Config, command *command.Commands, query *query.Queries, repo repository.Repository, encAlg crypto.EncryptionAlgorithm, es *eventstore.Eventstore, db *database.DB, externalSecure bool) *OPStorage {
func newStorage(config Config, command *command.Commands, query *query.Queries, repo repository.Repository, encAlg crypto.EncryptionAlgorithm, es *eventstore.Eventstore, db *database.DB) *OPStorage {
return &OPStorage{
repo: repo,
command: command,
@@ -210,7 +216,7 @@ func newStorage(config Config, command *command.Commands, query *query.Queries,
defaultRefreshTokenExpiration: config.DefaultRefreshTokenExpiration,
encAlg: encAlg,
locker: crdb.NewLocker(db.DB, locksTable, signingKey),
assetAPIPrefix: assets.AssetAPI(externalSecure),
assetAPIPrefix: assets.AssetAPI(),
}
}

View File

@@ -21,6 +21,7 @@ import (
"github.com/zitadel/zitadel/internal/api/authz"
http_util "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/api/http/middleware"
console_path "github.com/zitadel/zitadel/internal/api/ui/console/path"
)
type Config struct {
@@ -40,7 +41,6 @@ var (
const (
envRequestPath = "/assets/environment.json"
HandlerPrefix = "/ui/console"
)
var (
@@ -56,7 +56,7 @@ var (
)
func LoginHintLink(origin, username string) string {
return origin + HandlerPrefix + "?login_hint=" + username
return origin + console_path.HandlerPrefix + "?login_hint=" + username
}
func (i *spaHandler) Open(name string) (http.File, error) {

View File

@@ -0,0 +1,7 @@
package path
const (
HandlerPrefix = "/ui/console"
RedirectPath = HandlerPrefix + "/auth/callback"
PostLogoutPath = HandlerPrefix + "/signedout"
)

View File

@@ -1042,7 +1042,7 @@ func (l *Login) samlProvider(ctx context.Context, identityProvider *query.IDPTem
opts = append(opts, saml.WithTransientMappingAttributeName(identityProvider.SAMLIDPTemplate.TransientMappingAttributeName))
}
opts = append(opts,
saml.WithEntityID(http_utils.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), l.externalSecure)+"/idps/"+identityProvider.ID+"/saml/metadata"),
saml.WithEntityID(http_utils.DomainContext(ctx).Origin()+"/idps/"+identityProvider.ID+"/saml/metadata"),
saml.WithCustomRequestTracker(
requesttracker.New(
func(ctx context.Context, authRequestID, samlRequestID string) error {

View File

@@ -129,7 +129,7 @@ func createCSRFInterceptor(cookieName string, csrfCookieKey []byte, externalSecu
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 || instance.RequestedDomain() == "localhost"
secureOnly = externalSecure || http_utils.DomainContext(r.Context()).RequestedDomain() == "localhost"
}
csrf.Protect(csrfCookieKey,
csrf.Secure(secureOnly),
@@ -163,7 +163,7 @@ func (l *Login) Handler() http.Handler {
}
func (l *Login) getClaimedUserIDsOfOrgDomain(ctx context.Context, orgName string) ([]string, error) {
orgDomain, err := domain.NewIAMDomainName(orgName, authz.GetInstance(ctx).RequestedDomain())
orgDomain, err := domain.NewIAMDomainName(orgName, http_utils.DomainContext(ctx).RequestedDomain())
if err != nil {
return nil, err
}
@@ -199,5 +199,5 @@ func setUserContext(ctx context.Context, userID, resourceOwner string) context.C
}
func (l *Login) baseURL(ctx context.Context) string {
return http_utils.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), l.externalSecure) + HandlerPrefix
return http_utils.DomainContext(ctx).Origin() + HandlerPrefix
}

View File

@@ -3,7 +3,7 @@ package login
import (
"net/http"
"github.com/zitadel/zitadel/internal/api/authz"
http_util "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/zerrors"
@@ -128,7 +128,7 @@ func (l *Login) renderRegisterOrg(w http.ResponseWriter, r *http.Request, authRe
orgPolicy, _ := l.getDefaultDomainPolicy(r)
if orgPolicy != nil {
data.UserLoginMustBeDomain = orgPolicy.UserLoginMustBeDomain
data.IamDomain = authz.GetInstance(r.Context()).RequestedDomain()
data.IamDomain = http_util.DomainContext(r.Context()).RequestedDomain()
}
if authRequest == nil {