Skip to content

Commit 0b5a4e7

Browse files
GiteaBotwxiaoguang
andauthored
Use strict protocol check when redirect (#29642) (#29644)
Backport #29642 by wxiaoguang Co-authored-by: wxiaoguang <[email protected]>
1 parent b6a2b95 commit 0b5a4e7

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

modules/context/base.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ func (b *Base) Redirect(location string, status ...int) {
255255
code = status[0]
256256
}
257257

258-
if strings.Contains(location, "://") || strings.HasPrefix(location, "//") {
258+
if strings.HasPrefix(location, "http://") || strings.HasPrefix(location, "https://") || strings.HasPrefix(location, "//") {
259259
// Some browsers (Safari) have buggy behavior for Cookie + Cache + External Redirection, eg: /my-path => https://other/path
260260
// 1. the first request to "/my-path" contains cookie
261261
// 2. some time later, the request to "/my-path" doesn't contain cookie (caused by Prevent web tracking)

services/context/base_test.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Copyright 2024 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package context
5+
6+
import (
7+
"net/http"
8+
"net/http/httptest"
9+
"testing"
10+
11+
"code.gitea.io/gitea/modules/context"
12+
"code.gitea.io/gitea/modules/setting"
13+
14+
"github.com/stretchr/testify/assert"
15+
)
16+
17+
func TestRedirect(t *testing.T) {
18+
req, _ := http.NewRequest("GET", "/", nil)
19+
20+
cases := []struct {
21+
url string
22+
keep bool
23+
}{
24+
{"http://test", false},
25+
{"https://test", false},
26+
{"//test", false},
27+
{"/://test", true},
28+
{"/test", true},
29+
}
30+
for _, c := range cases {
31+
resp := httptest.NewRecorder()
32+
b, cleanup := context.NewBaseContext(resp, req)
33+
resp.Header().Add("Set-Cookie", (&http.Cookie{Name: setting.SessionConfig.CookieName, Value: "dummy"}).String())
34+
b.Redirect(c.url)
35+
cleanup()
36+
has := resp.Header().Get("Set-Cookie") == "i_like_gitea=dummy"
37+
assert.Equal(t, c.keep, has, "url = %q", c.url)
38+
}
39+
}

0 commit comments

Comments
 (0)