util_test.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. package controller
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "testing"
  6. "github.com/gin-gonic/gin"
  7. )
  8. func TestGetRemoteIpIgnoresForwardedHeadersFromUntrustedRemote(t *testing.T) {
  9. gin.SetMode(gin.TestMode)
  10. c, _ := gin.CreateTestContext(httptest.NewRecorder())
  11. c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
  12. c.Request.RemoteAddr = "203.0.113.10:12345"
  13. c.Request.Header.Set("X-Real-IP", "198.51.100.9")
  14. c.Request.Header.Set("X-Forwarded-For", "198.51.100.8")
  15. if got := getRemoteIp(c); got != "203.0.113.10" {
  16. t.Fatalf("remote IP = %q, want request remote address", got)
  17. }
  18. }
  19. func TestGetRemoteIpHonorsForwardedHeadersFromTrustedLoopbackProxy(t *testing.T) {
  20. gin.SetMode(gin.TestMode)
  21. c, _ := gin.CreateTestContext(httptest.NewRecorder())
  22. c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
  23. c.Request.RemoteAddr = "127.0.0.1:12345"
  24. c.Request.Header.Set("X-Forwarded-For", "198.51.100.8, 127.0.0.1")
  25. if got := getRemoteIp(c); got != "198.51.100.8" {
  26. t.Fatalf("remote IP = %q, want forwarded client IP", got)
  27. }
  28. }