1
0

util_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. }
  29. func TestResolveHostPrefersForwardedHostOverRealIP(t *testing.T) {
  30. gin.SetMode(gin.TestMode)
  31. c, _ := gin.CreateTestContext(httptest.NewRecorder())
  32. c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
  33. c.Request.Host = "panel.example.com:2053"
  34. c.Request.RemoteAddr = "127.0.0.1:12345"
  35. c.Request.Header.Set("X-Forwarded-Host", "sub.example.net:443")
  36. c.Request.Header.Set("X-Real-IP", "198.51.100.7")
  37. if got := resolveHost(c); got != "sub.example.net" {
  38. t.Fatalf("resolveHost = %q, want X-Forwarded-Host", got)
  39. }
  40. }
  41. func TestResolveHostIgnoresRealIPFromTrustedProxy(t *testing.T) {
  42. gin.SetMode(gin.TestMode)
  43. c, _ := gin.CreateTestContext(httptest.NewRecorder())
  44. c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
  45. c.Request.Host = "panel.example.com:2053"
  46. c.Request.RemoteAddr = "127.0.0.1:12345"
  47. c.Request.Header.Set("X-Real-IP", "198.51.100.7")
  48. if got := resolveHost(c); got != "panel.example.com" {
  49. t.Fatalf("resolveHost = %q, want request host (not X-Real-IP)", got)
  50. }
  51. }