Compare commits

...

4 Commits

Author SHA1 Message Date
Name
4002e40b21
Merge a14cf7c08dc37b7f9308248928aa3b16307f3c2f into 9914178584e42458ff7d23891463a880f58c9d86 2026-01-02 16:18:12 +08:00
Nurysso
9914178584
fix(context): ClientIP handling for multiple X-Forwarded-For header values (#4472)
* Fix ClientIP calculation by concatenating all RemoteIPHeaders values

* test: used http.MethodGet instead constants and fix lints

* lint error fixed

* Refactor ClientIP X-Forwarded-For tests

---------

Co-authored-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2026-01-02 10:15:27 +08:00
1911860538
a14cf7c08d refactor(render): use WriteJSON when JsonpJson.Callback is empty 2025-11-08 22:06:23 +08:00
1911860538
b7afe5a6af fix(render): improve JsonpJSON content type handling and simplify Context.JSONP 2025-11-08 13:35:02 +08:00
4 changed files with 58 additions and 20 deletions

View File

@ -989,7 +989,8 @@ func (c *Context) ClientIP() string {
if trusted && c.engine.ForwardedByClientIP && c.engine.RemoteIPHeaders != nil {
for _, headerName := range c.engine.RemoteIPHeaders {
ip, valid := c.engine.validateHeader(c.requestHeader(headerName))
headerValue := strings.Join(c.Request.Header.Values(headerName), ",")
ip, valid := c.engine.validateHeader(headerValue)
if valid {
return ip
}
@ -1165,13 +1166,10 @@ func (c *Context) SecureJSON(code int, obj any) {
// JSONP serializes the given struct as JSON into the response body.
// It adds padding to response body to request data from a server residing in a different domain than the client.
// It also sets the Content-Type as "application/javascript".
//
// When the callback parameter is empty, it behaves equivalently to Context.JSON.
func (c *Context) JSONP(code int, obj any) {
callback := c.DefaultQuery("callback", "")
if callback == "" {
c.Render(code, render.JSON{Data: obj})
return
}
c.Render(code, render.JsonpJSON{Callback: callback, Data: obj})
c.Render(code, render.JsonpJSON{Callback: c.Query("callback"), Data: obj})
}
// JSON serializes the given struct as JSON into the response body.

View File

@ -1143,6 +1143,37 @@ func TestContextRenderNoContentIndentedJSON(t *testing.T) {
assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
}
func TestContextClientIPWithMultipleHeaders(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest(http.MethodGet, "/test", nil)
// Multiple X-Forwarded-For headers
c.Request.Header.Add("X-Forwarded-For", "1.2.3.4, "+localhostIP)
c.Request.Header.Add("X-Forwarded-For", "5.6.7.8")
c.Request.RemoteAddr = localhostIP + ":1234"
c.engine.ForwardedByClientIP = true
c.engine.RemoteIPHeaders = []string{"X-Forwarded-For"}
_ = c.engine.SetTrustedProxies([]string{localhostIP})
// Should return 5.6.7.8 (last non-trusted IP)
assert.Equal(t, "5.6.7.8", c.ClientIP())
}
func TestContextClientIPWithSingleHeader(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest(http.MethodGet, "/test", nil)
c.Request.Header.Set("X-Forwarded-For", "1.2.3.4, "+localhostIP)
c.Request.RemoteAddr = localhostIP + ":1234"
c.engine.ForwardedByClientIP = true
c.engine.RemoteIPHeaders = []string{"X-Forwarded-For"}
_ = c.engine.SetTrustedProxies([]string{localhostIP})
// Should return 1.2.3.4
assert.Equal(t, "1.2.3.4", c.ClientIP())
}
// Tests that the response is serialized as Secure JSON
// and Content-Type is set to application/json
func TestContextRenderSecureJSON(t *testing.T) {

View File

@ -115,14 +115,14 @@ func (r SecureJSON) WriteContentType(w http.ResponseWriter) {
// Render (JsonpJSON) marshals the given interface object and writes it and its callback with custom ContentType.
func (r JsonpJSON) Render(w http.ResponseWriter) (err error) {
r.WriteContentType(w)
ret, err := json.API.Marshal(r.Data)
if err != nil {
return err
if r.Callback == "" {
return WriteJSON(w, r.Data)
}
if r.Callback == "" {
_, err = w.Write(ret)
r.WriteContentType(w)
ret, err := json.API.Marshal(r.Data)
if err != nil {
return err
}

View File

@ -183,19 +183,28 @@ func TestRenderJsonpJSONError(t *testing.T) {
assert.Equal(t, `write "`+`);`+`" error`, err.Error())
}
func TestRenderJsonpJSONError2(t *testing.T) {
func TestRenderJsonpJSONWithEmptyCallback(t *testing.T) {
w := httptest.NewRecorder()
data := map[string]any{
"foo": "bar",
"num": 42,
"nested": map[string]any{
"key": "value",
},
}
(JsonpJSON{"", data}).WriteContentType(w)
assert.Equal(t, "application/javascript; charset=utf-8", w.Header().Get("Content-Type"))
e := (JsonpJSON{"", data}).Render(w)
require.NoError(t, e)
err := (JsonpJSON{Callback: "", Data: data}).Render(w)
assert.JSONEq(t, "{\"foo\":\"bar\"}", w.Body.String())
assert.Equal(t, "application/javascript; charset=utf-8", w.Header().Get("Content-Type"))
require.NoError(t, err)
// Verify Content-Type is set to jsonContentType when callback is empty
assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
renderData, err := json.API.Marshal(data)
require.NoError(t, err)
// Verify body contains correct JSON data
assert.JSONEq(t, string(renderData), w.Body.String())
}
func TestRenderJsonpJSONFail(t *testing.T) {