Compare commits

...

11 Commits

Author SHA1 Message Date
Pratham Gadkari
a5e5ba9de6
Merge 527f128f96bf4d9e412b8e7f01323c33910d069e into b2b489dbf4826c2c630717a77fd5e42774625410 2026-01-18 17:58:32 -08:00
WeidiDeng
b2b489dbf4
chore(context): always trust xff headers from unix socket (#3359)
Co-authored-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2026-01-18 12:56:22 +08:00
OHZEKI Naoki
3ab698dc51
refactor(recovery): smart error comparison (#4142)
* refactor(recovery): rename var in CustomRecoveryWithWriter

* refactor(recovery): smart error comparison

* test(recovery): Directly reference the syscall error string
2026-01-17 16:40:43 +08:00
Pratham Gadkari
527f128f96 combining and adding tests 2025-11-30 16:35:13 +05:30
Pratham Gadkari
b6e5603530 more tests because coverage is failing 2025-11-30 16:26:33 +05:30
Pratham Gadkari
822cf17bf9 modifying setArray and setSlice 2025-11-30 16:10:58 +05:30
Pratham Gadkari
6b6ac46ae3 using errors instead of fmt 2025-11-30 16:01:27 +05:30
Pratham Gadkari
ee1f501d4a more tests for code coverage 2025-11-30 15:58:56 +05:30
Bo-Yi Wu
ef09093976
Merge branch 'master' into fix-binding-custom-unmarhsal-4296 2025-11-30 15:41:08 +08:00
Pratham Gadkari
513a86e17f added tests for feature and coverage 2025-11-15 22:28:32 +05:30
Pratham Gadkari
b4d09053db fix(binding): support custom unmarshaler for slices & arrays 2025-11-14 23:44:50 +05:30
6 changed files with 175 additions and 39 deletions

View File

@ -186,7 +186,10 @@ type BindUnmarshaler interface {
func trySetCustom(val string, value reflect.Value) (isSet bool, err error) {
switch v := value.Addr().Interface().(type) {
case BindUnmarshaler:
return true, v.UnmarshalParam(val)
if err := v.UnmarshalParam(val); err != nil {
return true, fmt.Errorf("invalid value %q: %w", val, err)
}
return true, nil
}
return false, nil
}
@ -245,7 +248,10 @@ func setByForm(value reflect.Value, field reflect.StructField, form map[string][
}
if ok, err = trySetCustom(vs[0], value); ok {
return ok, err
if err != nil {
return true, fmt.Errorf("field %q: %w", field.Name, err)
}
return true, nil
}
if vs, err = trySplit(vs, field); err != nil {
@ -268,7 +274,10 @@ func setByForm(value reflect.Value, field reflect.StructField, form map[string][
}
if ok, err = trySetCustom(vs[0], value); ok {
return ok, err
if err != nil {
return true, fmt.Errorf("field %q: %w", field.Name, err)
}
return true, nil
}
if vs, err = trySplit(vs, field); err != nil {
@ -293,7 +302,10 @@ func setByForm(value reflect.Value, field reflect.StructField, form map[string][
}
}
if ok, err := trySetCustom(val, value); ok {
return ok, err
if err != nil {
return true, fmt.Errorf("field %q: %w", field.Name, err)
}
return true, nil
}
return true, setWithProperType(val, value, field)
}
@ -461,6 +473,12 @@ func setTimeField(val string, structField reflect.StructField, value reflect.Val
func setArray(vals []string, value reflect.Value, field reflect.StructField) error {
for i, s := range vals {
if ok, err := trySetCustom(s, value.Index(i)); ok {
if err != nil {
return fmt.Errorf("field %q: %w", field.Name, err)
}
continue
}
err := setWithProperType(s, value.Index(i), field)
if err != nil {
return err

View File

@ -754,3 +754,104 @@ func TestMappingEmptyValues(t *testing.T) {
assert.Equal(t, []int{1, 2, 3}, s.SliceCsv)
})
}
type testCustom struct {
Value string
}
func (t *testCustom) UnmarshalParam(param string) error {
t.Value = "prefix_" + param
return nil
}
func TestTrySetCustomIntegration(t *testing.T) {
var s struct {
F testCustom `form:"f"`
}
err := mappingByPtr(&s, formSource{"f": {"hello"}}, "form")
require.NoError(t, err)
assert.Equal(t, "prefix_hello", s.F.Value)
}
type badCustom struct{}
func (b *badCustom) UnmarshalParam(s string) error {
return errors.New("boom")
}
func TestTrySetCustom_SingleValues(t *testing.T) {
t.Run("Error case", func(t *testing.T) {
var s struct {
F badCustom `form:"f"`
}
err := mappingByPtr(&s, formSource{"f": {"hello"}}, "form")
require.Error(t, err)
assert.Contains(t, err.Error(), "invalid value")
})
t.Run("Integration success", func(t *testing.T) {
var s struct {
F testCustom `form:"f"`
}
err := mappingByPtr(&s, formSource{"f": {"hello"}}, "form")
require.NoError(t, err)
assert.Equal(t, "prefix_hello", s.F.Value)
})
t.Run("Not applicable type", func(t *testing.T) {
var s struct {
N int `form:"n"`
}
err := mappingByPtr(&s, formSource{"n": {"42"}}, "form")
require.NoError(t, err)
assert.Equal(t, 42, s.N)
})
}
func TestTrySetCustom_Collections(t *testing.T) {
t.Run("Slice success", func(t *testing.T) {
var s struct {
F []testCustom `form:"f"`
}
err := mappingByPtr(&s, formSource{"f": {"one", "two"}}, "form")
require.NoError(t, err)
assert.Equal(t, "prefix_one", s.F[0].Value)
assert.Equal(t, "prefix_two", s.F[1].Value)
})
t.Run("Array success", func(t *testing.T) {
var s struct {
F [2]testCustom `form:"f"`
}
err := mappingByPtr(&s, formSource{"f": {"hello", "world"}}, "form")
require.NoError(t, err)
assert.Equal(t, "prefix_hello", s.F[0].Value)
assert.Equal(t, "prefix_world", s.F[1].Value)
})
t.Run("Slice error", func(t *testing.T) {
var s struct {
F []badCustom `form:"f"`
}
err := mappingByPtr(&s, formSource{"f": {"oops1", "oops2"}}, "form")
require.Error(t, err)
assert.Contains(t, err.Error(), "invalid value")
})
t.Run("Array error", func(t *testing.T) {
var s struct {
F [2]badCustom `form:"f"`
}
err := mappingByPtr(&s, formSource{"f": {"fail1", "fail2"}}, "form")
require.Error(t, err)
assert.Contains(t, err.Error(), "invalid value")
})
}

View File

@ -978,14 +978,27 @@ func (c *Context) ClientIP() string {
}
}
// It also checks if the remoteIP is a trusted proxy or not.
// In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks
// defined by Engine.SetTrustedProxies()
remoteIP := net.ParseIP(c.RemoteIP())
if remoteIP == nil {
return ""
var (
trusted bool
remoteIP net.IP
)
// If gin is listening a unix socket, always trust it.
localAddr, ok := c.Request.Context().Value(http.LocalAddrContextKey).(net.Addr)
if ok && strings.HasPrefix(localAddr.Network(), "unix") {
trusted = true
}
// Fallback
if !trusted {
// It also checks if the remoteIP is a trusted proxy or not.
// In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks
// defined by Engine.SetTrustedProxies()
remoteIP = net.ParseIP(c.RemoteIP())
if remoteIP == nil {
return ""
}
trusted = c.engine.isTrustedProxy(remoteIP)
}
trusted := c.engine.isTrustedProxy(remoteIP)
if trusted && c.engine.ForwardedByClientIP && c.engine.RemoteIPHeaders != nil {
for _, headerName := range c.engine.RemoteIPHeaders {

View File

@ -1915,6 +1915,16 @@ func TestContextClientIP(t *testing.T) {
c.engine.trustedCIDRs, _ = c.engine.prepareTrustedCIDRs()
resetContextForClientIPTests(c)
// unix address
addr := &net.UnixAddr{Net: "unix", Name: "@"}
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), http.LocalAddrContextKey, addr))
c.Request.RemoteAddr = addr.String()
assert.Equal(t, "20.20.20.20", c.ClientIP())
// reset
c.Request = c.Request.WithContext(context.Background())
resetContextForClientIPTests(c)
// Legacy tests (validating that the defaults don't break the
// (insecure!) old behaviour)
assert.Equal(t, "20.20.20.20", c.ClientIP())

View File

@ -12,12 +12,12 @@ import (
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"os"
"runtime"
"strings"
"syscall"
"time"
"github.com/gin-gonic/gin/internal/bytesconv"
@ -57,40 +57,33 @@ func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc {
}
return func(c *Context) {
defer func() {
if err := recover(); err != nil {
if rec := recover(); rec != nil {
// Check for a broken connection, as it is not really a
// condition that warrants a panic stack trace.
var brokenPipe bool
if ne, ok := err.(*net.OpError); ok {
var se *os.SyscallError
if errors.As(ne, &se) {
seStr := strings.ToLower(se.Error())
if strings.Contains(seStr, "broken pipe") ||
strings.Contains(seStr, "connection reset by peer") {
brokenPipe = true
}
}
}
if e, ok := err.(error); ok && errors.Is(e, http.ErrAbortHandler) {
brokenPipe = true
var isBrokenPipe bool
err, ok := rec.(error)
if ok {
isBrokenPipe = errors.Is(err, syscall.EPIPE) ||
errors.Is(err, syscall.ECONNRESET) ||
errors.Is(err, http.ErrAbortHandler)
}
if logger != nil {
if brokenPipe {
logger.Printf("%s\n%s%s", err, secureRequestDump(c.Request), reset)
if isBrokenPipe {
logger.Printf("%s\n%s%s", rec, secureRequestDump(c.Request), reset)
} else if IsDebugging() {
logger.Printf("[Recovery] %s panic recovered:\n%s\n%s\n%s%s",
timeFormat(time.Now()), secureRequestDump(c.Request), err, stack(stackSkip), reset)
timeFormat(time.Now()), secureRequestDump(c.Request), rec, stack(stackSkip), reset)
} else {
logger.Printf("[Recovery] %s panic recovered:\n%s\n%s%s",
timeFormat(time.Now()), err, stack(stackSkip), reset)
timeFormat(time.Now()), rec, stack(stackSkip), reset)
}
}
if brokenPipe {
if isBrokenPipe {
// If the connection is dead, we can't write a status to it.
c.Error(err.(error)) //nolint: errcheck
c.Error(err) //nolint: errcheck
c.Abort()
} else {
handle(c, err)
handle(c, rec)
}
}
}()

View File

@ -98,13 +98,13 @@ func TestFunction(t *testing.T) {
func TestPanicWithBrokenPipe(t *testing.T) {
const expectCode = 204
expectMsgs := map[syscall.Errno]string{
syscall.EPIPE: "broken pipe",
syscall.ECONNRESET: "connection reset by peer",
expectErrnos := []syscall.Errno{
syscall.EPIPE,
syscall.ECONNRESET,
}
for errno, expectMsg := range expectMsgs {
t.Run(expectMsg, func(t *testing.T) {
for _, errno := range expectErrnos {
t.Run("Recovery from "+errno.Error(), func(t *testing.T) {
var buf strings.Builder
router := New()
@ -122,7 +122,8 @@ func TestPanicWithBrokenPipe(t *testing.T) {
w := PerformRequest(router, http.MethodGet, "/recovery")
// TEST
assert.Equal(t, expectCode, w.Code)
assert.Contains(t, strings.ToLower(buf.String()), expectMsg)
assert.Contains(t, strings.ToLower(buf.String()), errno.Error())
assert.NotContains(t, strings.ToLower(buf.String()), "[Recovery]")
})
}
}