@@ -5,11 +5,14 @@ import (
55 "fmt"
66 "net/http"
77 "net/http/httptest"
8+ "net/url"
89 "strings"
910 "testing"
1011 "time"
1112
13+ "github.com/oauth2-proxy/oauth2-proxy/pkg/apis/options"
1214 "github.com/oauth2-proxy/oauth2-proxy/pkg/logger"
15+ "github.com/oauth2-proxy/oauth2-proxy/pkg/validation"
1316)
1417
1518func TestLoggingHandler_ServeHTTP(t *testing.T) {
@@ -67,3 +70,59 @@ func TestLoggingHandler_ServeHTTP(t *testing.T) {
6770 }
6871 }
6972}
73+
74+func TestLoggingHandler_PingUserAgent(t *testing.T) {
75+ tests := []struct {
76+ ExpectedLogMessage string
77+ Path string
78+ SilencePingLogging bool
79+ WithUserAgent string
80+ }{
81+ {"444\n", "/foo", true, "Blah"},
82+ {"444\n", "/foo", false, "Blah"},
83+ {"", "/ping", true, "Blah"},
84+ {"200\n", "/ping", false, "Blah"},
85+ {"", "/ping", true, "PingMe!"},
86+ {"", "/ping", false, "PingMe!"},
87+ {"", "/foo", true, "PingMe!"},
88+ {"", "/foo", false, "PingMe!"},
89+ }
90+
91+ for idx, test := range tests {
92+ t.Run(fmt.Sprintf("%d", idx), func(t *testing.T) {
93+ opts := options.NewOptions()
94+ opts.PingUserAgent = "PingMe!"
95+ opts.SkipAuthRegex = []string{"/foo"}
96+ opts.Upstreams = []string{"static://444/foo"}
97+ opts.Logging.SilencePing = test.SilencePingLogging
98+ if test.SilencePingLogging {
99+ opts.Logging.ExcludePaths = []string{"/ping"}
100+ }
101+ opts.RawRedirectURL = "localhost"
102+ validation.Validate(opts)
103+
104+ p := NewOAuthProxy(opts, func(email string) bool {
105+ return true
106+ })
107+ p.provider = NewTestProvider(&url.URL{Host: "localhost"}, "")
108+
109+ buf := bytes.NewBuffer(nil)
110+ logger.SetOutput(buf)
111+ logger.SetReqEnabled(true)
112+ logger.SetReqTemplate("{{.StatusCode}}")
113+
114+ r, _ := http.NewRequest("GET", test.Path, nil)
115+ if test.WithUserAgent != "" {
116+ r.Header.Set("User-Agent", test.WithUserAgent)
117+ }
118+
119+ h := LoggingHandler(p)
120+ h.ServeHTTP(httptest.NewRecorder(), r)
121+
122+ actual := buf.String()
123+ if !strings.Contains(actual, test.ExpectedLogMessage) {
124+ t.Errorf("Log message was\n%s\ninstead of matching \n%s", actual, test.ExpectedLogMessage)
125+ }
126+ })
127+ }
128+}