Skip to content

Commit 516ff5b

Browse files
committed
fix
1 parent 42718d3 commit 516ff5b

File tree

4 files changed

+100
-127
lines changed

4 files changed

+100
-127
lines changed

modules/web/route.go

+57-1
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@ package web
55

66
import (
77
"net/http"
8+
"net/url"
89
"strings"
910

11+
"code.gitea.io/gitea/modules/setting"
1012
"code.gitea.io/gitea/modules/web/middleware"
1113

1214
"gitea.com/go-chi/binding"
@@ -160,14 +162,68 @@ func (r *Route) Patch(pattern string, h ...any) {
160162

161163
// ServeHTTP implements http.Handler
162164
func (r *Route) ServeHTTP(w http.ResponseWriter, req *http.Request) {
163-
r.R.ServeHTTP(w, req)
165+
r.normalizeRequestPath(w, req, r.R)
164166
}
165167

166168
// NotFound defines a handler to respond whenever a route could not be found.
167169
func (r *Route) NotFound(h http.HandlerFunc) {
168170
r.R.NotFound(h)
169171
}
170172

173+
func (r *Route) normalizeRequestPath(resp http.ResponseWriter, req *http.Request, next http.Handler) {
174+
normalized := false
175+
normalizedPath := req.URL.EscapedPath()
176+
if normalizedPath == "" {
177+
normalizedPath, normalized = "/", true
178+
} else if normalizedPath != "/" {
179+
normalized = strings.HasSuffix(normalizedPath, "/")
180+
normalizedPath = strings.TrimRight(normalizedPath, "/")
181+
}
182+
removeRepeatedSlashes := strings.Contains(normalizedPath, "//")
183+
normalized = normalized || removeRepeatedSlashes
184+
185+
// the following code block is a slow-path for replacing all repeated slashes "//" to one single "/"
186+
// if the path doesn't have repeated slashes, then no need to execute it
187+
if removeRepeatedSlashes {
188+
buf := &strings.Builder{}
189+
for i := 0; i < len(normalizedPath); i++ {
190+
if i == 0 || normalizedPath[i-1] != '/' || normalizedPath[i] != '/' {
191+
buf.WriteByte(normalizedPath[i])
192+
}
193+
}
194+
normalizedPath = buf.String()
195+
}
196+
197+
// if the config tells Gitea to use a sub-url path directly without reverse proxy,
198+
// then we need to remove the sub-url path from the request URL path
199+
if setting.UseSubURLPath {
200+
remainingPath, ok := strings.CutPrefix(normalizedPath, setting.AppSubURL+"/")
201+
if ok {
202+
normalizedPath = "/" + remainingPath
203+
} else if normalizedPath == setting.AppSubURL {
204+
normalizedPath = "/"
205+
} else if !strings.HasPrefix(normalizedPath+"/", "/v2/") {
206+
// do not respond to other requests, to simulate a real sub-path environment
207+
http.Error(resp, "404 page not found, sub-path is: "+setting.AppSubURL, http.StatusNotFound)
208+
return
209+
}
210+
normalized = true
211+
}
212+
213+
// if the path is normalized, then fill it back to the request
214+
if normalized {
215+
decodedPath, err := url.PathUnescape(normalizedPath)
216+
if err != nil {
217+
http.Error(resp, "400 Bad Request: unable to unescape path "+normalizedPath, http.StatusBadRequest)
218+
return
219+
}
220+
req.URL.RawPath = normalizedPath
221+
req.URL.Path = decodedPath
222+
}
223+
224+
next.ServeHTTP(resp, req)
225+
}
226+
171227
// Combo delegates requests to Combo
172228
func (r *Route) Combo(pattern string, h ...any) *Combo {
173229
return &Combo{r, pattern, h}

modules/web/route_test.go

+43
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ import (
1010
"strconv"
1111
"testing"
1212

13+
"code.gitea.io/gitea/modules/setting"
14+
"code.gitea.io/gitea/modules/test"
15+
1316
chi "github.com/go-chi/chi/v5"
1417
"github.com/stretchr/testify/assert"
1518
)
@@ -176,3 +179,43 @@ func TestRoute3(t *testing.T) {
176179
assert.EqualValues(t, http.StatusOK, recorder.Code)
177180
assert.EqualValues(t, 4, hit)
178181
}
182+
183+
func TestRouteNormalizePath(t *testing.T) {
184+
type paths struct {
185+
EscapedPath, RawPath, Path string
186+
}
187+
testPath := func(reqPath string, expectedPaths paths) {
188+
recorder := httptest.NewRecorder()
189+
recorder.Body = bytes.NewBuffer(nil)
190+
191+
actualPaths := paths{EscapedPath: "(none)", RawPath: "(none)", Path: "(none)"}
192+
r := NewRoute()
193+
r.Get("/*", func(resp http.ResponseWriter, req *http.Request) {
194+
actualPaths.EscapedPath = req.URL.EscapedPath()
195+
actualPaths.RawPath = req.URL.RawPath
196+
actualPaths.Path = req.URL.Path
197+
})
198+
199+
req, err := http.NewRequest("GET", reqPath, nil)
200+
assert.NoError(t, err)
201+
r.ServeHTTP(recorder, req)
202+
assert.Equal(t, expectedPaths, actualPaths, "req path = %q", reqPath)
203+
}
204+
205+
// RawPath could be empty if the EscapedPath is the same as escape(Path) and it is already normalized
206+
testPath("/", paths{EscapedPath: "/", RawPath: "", Path: "/"})
207+
testPath("//", paths{EscapedPath: "/", RawPath: "/", Path: "/"})
208+
testPath("/%2f", paths{EscapedPath: "/%2f", RawPath: "/%2f", Path: "//"})
209+
testPath("///a//b/", paths{EscapedPath: "/a/b", RawPath: "/a/b", Path: "/a/b"})
210+
211+
defer test.MockVariableValue(&setting.UseSubURLPath, true)()
212+
defer test.MockVariableValue(&setting.AppSubURL, "/sub-path")()
213+
testPath("/", paths{EscapedPath: "(none)", RawPath: "(none)", Path: "(none)"}) // 404
214+
testPath("/sub-path", paths{EscapedPath: "/", RawPath: "/", Path: "/"})
215+
testPath("/sub-path/", paths{EscapedPath: "/", RawPath: "/", Path: "/"})
216+
testPath("/sub-path//a/b///", paths{EscapedPath: "/a/b", RawPath: "/a/b", Path: "/a/b"})
217+
testPath("/sub-path/%2f/", paths{EscapedPath: "/%2f", RawPath: "/%2f", Path: "//"})
218+
testPath("/v2", paths{EscapedPath: "/v2", RawPath: "/v2", Path: "/v2"})
219+
testPath("/v2/", paths{EscapedPath: "/v2", RawPath: "/v2", Path: "/v2"})
220+
testPath("/v2/%2f", paths{EscapedPath: "/v2/%2f", RawPath: "/v2/%2f", Path: "/v2//"})
221+
}

routers/common/middleware.go

-56
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,10 @@ import (
1919

2020
"gitea.com/go-chi/session"
2121
"github.com/chi-middleware/proxy"
22-
chi "github.com/go-chi/chi/v5"
2322
)
2423

2524
// ProtocolMiddlewares returns HTTP protocol related middlewares, and it provides a global panic recovery
2625
func ProtocolMiddlewares() (handlers []any) {
27-
// first, normalize the URL path
28-
handlers = append(handlers, normalizeRequestPathMiddleware)
29-
3026
// prepare the ContextData and panic recovery
3127
handlers = append(handlers, func(next http.Handler) http.Handler {
3228
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
@@ -75,58 +71,6 @@ func ProtocolMiddlewares() (handlers []any) {
7571
return handlers
7672
}
7773

78-
func normalizeRequestPathMiddleware(next http.Handler) http.Handler {
79-
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
80-
// escape the URL RawPath to ensure that all routing is done using a correctly escaped URL
81-
req.URL.RawPath = req.URL.EscapedPath()
82-
83-
urlPath := req.URL.RawPath
84-
rctx := chi.RouteContext(req.Context())
85-
if rctx != nil && rctx.RoutePath != "" {
86-
urlPath = rctx.RoutePath
87-
}
88-
89-
normalizedPath := strings.TrimRight(urlPath, "/")
90-
// the following code block is a slow-path for replacing all repeated slashes "//" to one single "/"
91-
// if the path doesn't have repeated slashes, then no need to execute it
92-
if strings.Contains(normalizedPath, "//") {
93-
buf := &strings.Builder{}
94-
prevWasSlash := false
95-
for _, chr := range normalizedPath {
96-
if chr != '/' || !prevWasSlash {
97-
buf.WriteRune(chr)
98-
}
99-
prevWasSlash = chr == '/'
100-
}
101-
normalizedPath = buf.String()
102-
}
103-
104-
if setting.UseSubURLPath {
105-
remainingPath, ok := strings.CutPrefix(normalizedPath, setting.AppSubURL+"/")
106-
if ok {
107-
normalizedPath = "/" + remainingPath
108-
} else if normalizedPath == setting.AppSubURL {
109-
normalizedPath = "/"
110-
} else if !strings.HasPrefix(normalizedPath+"/", "/v2/") {
111-
// do not respond to other requests, to simulate a real sub-path environment
112-
http.Error(resp, "404 page not found, sub-path is: "+setting.AppSubURL, http.StatusNotFound)
113-
return
114-
}
115-
// TODO: it's not quite clear about how req.URL and rctx.RoutePath work together.
116-
// Fortunately, it is only used for debug purpose, we have enough time to figure it out in the future.
117-
req.URL.RawPath = normalizedPath
118-
req.URL.Path = normalizedPath
119-
}
120-
121-
if rctx == nil {
122-
req.URL.Path = normalizedPath
123-
} else {
124-
rctx.RoutePath = normalizedPath
125-
}
126-
next.ServeHTTP(resp, req)
127-
})
128-
}
129-
13074
func Sessioner() func(next http.Handler) http.Handler {
13175
return session.Sessioner(session.Options{
13276
Provider: setting.SessionConfig.Provider,

routers/common/middleware_test.go

-70
This file was deleted.

0 commit comments

Comments
 (0)