Files
Atay-Makhzan/routers/common/middleware.go
T

142 lines
5.1 KiB
Go
Raw Normal View History

2021-06-09 07:33:54 +08:00
// Copyright 2021 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
2021-06-09 07:33:54 +08:00
package common
import (
"fmt"
"net/http"
"strings"
"code.gitea.io/gitea/modules/cache"
2025-01-22 02:57:07 +08:00
"code.gitea.io/gitea/modules/gtprof"
2024-05-07 16:26:13 +08:00
"code.gitea.io/gitea/modules/httplib"
2026-03-08 17:59:46 +08:00
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/public"
2024-12-24 11:43:57 +08:00
"code.gitea.io/gitea/modules/reqctx"
2021-06-09 07:33:54 +08:00
"code.gitea.io/gitea/modules/setting"
2022-01-20 19:41:25 +08:00
"code.gitea.io/gitea/modules/web/routing"
"code.gitea.io/gitea/services/context"
2021-06-09 07:33:54 +08:00
"gitea.com/go-chi/session"
2021-06-09 07:33:54 +08:00
"github.com/chi-middleware/proxy"
2024-06-18 07:28:47 +08:00
"github.com/go-chi/chi/v5"
2021-06-09 07:33:54 +08:00
)
// ProtocolMiddlewares returns HTTP protocol related middlewares, and it provides a global panic recovery
func ProtocolMiddlewares() (handlers []any) {
2024-12-24 11:43:57 +08:00
// the order is important
handlers = append(handlers, ChiRoutePathHandler()) // make sure chi has correct paths
2024-12-25 00:51:13 +08:00
handlers = append(handlers, RequestContextHandler()) // prepare the context and panic recovery
2024-12-24 11:43:57 +08:00
if setting.ReverseProxyLimit > 0 && len(setting.ReverseProxyTrustedProxies) > 0 {
handlers = append(handlers, ForwardedHeadersHandler(setting.ReverseProxyLimit, setting.ReverseProxyTrustedProxies))
}
if setting.IsRouteLogEnabled() {
handlers = append(handlers, routing.NewLoggerHandler())
}
if setting.IsAccessLogEnabled() {
handlers = append(handlers, context.AccessLogger())
}
if !setting.IsProd {
handlers = append(handlers, public.ViteDevMiddleware)
}
2024-12-24 11:43:57 +08:00
return handlers
}
func RequestContextHandler() func(h http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(respOrig http.ResponseWriter, req *http.Request) {
// this response writer might not be the same as the one in context.Base.Resp
// because there might be a "gzip writer" in the middle, so the "written size" here is the compressed size
respWriter := context.WrapResponseWriter(respOrig)
profDesc := fmt.Sprintf("HTTP: %s %s", req.Method, req.RequestURI)
2024-12-24 11:43:57 +08:00
ctx, finished := reqctx.NewRequestContext(req.Context(), profDesc)
defer finished()
2025-01-22 02:57:07 +08:00
ctx, span := gtprof.GetTracer().Start(ctx, gtprof.TraceSpanHTTP)
req = req.WithContext(ctx)
defer func() {
chiCtx := chi.RouteContext(req.Context())
span.SetAttributeString(gtprof.TraceAttrHTTPRoute, chiCtx.RoutePattern())
span.End()
}()
defer func() {
2026-03-08 17:59:46 +08:00
if recovered := recover(); recovered != nil {
renderPanicErrorPage(respWriter, req, recovered) // it should never panic, and it handles the stack trace internally
}
}()
2024-12-24 11:43:57 +08:00
ds := reqctx.GetRequestDataStore(ctx)
req = req.WithContext(cache.WithCacheContext(ctx))
ds.SetContextValue(httplib.RequestContextKey, req)
ds.AddCleanUp(func() {
// TODO: GOLANG-HTTP-TMPDIR: Golang saves the uploaded files to temp directory (TMPDIR) when parsing multipart-form.
// The "req" might have changed due to the new "req.WithContext" calls
// For example: in NewBaseContext, a new "req" with context is created, and the multipart-form is parsed there.
// So we always use the latest "req" from the data store.
ctxReq := ds.GetContextValue(httplib.RequestContextKey).(*http.Request)
if ctxReq.MultipartForm != nil {
_ = ctxReq.MultipartForm.RemoveAll() // remove the temp files buffered to tmp directory
2024-12-24 11:43:57 +08:00
}
})
next.ServeHTTP(respWriter, req)
})
2024-12-24 11:43:57 +08:00
}
}
2021-06-09 07:33:54 +08:00
2024-12-24 11:43:57 +08:00
func ChiRoutePathHandler() func(h http.Handler) http.Handler {
// make sure chi uses EscapedPath(RawPath) as RoutePath, then "%2f" could be handled correctly
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
2025-01-22 02:57:07 +08:00
chiCtx := chi.RouteContext(req.Context())
2024-12-24 11:43:57 +08:00
if req.URL.RawPath == "" {
2025-01-22 02:57:07 +08:00
chiCtx.RoutePath = req.URL.EscapedPath()
2021-06-09 07:33:54 +08:00
} else {
2025-01-22 02:57:07 +08:00
chiCtx.RoutePath = req.URL.RawPath
2021-06-09 07:33:54 +08:00
}
2024-12-24 11:43:57 +08:00
next.ServeHTTP(resp, req)
})
2021-06-09 07:33:54 +08:00
}
2024-12-24 11:43:57 +08:00
}
2022-01-20 19:41:25 +08:00
2024-12-24 11:43:57 +08:00
func ForwardedHeadersHandler(limit int, trustedProxies []string) func(h http.Handler) http.Handler {
opt := proxy.NewForwardedHeadersOptions().WithForwardLimit(limit).ClearTrustedProxies()
for _, n := range trustedProxies {
if !strings.Contains(n, "/") {
opt.AddTrustedProxy(n)
} else {
opt.AddTrustedNetwork(n)
}
2021-06-09 07:33:54 +08:00
}
2024-12-24 11:43:57 +08:00
return proxy.ForwardedHeaders(opt)
2021-06-09 07:33:54 +08:00
}
2025-11-26 23:25:34 +08:00
func MustInitSessioner() func(next http.Handler) http.Handler {
// TODO: CHI-SESSION-GOB-REGISTER: chi-session has a design problem: it calls gob.Register for "Set"
// But if the server restarts, then the first "Get" will fail to decode the previously stored session data because the structs are not registered yet.
// So each package should make sure their structs are registered correctly during startup for session storage.
middleware, err := session.Sessioner(session.Options{
Provider: setting.SessionConfig.Provider,
ProviderConfig: setting.SessionConfig.ProviderConfig,
CookieName: setting.SessionConfig.CookieName,
CookiePath: setting.SessionConfig.CookiePath,
Gclifetime: setting.SessionConfig.Gclifetime,
Maxlifetime: setting.SessionConfig.Maxlifetime,
Secure: setting.SessionConfig.Secure,
SameSite: setting.SessionConfig.SameSite,
Domain: setting.SessionConfig.Domain,
})
if err != nil {
2026-03-08 17:59:46 +08:00
log.Fatal("common.Sessioner failed: %v", err)
}
2025-11-26 23:25:34 +08:00
return middleware
}