package httpadapter import ( "fmt" "log/slog" "net/http" "net/netip" "github.com/go-chi/chi/v5" kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware" apiadapter "lincodex/backend/internal/adapter/primary/http/api" httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware" "lincodex/backend/internal/adapter/primary/http/problem" v1 "lincodex/backend/internal/adapter/primary/http/v1" ) const ( healthPath = "/healthz" readinessPath = "/readyz" apiRoot = "/api" publicPrefix = apiRoot + "/v1" ) // NewRouter mounts the internal operational routes and the generated public API. // Every error under /api/v1 is an RFC 9457 problem response: problems maps // ht.ErrNotImplemented to 501, request decoding and validation errors to 400, // unknown routes under /api to 404, unsupported methods to 405, and any other // server error or panic to 500 without exposing its text. Operation errors go // through apiHandler.NewError. security decides every operation that requires // a session; trustedProxies are the reverse proxies whose X-Forwarded-For // is believed; the generated server answers its rejection, and a request // without the session cookie, with 401 unauthenticated through NewError. func NewRouter( health *v1.HealthHandler, apiHandler apiadapter.Handler, security apiadapter.SecurityHandler, problems *problem.Responder, collector httpmiddleware.RequestMetrics, logger *slog.Logger, trustedProxies []netip.Prefix, ) (http.Handler, error) { apiServer, err := apiadapter.NewServer( apiHandler, security, apiadapter.WithErrorHandler(problems.HandleServerError), apiadapter.WithNotFound(problems.NotFound), apiadapter.WithMethodNotAllowed(problems.MethodNotAllowed), ) if err != nil { return nil, fmt.Errorf("httpadapter.NewRouter - create API server: %w", err) } router := chi.NewRouter() // Request ID, request logging, and metrics wrap every route, so both // recovery middlewares below run inside them: a recovered panic carries the // request ID and its 500 is logged and counted. The request log names the // same route template as the metrics, never the raw path or query. resolveRoute := operationRoute(apiServer) router.Use(kitmiddleware.RequestID()) // The client address is resolved once, through the trusted proxies only, // for the per-client rate limits of the handlers. router.Use(httpmiddleware.ClientIP(trustedProxies)) // Unsafe public identity operations and session CSRF checks compare one // Origin header value exactly with the configured public origin. Session // metadata never trusts forwarded headers. router.Use(httpmiddleware.SessionRequestMetadata()) router.Use(httpmiddleware.RequestLog(logger, resolveRoute, healthPath, readinessPath)) router.Use(httpmiddleware.CollectMetrics(collector, resolveRoute)) router.Group(func(operational chi.Router) { operational.Use(kitmiddleware.Recoverer(logger)) operational.Get(healthPath, health.Healthz) operational.Get(readinessPath, health.Readyz) }) // The public API uses only problems.Recover, which answers panics with the // contract's internal problem and re-raises http.ErrAbortHandler so the // server aborts the response; the kit Recoverer would swallow that panic. router.Group(func(public chi.Router) { public.Use(problems.Recover) public.Handle(apiWildcard, clearUnauthorizedLogoutCookie(apiServer)) // Unknown /api paths outside the versioned prefix are also problems, // so every error under /api has the contract's format. public.Handle(apiRoot, http.HandlerFunc(problems.NotFound)) public.Handle(apiRoot+"/*", http.HandlerFunc(problems.NotFound)) }) return router, nil } func clearUnauthorizedLogoutCookie(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { clearCookie := r.Method == http.MethodDelete && r.URL.Path == publicPrefix+"/identity/sessions/current" next.ServeHTTP(&logoutCookieWriter{ResponseWriter: w, clearCookie: clearCookie}, r) }) } type logoutCookieWriter struct { http.ResponseWriter clearCookie bool } func (writer *logoutCookieWriter) WriteHeader(status int) { if writer.clearCookie && status == http.StatusUnauthorized { writer.Header().Add("Set-Cookie", v1.ExpiredSessionCookie()) } writer.ResponseWriter.WriteHeader(status) } func (writer *logoutCookieWriter) Unwrap() http.ResponseWriter { return writer.ResponseWriter } // apiWildcard is the chi pattern that mounts the generated server. const apiWildcard = publicPrefix + "/*" // operationRoute names a request under the versioned prefix by the OpenAPI // path template of its operation, such as /api/v1/me/invitations/{invitation_id}, // so the metrics tell operations apart without a path parameter in a label. // A path or method that matches no operation keeps the wildcard pattern. func operationRoute(server *apiadapter.Server) httpmiddleware.RouteResolver { return func(r *http.Request, pattern string) string { if pattern != apiWildcard { return pattern } operation, ok := server.FindPath(r.Method, r.URL) if !ok { return pattern } return operation.PathPattern() } }