Browse Source

trace: make AuthRequest robust to multiple RemoteAddr formats

Change-Id: Ia61f61d0b9395f383ff622f2d606dcd499f57776
Reviewed-on: https://go-review.googlesource.com/20588
Reviewed-by: David Symonds <dsymonds@golang.org>
Dave Day 9 năm trước cách đây
mục cha
commit
35b06af072
2 tập tin đã thay đổi với 32 bổ sung4 xóa
  1. 7 4
      trace/trace.go
  2. 25 0
      trace/trace_test.go

+ 7 - 4
trace/trace.go

@@ -95,11 +95,14 @@ var DebugUseAfterFinish = false
 //
 // The default AuthRequest function returns (true, true) iff the request comes from localhost/127.0.0.1/[::1].
 var AuthRequest = func(req *http.Request) (any, sensitive bool) {
+	// RemoteAddr is commonly in the form "IP" or "IP:port".
+	// If it is in the form "IP:port", split off the port.
 	host, _, err := net.SplitHostPort(req.RemoteAddr)
-	switch {
-	case err != nil: // Badly formed address; fail closed.
-		return false, false
-	case host == "localhost" || host == "127.0.0.1" || host == "::1":
+	if err != nil {
+		host = req.RemoteAddr
+	}
+	switch host {
+	case "localhost", "127.0.0.1", "::1":
 		return true, true
 	default:
 		return false, false

+ 25 - 0
trace/trace_test.go

@@ -5,6 +5,7 @@
 package trace
 
 import (
+	"net/http"
 	"reflect"
 	"testing"
 )
@@ -44,3 +45,27 @@ func TestResetLog(t *testing.T) {
 		t.Errorf("reset didn't clear all fields: %+v", el)
 	}
 }
+
+func TestAuthRequest(t *testing.T) {
+	testCases := []struct {
+		host string
+		want bool
+	}{
+		{host: "192.168.23.1", want: false},
+		{host: "192.168.23.1:8080", want: false},
+		{host: "malformed remote addr", want: false},
+		{host: "localhost", want: true},
+		{host: "localhost:8080", want: true},
+		{host: "127.0.0.1", want: true},
+		{host: "127.0.0.1:8080", want: true},
+		{host: "::1", want: true},
+		{host: "[::1]:8080", want: true},
+	}
+	for _, tt := range testCases {
+		req := &http.Request{RemoteAddr: tt.host}
+		any, sensitive := AuthRequest(req)
+		if any != tt.want || sensitive != tt.want {
+			t.Errorf("AuthRequest(%q) = %t, %t; want %t, %t", tt.host, any, sensitive, tt.want, tt.want)
+		}
+	}
+}