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

Fix respect of x-real-ip / x-forwarded-for headers in context #16443

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions modules/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -511,9 +511,19 @@ func (ctx *Context) GetCookieFloat64(name string) float64 {
return v
}

// RemoteAddr returns the client machie ip address
// RemoteAddr returns the client machine ip address. It respects the X-Real-IP (preferred) or X-Forwarded-For header.
func (ctx *Context) RemoteAddr() string {
return ctx.Req.RemoteAddr
addr := ctx.Req.Header.Get("X-Real-IP")
if len(addr) == 0 {
addr = ctx.Req.Header.Get("X-Forwarded-For")
if addr == "" {
addr = ctx.Req.RemoteAddr
if i := strings.LastIndex(addr, ":"); i > -1 {
addr = addr[:i]
}
}
}
return addr
}

// Params returns the param on route
Expand Down
44 changes: 44 additions & 0 deletions modules/context/context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright 2021 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package context

import (
"net/http"
"testing"

"code.gitea.io/gitea/modules/context"

"github.com/stretchr/testify/assert"
)

func TestRemoteAddrNoHeader(t *testing.T) {
expected := "123.456.78.9"
req, _ := http.NewRequest(http.MethodGet, "url", nil)
req.RemoteAddr = expected

ctx := context.Context{Req: req}

assert.Equal(t, expected, ctx.RemoteAddr(), "RemoteAddr should match the expected response")
}

func TestRemoteAddrXRealIpHeader(t *testing.T) {
expected := "123.456.78.9"
req, _ := http.NewRequest(http.MethodGet, "url", nil)
req.Header.Add("X-Real-IP", expected)

ctx := context.Context{Req: req}

assert.Equal(t, expected, ctx.RemoteAddr(), "RemoteAddr should match the expected response")
}

func TestRemoteAddrXForwardedForHeader(t *testing.T) {
expected := "123.456.78.9"
req, _ := http.NewRequest(http.MethodGet, "url", nil)
req.Header.Add("X-Forwarded-For", expected)

ctx := context.Context{Req: req}

assert.Equal(t, expected, ctx.RemoteAddr(), "RemoteAddr should match the expected response")
}