Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(Redirect): Added to prevent the redirect location from being empty in debug mode #4011

Closed
wants to merge 10 commits into from
7 changes: 7 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -1066,7 +1066,14 @@
}

// Redirect returns an HTTP redirect to the specific location.
// When the 'location' parameter is empty, it poses a potential security risk.
// Avoid bringing potential security risks into the production environment.
func (c *Context) Redirect(code int, location string) {
if IsDebugging() && location == "" {
debugPrint(`[WARNING] When the 'location' parameter is empty, it poses a potential security risk. Please input a secure redirection URL to ensure safe operation.`)
location = "/"

Check warning on line 1074 in context.go

View check run for this annotation

Codecov / codecov/patch

context.go#L1073-L1074

Added lines #L1073 - L1074 were not covered by tests
}

c.Render(-1, render.Redirect{
Code: code,
Location: location,
Expand Down
12 changes: 12 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1217,6 +1217,18 @@ func TestContextRenderRedirectWith201(t *testing.T) {
assert.Equal(t, "/resource", w.Header().Get("Location"))
}

func TestContextRenderRedirectWithEmptyPath(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)

c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
c.Redirect(http.StatusTemporaryRedirect, "")
c.Writer.WriteHeaderNow()

assert.Equal(t, http.StatusTemporaryRedirect, w.Code)
assert.Equal(t, "/", w.Header().Get("Location"))
}

func TestContextRenderRedirectAll(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
Expand Down
2 changes: 2 additions & 0 deletions docs/doc.md
Original file line number Diff line number Diff line change
Expand Up @@ -1496,6 +1496,8 @@ Gin allow by default use only one html.Template. Check [a multitemplate render](

Issuing a HTTP redirect is easy. Both internal and external locations are supported.

Note: When the location is empty, there is a security risk. Please do not bring it to production

```go
r.GET("/test", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")
Expand Down