mirror of
https://github.com/VictoriaMetrics/VictoriaMetrics.git
synced 2026-05-17 08:36:55 +03:00
lib/httpserver: properly quote the returned address from GetQuotedRemoteAddr() for requests with X-Forwarded-For header
Make sure that the quoted address can be used as JSON string. Updates https://github.com/VictoriaMetrics/VictoriaMetrics/pull/4676#issuecomment-1663203424 This is a follow up for252643d100andac0b7e0421Updates https://github.com/VictoriaMetrics/VictoriaMetrics/pull/4676
This commit is contained in:
36
lib/httpserver/httpserver_test.go
Normal file
36
lib/httpserver/httpserver_test.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package httpserver
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGetQuotedRemoteAddr(t *testing.T) {
|
||||
f := func(remoteAddr, xForwardedFor, expectedAddr string) {
|
||||
t.Helper()
|
||||
|
||||
req := &http.Request{
|
||||
RemoteAddr: remoteAddr,
|
||||
}
|
||||
if xForwardedFor != "" {
|
||||
req.Header = map[string][]string{
|
||||
"X-Forwarded-For": {xForwardedFor},
|
||||
}
|
||||
}
|
||||
addr := GetQuotedRemoteAddr(req)
|
||||
if addr != expectedAddr {
|
||||
t.Fatalf("unexpected remote addr;\ngot\n%s\nwant\n%s", addr, expectedAddr)
|
||||
}
|
||||
|
||||
// Verify that the addr can be unmarshaled as JSON string
|
||||
var s string
|
||||
if err := json.Unmarshal([]byte(addr), &s); err != nil {
|
||||
t.Fatalf("cannot unmarshal addr: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
f("1.2.3.4", "", `"1.2.3.4"`)
|
||||
f("1.2.3.4", "foo.bar", `"1.2.3.4, X-Forwarded-For: foo.bar"`)
|
||||
f("1.2\n\"3.4", "foo\nb\"ar", `"1.2\n\"3.4, X-Forwarded-For: foo\nb\"ar"`)
|
||||
}
|
||||
Reference in New Issue
Block a user