mirror of
https://github.com/zitadel/zitadel.git
synced 2025-08-11 19:07:30 +00:00
feat: run on a single port (#3163)
* start v2 * start * run * some cleanup * remove v2 pkg again * simplify * webauthn * remove unused config * fix login path in Dockerfile * fix asset_generator.go * health handler * fix grpc web * refactor * merge * build new main.go * run new main.go * update logging pkg * fix error msg * update logging * cleanup * cleanup * go mod tidy * change localDevMode * fix customEndpoints * update logging * comments * change local flag to external configs * fix location generated go code * fix Co-authored-by: fforootd <florian@caos.ch>
This commit is contained in:
@@ -3,100 +3,101 @@ package api
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/caos/logging"
|
||||
sentryhttp "github.com/getsentry/sentry-go/http"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/improbable-eng/grpc-web/go/grpcweb"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
admin_es "github.com/caos/zitadel/internal/admin/repository/eventsourcing"
|
||||
"github.com/caos/zitadel/internal/api/authz"
|
||||
grpc_util "github.com/caos/zitadel/internal/api/grpc"
|
||||
internal_authz "github.com/caos/zitadel/internal/api/authz"
|
||||
"github.com/caos/zitadel/internal/api/grpc/server"
|
||||
http_util "github.com/caos/zitadel/internal/api/http"
|
||||
"github.com/caos/zitadel/internal/api/oidc"
|
||||
auth_es "github.com/caos/zitadel/internal/auth/repository/eventsourcing"
|
||||
authz_repo "github.com/caos/zitadel/internal/authz/repository"
|
||||
"github.com/caos/zitadel/internal/authz/repository"
|
||||
"github.com/caos/zitadel/internal/config/systemdefaults"
|
||||
"github.com/caos/zitadel/internal/domain"
|
||||
"github.com/caos/zitadel/internal/errors"
|
||||
"github.com/caos/zitadel/internal/query"
|
||||
"github.com/caos/zitadel/internal/telemetry/metrics"
|
||||
"github.com/caos/zitadel/internal/telemetry/metrics/otel"
|
||||
"github.com/caos/zitadel/internal/telemetry/tracing"
|
||||
view_model "github.com/caos/zitadel/internal/view/model"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
GRPC grpc_util.Config
|
||||
OIDC oidc.OPHandlerConfig
|
||||
Domain string
|
||||
}
|
||||
|
||||
type API struct {
|
||||
port uint16
|
||||
grpcServer *grpc.Server
|
||||
gatewayHandler *server.GatewayHandler
|
||||
verifier *authz.TokenVerifier
|
||||
serverPort string
|
||||
verifier *internal_authz.TokenVerifier
|
||||
health health
|
||||
auth auth
|
||||
admin admin
|
||||
router *mux.Router
|
||||
externalSecure bool
|
||||
}
|
||||
|
||||
type health interface {
|
||||
Health(ctx context.Context) error
|
||||
IAMByID(ctx context.Context, id string) (*query.IAM, error)
|
||||
VerifierClientID(ctx context.Context, appName string) (string, string, error)
|
||||
}
|
||||
|
||||
type auth interface {
|
||||
ActiveUserSessionCount() int64
|
||||
}
|
||||
|
||||
type admin interface {
|
||||
GetViews() ([]*view_model.View, error)
|
||||
GetSpoolerDiv(database, viewName string) int64
|
||||
}
|
||||
|
||||
func Create(config Config, authZ authz.Config, q *query.Queries, authZRepo authz_repo.Repository, authRepo *auth_es.EsRepository, adminRepo *admin_es.EsRepository, sd systemdefaults.SystemDefaults) *API {
|
||||
func New(
|
||||
port uint16,
|
||||
router *mux.Router,
|
||||
repo *struct {
|
||||
repository.Repository
|
||||
*query.Queries
|
||||
},
|
||||
authZ internal_authz.Config,
|
||||
sd systemdefaults.SystemDefaults,
|
||||
externalSecure bool,
|
||||
) *API {
|
||||
verifier := internal_authz.Start(repo)
|
||||
api := &API{
|
||||
serverPort: config.GRPC.ServerPort,
|
||||
port: port,
|
||||
verifier: verifier,
|
||||
health: repo,
|
||||
router: router,
|
||||
externalSecure: externalSecure,
|
||||
}
|
||||
|
||||
repo := struct {
|
||||
authz_repo.Repository
|
||||
query.Queries
|
||||
}{
|
||||
authZRepo,
|
||||
*q,
|
||||
}
|
||||
|
||||
api.verifier = authz.Start(&repo)
|
||||
api.health = &repo
|
||||
api.auth = authRepo
|
||||
api.admin = adminRepo
|
||||
api.grpcServer = server.CreateServer(api.verifier, authZ, sd.DefaultLanguage)
|
||||
api.gatewayHandler = server.CreateGatewayHandler(config.GRPC)
|
||||
api.RegisterHandler("", api.healthHandler())
|
||||
api.routeGRPC()
|
||||
|
||||
api.RegisterHandler("/debug", api.healthHandler())
|
||||
|
||||
return api
|
||||
}
|
||||
|
||||
func (a *API) RegisterServer(ctx context.Context, server server.Server) {
|
||||
server.RegisterServer(a.grpcServer)
|
||||
a.gatewayHandler.RegisterGateway(ctx, server)
|
||||
a.verifier.RegisterServer(server.AppName(), server.MethodPrefix(), server.AuthMethods())
|
||||
func (a *API) RegisterServer(ctx context.Context, grpcServer server.Server) error {
|
||||
grpcServer.RegisterServer(a.grpcServer)
|
||||
handler, prefix, err := server.CreateGateway(ctx, grpcServer, a.port)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.RegisterHandler(prefix, handler)
|
||||
a.verifier.RegisterServer(grpcServer.AppName(), grpcServer.MethodPrefix(), grpcServer.AuthMethods())
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *API) RegisterHandler(prefix string, handler http.Handler) {
|
||||
prefix = strings.TrimSuffix(prefix, "/")
|
||||
sentryHandler := sentryhttp.New(sentryhttp.Options{})
|
||||
a.gatewayHandler.RegisterHandler(prefix, sentryHandler.Handle(handler))
|
||||
subRouter := a.router.PathPrefix(prefix).Subrouter()
|
||||
subRouter.PathPrefix("/").Handler(http.StripPrefix(prefix, sentryHandler.Handle(handler)))
|
||||
}
|
||||
|
||||
func (a *API) Start(ctx context.Context) {
|
||||
server.Serve(ctx, a.grpcServer, a.serverPort)
|
||||
a.gatewayHandler.Serve(ctx)
|
||||
func (a *API) routeGRPC() {
|
||||
http2Route := a.router.Methods(http.MethodPost).
|
||||
MatcherFunc(func(r *http.Request, _ *mux.RouteMatch) bool {
|
||||
return r.ProtoMajor == 2
|
||||
}).
|
||||
Subrouter()
|
||||
http2Route.Headers("Content-Type", "application/grpc").Handler(a.grpcServer)
|
||||
|
||||
if !a.externalSecure {
|
||||
a.routeGRPCWeb(a.router)
|
||||
return
|
||||
}
|
||||
a.routeGRPCWeb(http2Route)
|
||||
}
|
||||
|
||||
func (a *API) routeGRPCWeb(router *mux.Router) {
|
||||
router.NewRoute().HeadersRegexp("Content-Type", "application/grpc-web.*").Handler(grpcweb.WrapServer(a.grpcServer))
|
||||
}
|
||||
|
||||
func (a *API) healthHandler() http.Handler {
|
||||
@@ -125,99 +126,46 @@ func (a *API) healthHandler() http.Handler {
|
||||
handler.HandleFunc("/healthz", handleHealth)
|
||||
handler.HandleFunc("/ready", handleReadiness(checks))
|
||||
handler.HandleFunc("/validate", handleValidate(checks))
|
||||
handler.HandleFunc("/clientID", a.handleClientID)
|
||||
handler.Handle("/metrics", a.handleMetrics())
|
||||
|
||||
return handler
|
||||
}
|
||||
|
||||
func handleHealth(w http.ResponseWriter, r *http.Request) {
|
||||
_, err := w.Write([]byte("ok"))
|
||||
logging.Log("API-Hfss2").OnError(err).WithField("traceID", tracing.TraceIDFromCtx(r.Context())).Error("error writing ok for health")
|
||||
logging.WithFields("traceID", tracing.TraceIDFromCtx(r.Context())).OnError(err).Error("error writing ok for health")
|
||||
}
|
||||
|
||||
func handleReadiness(checks []ValidationFunction) func(w http.ResponseWriter, r *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
errors := validate(r.Context(), checks)
|
||||
if len(errors) == 0 {
|
||||
errs := validate(r.Context(), checks)
|
||||
if len(errs) == 0 {
|
||||
http_util.MarshalJSON(w, "ok", nil, http.StatusOK)
|
||||
return
|
||||
}
|
||||
http_util.MarshalJSON(w, nil, errors[0], http.StatusPreconditionFailed)
|
||||
http_util.MarshalJSON(w, nil, errs[0], http.StatusPreconditionFailed)
|
||||
}
|
||||
}
|
||||
|
||||
func handleValidate(checks []ValidationFunction) func(w http.ResponseWriter, r *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
errors := validate(r.Context(), checks)
|
||||
if len(errors) == 0 {
|
||||
errs := validate(r.Context(), checks)
|
||||
if len(errs) == 0 {
|
||||
http_util.MarshalJSON(w, "ok", nil, http.StatusOK)
|
||||
return
|
||||
}
|
||||
http_util.MarshalJSON(w, errors, nil, http.StatusOK)
|
||||
http_util.MarshalJSON(w, errs, nil, http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *API) handleClientID(w http.ResponseWriter, r *http.Request) {
|
||||
id, _, err := a.health.VerifierClientID(r.Context(), "Zitadel Console")
|
||||
if err != nil {
|
||||
http_util.MarshalJSON(w, nil, err, http.StatusPreconditionFailed)
|
||||
return
|
||||
}
|
||||
http_util.MarshalJSON(w, id, nil, http.StatusOK)
|
||||
}
|
||||
|
||||
func (a *API) handleMetrics() http.Handler {
|
||||
a.registerActiveSessionCounters()
|
||||
a.registerSpoolerDivCounters()
|
||||
return metrics.GetExporter()
|
||||
}
|
||||
|
||||
func (a *API) registerActiveSessionCounters() {
|
||||
metrics.RegisterValueObserver(
|
||||
metrics.ActiveSessionCounter,
|
||||
metrics.ActiveSessionCounterDescription,
|
||||
func(ctx context.Context, result metric.Int64ObserverResult) {
|
||||
result.Observe(
|
||||
a.auth.ActiveUserSessionCount(),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func (a *API) registerSpoolerDivCounters() {
|
||||
views, err := a.admin.GetViews()
|
||||
if err != nil {
|
||||
logging.Log("API-3M8sd").WithError(err).Error("could not read views for metrics")
|
||||
return
|
||||
}
|
||||
metrics.RegisterValueObserver(
|
||||
metrics.SpoolerDivCounter,
|
||||
metrics.SpoolerDivCounterDescription,
|
||||
func(ctx context.Context, result metric.Int64ObserverResult) {
|
||||
for _, view := range views {
|
||||
labels := map[string]attribute.Value{
|
||||
metrics.Database: attribute.StringValue(view.Database),
|
||||
metrics.ViewName: attribute.StringValue(view.ViewName),
|
||||
}
|
||||
result.Observe(
|
||||
a.admin.GetSpoolerDiv(view.Database, view.ViewName),
|
||||
otel.MapToKeyValue(labels)...,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
type ValidationFunction func(ctx context.Context) error
|
||||
|
||||
func validate(ctx context.Context, validations []ValidationFunction) []error {
|
||||
errors := make([]error, 0)
|
||||
errs := make([]error, 0)
|
||||
for _, validation := range validations {
|
||||
if err := validation(ctx); err != nil {
|
||||
logging.Log("API-vf823").WithError(err).WithField("traceID", tracing.TraceIDFromCtx(ctx)).Error("validation failed")
|
||||
errors = append(errors, err)
|
||||
logging.WithFields("traceID", tracing.TraceIDFromCtx(ctx)).WithError(err).Error("validation failed")
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
return errors
|
||||
return errs
|
||||
}
|
||||
|
Reference in New Issue
Block a user