git.iko.soy/typeable/oauth2-proxy
on master help sign in
Add tests for upstream package
5b95ed3Joel Speed
pkg/upstream/file_test.gonew file+58
@@ -0,0 +1,58 @@
1+package upstream
2+
3+import (
4+ "crypto/rand"
5+ "io"
6+ "net/http"
7+ "net/http/httptest"
8+ "os"
9+
10+ . "github.com/onsi/ginkgo"
11+ . "github.com/onsi/ginkgo/extensions/table"
12+ . "github.com/onsi/gomega"
13+)
14+
15+var _ = Describe("File Server Suite", func() {
16+ var dir string
17+ var handler http.Handler
18+ var id string
19+
20+ const (
21+ foo = "foo"
22+ bar = "bar"
23+ baz = "baz"
24+ pageNotFound = "404 page not found\n"
25+ )
26+
27+ BeforeEach(func() {
28+ // Generate a random id before each test to check the GAP-Upstream-Address
29+ // is being set correctly
30+ idBytes := make([]byte, 16)
31+ _, err := io.ReadFull(rand.Reader, idBytes)
32+ Expect(err).ToNot(HaveOccurred())
33+ id = string(idBytes)
34+
35+ handler = newFileServer(id, "/files", filesDir)
36+ })
37+
38+ AfterEach(func() {
39+ Expect(os.RemoveAll(dir)).To(Succeed())
40+ })
41+
42+ DescribeTable("fileServer ServeHTTP",
43+ func(requestPath string, expectedResponseCode int, expectedBody string) {
44+ req := httptest.NewRequest("", requestPath, nil)
45+ rw := httptest.NewRecorder()
46+ handler.ServeHTTP(rw, req)
47+
48+ Expect(rw.Header().Get("GAP-Upstream-Address")).To(Equal(id))
49+ Expect(rw.Code).To(Equal(expectedResponseCode))
50+ Expect(rw.Body.String()).To(Equal(expectedBody))
51+ },
52+ Entry("for file foo", "/files/foo", 200, foo),
53+ Entry("for file bar", "/files/bar", 200, bar),
54+ Entry("for file foo/baz", "/files/subdir/baz", 200, baz),
55+ Entry("for a non-existent file inside the path", "/files/baz", 404, pageNotFound),
56+ Entry("for a non-existent file oustide the path", "/baz", 404, pageNotFound),
57+ )
58+})
pkg/upstream/http.go+7−1
@@ -6,6 +6,7 @@ import (
6 "net/http/httputil"
6 "net/http/httputil"
7 "net/url"
7 "net/url"
8 "strings"
8 "strings"
9+ "time"
9
10
10 "github.com/mbland/hmacauth"
11 "github.com/mbland/hmacauth"
11 "github.com/oauth2-proxy/oauth2-proxy/pkg/apis/options"
12 "github.com/oauth2-proxy/oauth2-proxy/pkg/apis/options"
@@ -96,7 +97,12 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr
96 proxy := httputil.NewSingleHostReverseProxy(target)
97 proxy := httputil.NewSingleHostReverseProxy(target)
97
98
98 // Configure options on the SingleHostReverseProxy
99 // Configure options on the SingleHostReverseProxy
100+ if upstream.FlushInterval != nil {
99− proxy.FlushInterval = *upstream.FlushInterval
101+ proxy.FlushInterval = *upstream.FlushInterval
102+ } else {
103+ proxy.FlushInterval = 1 * time.Second
104+ }
105+
100 if upstream.InsecureSkipTLSVerify {
106 if upstream.InsecureSkipTLSVerify {
101 proxy.Transport = &http.Transport{
107 proxy.Transport = &http.Transport{
102 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
108 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
pkg/upstream/http_test.gonew file+417
@@ -0,0 +1,417 @@
1+package upstream
2+
3+import (
4+ "bytes"
5+ "crypto"
6+ "crypto/tls"
7+ "encoding/json"
8+ "fmt"
9+ "net/http"
10+ "net/http/httptest"
11+ "net/http/httputil"
12+ "net/url"
13+ "strings"
14+ "time"
15+
16+ "github.com/oauth2-proxy/oauth2-proxy/pkg/apis/options"
17+ . "github.com/onsi/ginkgo"
18+ . "github.com/onsi/ginkgo/extensions/table"
19+ . "github.com/onsi/gomega"
20+ "golang.org/x/net/websocket"
21+)
22+
23+var _ = Describe("HTTP Upstream Suite", func() {
24+
25+ const flushInterval5s = 5 * time.Second
26+ const flushInterval1s = 1 * time.Second
27+
28+ type httpUpstreamTableInput struct {
29+ id string
30+ serverAddr *string
31+ target string
32+ method string
33+ body []byte
34+ signatureData *options.SignatureData
35+ existingHeaders map[string]string
36+ expectedResponse testHTTPResponse
37+ errorHandler ProxyErrorHandler
38+ }
39+
40+ DescribeTable("HTTP Upstream ServeHTTP",
41+ func(in *httpUpstreamTableInput) {
42+ buf := bytes.NewBuffer(in.body)
43+ req := httptest.NewRequest(in.method, in.target, buf)
44+ // Don't mock the remote Address
45+ req.RemoteAddr = ""
46+
47+ for key, value := range in.existingHeaders {
48+ req.Header.Add(key, value)
49+ }
50+
51+ rw := httptest.NewRecorder()
52+
53+ flush := 1 * time.Second
54+ upstream := options.Upstream{
55+ ID: in.id,
56+ PassHostHeader: true,
57+ ProxyWebSockets: false,
58+ InsecureSkipTLSVerify: false,
59+ FlushInterval: &flush,
60+ }
61+
62+ Expect(in.serverAddr).ToNot(BeNil())
63+ u, err := url.Parse(*in.serverAddr)
64+ Expect(err).ToNot(HaveOccurred())
65+
66+ handler := newHTTPUpstreamProxy(upstream, u, in.signatureData, in.errorHandler)
67+ handler.ServeHTTP(rw, req)
68+
69+ Expect(rw.Code).To(Equal(in.expectedResponse.code))
70+
71+ // Delete extra headers that aren't relevant to tests
72+ testSanitizeResponseHeader(rw.Header())
73+ Expect(rw.Header()).To(Equal(in.expectedResponse.header))
74+
75+ body := rw.Body.Bytes()
76+ if in.expectedResponse.raw != "" || rw.Code != http.StatusOK {
77+ Expect(string(body)).To(Equal(in.expectedResponse.raw))
78+ return
79+ }
80+
81+ // Compare the reflected request to the upstream
82+ request := testHTTPRequest{}
83+ Expect(json.Unmarshal(body, &request)).To(Succeed())
84+ testSanitizeRequestHeader(request.Header)
85+ Expect(request).To(Equal(in.expectedResponse.request))
86+ },
87+ Entry("request a path on the server", &httpUpstreamTableInput{
88+ id: "default",
89+ serverAddr: &serverAddr,
90+ target: "http://example.localhost/foo",
91+ method: "GET",
92+ body: []byte{},
93+ errorHandler: nil,
94+ expectedResponse: testHTTPResponse{
95+ code: 200,
96+ header: map[string][]string{
97+ gapUpstream: {"default"},
98+ contentType: {applicationJSON},
99+ },
100+ request: testHTTPRequest{
101+ Method: "GET",
102+ URL: "http://example.localhost/foo",
103+ Header: map[string][]string{},
104+ Body: []byte{},
105+ Host: "example.localhost",
106+ RequestURI: "http://example.localhost/foo",
107+ },
108+ },
109+ }),
110+ Entry("request a path with encoded slashes", &httpUpstreamTableInput{
111+ id: "encodedSlashes",
112+ serverAddr: &serverAddr,
113+ target: "http://example.localhost/foo%2fbar/?baz=1",
114+ method: "GET",
115+ body: []byte{},
116+ errorHandler: nil,
117+ expectedResponse: testHTTPResponse{
118+ code: 200,
119+ header: map[string][]string{
120+ gapUpstream: {"encodedSlashes"},
121+ contentType: {applicationJSON},
122+ },
123+ request: testHTTPRequest{
124+ Method: "GET",
125+ URL: "http://example.localhost/foo%2fbar/?baz=1",
126+ Header: map[string][]string{},
127+ Body: []byte{},
128+ Host: "example.localhost",
129+ RequestURI: "http://example.localhost/foo%2fbar/?baz=1",
130+ },
131+ },
132+ }),
133+ Entry("when the request has a body", &httpUpstreamTableInput{
134+ id: "requestWithBody",
135+ serverAddr: &serverAddr,
136+ target: "http://example.localhost/withBody",
137+ method: "POST",
138+ body: []byte("body"),
139+ errorHandler: nil,
140+ expectedResponse: testHTTPResponse{
141+ code: 200,
142+ header: map[string][]string{
143+ gapUpstream: {"requestWithBody"},
144+ contentType: {applicationJSON},
145+ },
146+ request: testHTTPRequest{
147+ Method: "POST",
148+ URL: "http://example.localhost/withBody",
149+ Header: map[string][]string{
150+ contentLength: {"4"},
151+ },
152+ Body: []byte("body"),
153+ Host: "example.localhost",
154+ RequestURI: "http://example.localhost/withBody",
155+ },
156+ },
157+ }),
158+ Entry("when the upstream is unavailable", &httpUpstreamTableInput{
159+ id: "unavailableUpstream",
160+ serverAddr: &invalidServer,
161+ target: "http://example.localhost/unavailableUpstream",
162+ method: "GET",
163+ body: []byte{},
164+ errorHandler: nil,
165+ expectedResponse: testHTTPResponse{
166+ code: 502,
167+ header: map[string][]string{
168+ gapUpstream: {"unavailableUpstream"},
169+ },
170+ request: testHTTPRequest{},
171+ },
172+ }),
173+ Entry("when the upstream is unavailable and an error handler is set", &httpUpstreamTableInput{
174+ id: "withErrorHandler",
175+ serverAddr: &invalidServer,
176+ target: "http://example.localhost/withErrorHandler",
177+ method: "GET",
178+ body: []byte{},
179+ errorHandler: func(rw http.ResponseWriter, _ *http.Request, _ error) {
180+ rw.WriteHeader(502)
181+ rw.Write([]byte("error"))
182+ },
183+ expectedResponse: testHTTPResponse{
184+ code: 502,
185+ header: map[string][]string{
186+ gapUpstream: {"withErrorHandler"},
187+ },
188+ raw: "error",
189+ request: testHTTPRequest{},
190+ },
191+ }),
192+ Entry("with a signature", &httpUpstreamTableInput{
193+ id: "withSignature",
194+ serverAddr: &serverAddr,
195+ target: "http://example.localhost/withSignature",
196+ method: "GET",
197+ body: []byte{},
198+ signatureData: &options.SignatureData{
199+ Hash: crypto.SHA256,
200+ Key: "key",
201+ },
202+ errorHandler: nil,
203+ expectedResponse: testHTTPResponse{
204+ code: 200,
205+ header: map[string][]string{
206+ contentType: {applicationJSON},
207+ gapUpstream: {"withSignature"},
208+ },
209+ request: testHTTPRequest{
210+ Method: "GET",
211+ URL: "http://example.localhost/withSignature",
212+ Header: map[string][]string{
213+ gapAuth: {""},
214+ gapSignature: {"sha256 osMWI8Rr0Zr5HgNq6wakrgJITVJQMmFN1fXCesrqrmM="},
215+ },
216+ Body: []byte{},
217+ Host: "example.localhost",
218+ RequestURI: "http://example.localhost/withSignature",
219+ },
220+ },
221+ }),
222+ Entry("with existing headers", &httpUpstreamTableInput{
223+ id: "existingHeaders",
224+ serverAddr: &serverAddr,
225+ target: "http://example.localhost/existingHeaders",
226+ method: "GET",
227+ body: []byte{},
228+ errorHandler: nil,
229+ existingHeaders: map[string]string{
230+ "Header1": "value1",
231+ "Header2": "value2",
232+ },
233+ expectedResponse: testHTTPResponse{
234+ code: 200,
235+ header: map[string][]string{
236+ gapUpstream: {"existingHeaders"},
237+ contentType: {applicationJSON},
238+ },
239+ request: testHTTPRequest{
240+ Method: "GET",
241+ URL: "http://example.localhost/existingHeaders",
242+ Header: map[string][]string{
243+ "Header1": {"value1"},
244+ "Header2": {"value2"},
245+ },
246+ Body: []byte{},
247+ Host: "example.localhost",
248+ RequestURI: "http://example.localhost/existingHeaders",
249+ },
250+ },
251+ }),
252+ )
253+
254+ It("ServeHTTP, when not passing a host header", func() {
255+ req := httptest.NewRequest("", "http://example.localhost/foo", nil)
256+ rw := httptest.NewRecorder()
257+
258+ flush := 1 * time.Second
259+ upstream := options.Upstream{
260+ ID: "noPassHost",
261+ PassHostHeader: false,
262+ ProxyWebSockets: false,
263+ InsecureSkipTLSVerify: false,
264+ FlushInterval: &flush,
265+ }
266+
267+ u, err := url.Parse(serverAddr)
268+ Expect(err).ToNot(HaveOccurred())
269+
270+ handler := newHTTPUpstreamProxy(upstream, u, nil, nil)
271+ httpUpstream, ok := handler.(*httpUpstreamProxy)
272+ Expect(ok).To(BeTrue())
273+
274+ // Override the handler to just run the director and not actually send the request
275+ requestInterceptor := func(h http.Handler) http.Handler {
276+ return http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {
277+ proxy, ok := h.(*httputil.ReverseProxy)
278+ Expect(ok).To(BeTrue())
279+ proxy.Director(req)
280+ })
281+ }
282+ httpUpstream.handler = requestInterceptor(httpUpstream.handler)
283+
284+ httpUpstream.ServeHTTP(rw, req)
285+ Expect(req.Host).To(Equal(strings.TrimPrefix(serverAddr, "http://")))
286+ })
287+
288+ type newUpstreamTableInput struct {
289+ proxyWebSockets bool
290+ flushInterval time.Duration
291+ skipVerify bool
292+ sigData *options.SignatureData
293+ errorHandler func(http.ResponseWriter, *http.Request, error)
294+ }
295+
296+ DescribeTable("newHTTPUpstreamProxy",
297+ func(in *newUpstreamTableInput) {
298+ u, err := url.Parse("http://upstream:1234")
299+ Expect(err).ToNot(HaveOccurred())
300+
301+ upstream := options.Upstream{
302+ ID: "foo123",
303+ FlushInterval: &in.flushInterval,
304+ InsecureSkipTLSVerify: in.skipVerify,
305+ ProxyWebSockets: in.proxyWebSockets,
306+ }
307+
308+ handler := newHTTPUpstreamProxy(upstream, u, in.sigData, in.errorHandler)
309+ upstreamProxy, ok := handler.(*httpUpstreamProxy)
310+ Expect(ok).To(BeTrue())
311+
312+ Expect(upstreamProxy.auth != nil).To(Equal(in.sigData != nil))
313+ Expect(upstreamProxy.wsHandler != nil).To(Equal(in.proxyWebSockets))
314+ Expect(upstreamProxy.upstream).To(Equal(upstream.ID))
315+ Expect(upstreamProxy.handler).ToNot(BeNil())
316+
317+ proxy, ok := upstreamProxy.handler.(*httputil.ReverseProxy)
318+ Expect(ok).To(BeTrue())
319+ Expect(proxy.FlushInterval).To(Equal(in.flushInterval))
320+ Expect(proxy.ErrorHandler != nil).To(Equal(in.errorHandler != nil))
321+ if in.skipVerify {
322+ Expect(proxy.Transport).To(Equal(&http.Transport{
323+ TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
324+ }))
325+ }
326+ },
327+ Entry("with proxy websockets", &newUpstreamTableInput{
328+ proxyWebSockets: true,
329+ flushInterval: flushInterval1s,
330+ skipVerify: false,
331+ sigData: nil,
332+ errorHandler: nil,
333+ }),
334+ Entry("with a non standard flush interval", &newUpstreamTableInput{
335+ proxyWebSockets: false,
336+ flushInterval: flushInterval5s,
337+ skipVerify: false,
338+ sigData: nil,
339+ errorHandler: nil,
340+ }),
341+ Entry("with a InsecureSkipTLSVerify", &newUpstreamTableInput{
342+ proxyWebSockets: false,
343+ flushInterval: flushInterval1s,
344+ skipVerify: true,
345+ sigData: nil,
346+ errorHandler: nil,
347+ }),
348+ Entry("with a SignatureData", &newUpstreamTableInput{
349+ proxyWebSockets: false,
350+ flushInterval: flushInterval1s,
351+ skipVerify: false,
352+ sigData: &options.SignatureData{Hash: crypto.SHA256, Key: "secret"},
353+ errorHandler: nil,
354+ }),
355+ Entry("with an error handler", &newUpstreamTableInput{
356+ proxyWebSockets: false,
357+ flushInterval: flushInterval1s,
358+ skipVerify: false,
359+ sigData: nil,
360+ errorHandler: func(rw http.ResponseWriter, req *http.Request, arg3 error) {
361+ rw.WriteHeader(502)
362+ },
363+ }),
364+ )
365+
366+ Context("with a websocket proxy", func() {
367+ var proxyServer *httptest.Server
368+
369+ BeforeEach(func() {
370+ flush := 1 * time.Second
371+ upstream := options.Upstream{
372+ ID: "websocketProxy",
373+ PassHostHeader: true,
374+ ProxyWebSockets: true,
375+ InsecureSkipTLSVerify: false,
376+ FlushInterval: &flush,
377+ }
378+
379+ u, err := url.Parse(serverAddr)
380+ Expect(err).ToNot(HaveOccurred())
381+
382+ handler := newHTTPUpstreamProxy(upstream, u, nil, nil)
383+ proxyServer = httptest.NewServer(handler)
384+ })
385+
386+ AfterEach(func() {
387+ proxyServer.Close()
388+ })
389+
390+ It("will proxy websockets", func() {
391+ origin := "http://example.localhost"
392+ message := "Hello, world!"
393+
394+ proxyURL, err := url.Parse(fmt.Sprintf("http://%s", proxyServer.Listener.Addr().String()))
395+ Expect(err).ToNot(HaveOccurred())
396+
397+ wsAddr := fmt.Sprintf("ws://%s/", proxyURL.Host)
398+ ws, err := websocket.Dial(wsAddr, "", origin)
399+ Expect(err).ToNot(HaveOccurred())
400+
401+ Expect(websocket.Message.Send(ws, []byte(message))).To(Succeed())
402+ var response testWebSocketResponse
403+ Expect(websocket.JSON.Receive(ws, &response)).To(Succeed())
404+ Expect(response).To(Equal(testWebSocketResponse{
405+ Message: message,
406+ Origin: origin,
407+ }))
408+ })
409+
410+ It("will proxy HTTP requests", func() {
411+ response, err := http.Get(fmt.Sprintf("http://%s", proxyServer.Listener.Addr().String()))
412+ Expect(err).ToNot(HaveOccurred())
413+ Expect(response.StatusCode).To(Equal(200))
414+ Expect(response.Header.Get(gapUpstream)).To(Equal("websocketProxy"))
415+ })
416+ })
417+})
pkg/upstream/proxy_test.gonew file+182
@@ -0,0 +1,182 @@
1+package upstream
2+
3+import (
4+ "crypto"
5+ "encoding/json"
6+ "fmt"
7+ "html/template"
8+ "net/http"
9+ "net/http/httptest"
10+
11+ "github.com/oauth2-proxy/oauth2-proxy/pkg/apis/options"
12+ . "github.com/onsi/ginkgo"
13+ . "github.com/onsi/ginkgo/extensions/table"
14+ . "github.com/onsi/gomega"
15+)
16+
17+var _ = Describe("Proxy Suite", func() {
18+ var upstreamServer http.Handler
19+
20+ BeforeEach(func() {
21+ sigData := &options.SignatureData{Hash: crypto.SHA256, Key: "secret"}
22+
23+ tmpl, err := template.New("").Parse("{{ .Title }}\n{{ .Message }}\n{{ .ProxyPrefix }}")
24+ Expect(err).ToNot(HaveOccurred())
25+ errorHandler := NewProxyErrorHandler(tmpl, "prefix")
26+
27+ ok := http.StatusOK
28+
29+ upstreams := options.Upstreams{
30+ {
31+ ID: "http-backend",
32+ Path: "/http/",
33+ URI: serverAddr,
34+ },
35+ {
36+ ID: "file-backend",
37+ Path: "/files/",
38+ URI: fmt.Sprintf("file:///%s", filesDir),
39+ },
40+ {
41+ ID: "static-backend",
42+ Path: "/static/",
43+ Static: true,
44+ StaticCode: &ok,
45+ },
46+ {
47+ ID: "bad-http-backend",
48+ Path: "/bad-http/",
49+ URI: "http://::1",
50+ },
51+ {
52+ ID: "single-path-backend",
53+ Path: "/single-path",
54+ Static: true,
55+ StaticCode: &ok,
56+ },
57+ }
58+
59+ upstreamServer, err = NewProxy(upstreams, sigData, errorHandler)
60+ Expect(err).ToNot(HaveOccurred())
61+ })
62+
63+ type proxyTableInput struct {
64+ target string
65+ response testHTTPResponse
66+ }
67+
68+ DescribeTable("Proxy ServerHTTP",
69+ func(in *proxyTableInput) {
70+ req := httptest.NewRequest("", in.target, nil)
71+ rw := httptest.NewRecorder()
72+ // Don't mock the remote Address
73+ req.RemoteAddr = ""
74+
75+ upstreamServer.ServeHTTP(rw, req)
76+
77+ Expect(rw.Code).To(Equal(in.response.code))
78+
79+ // Delete extra headers that aren't relevant to tests
80+ testSanitizeResponseHeader(rw.Header())
81+ Expect(rw.Header()).To(Equal(in.response.header))
82+
83+ body := rw.Body.Bytes()
84+ // If the raw body is set, check that, else check the Request object
85+ if in.response.raw != "" {
86+ Expect(string(body)).To(Equal(in.response.raw))
87+ return
88+ }
89+
90+ // Compare the reflected request to the upstream
91+ request := testHTTPRequest{}
92+ Expect(json.Unmarshal(body, &request)).To(Succeed())
93+ testSanitizeRequestHeader(request.Header)
94+ Expect(request).To(Equal(in.response.request))
95+ },
96+ Entry("with a request to the HTTP service", &proxyTableInput{
97+ target: "http://example.localhost/http/1234",
98+ response: testHTTPResponse{
99+ code: 200,
100+ header: map[string][]string{
101+ gapUpstream: {"http-backend"},
102+ contentType: {applicationJSON},
103+ },
104+ request: testHTTPRequest{
105+ Method: "GET",
106+ URL: "http://example.localhost/http/1234",
107+ Header: map[string][]string{
108+ "Gap-Auth": {""},
109+ "Gap-Signature": {"sha256 ofB1u6+FhEUbFLc3/uGbJVkl7GaN4egFqVvyO3+2I1w="},
110+ },
111+ Body: []byte{},
112+ Host: "example.localhost",
113+ RequestURI: "http://example.localhost/http/1234",
114+ },
115+ },
116+ }),
117+ Entry("with a request to the File backend", &proxyTableInput{
118+ target: "http://example.localhost/files/foo",
119+ response: testHTTPResponse{
120+ code: 200,
121+ header: map[string][]string{
122+ contentType: {textPlainUTF8},
123+ gapUpstream: {"file-backend"},
124+ },
125+ raw: "foo",
126+ },
127+ }),
128+ Entry("with a request to the Static backend", &proxyTableInput{
129+ target: "http://example.localhost/static/bar",
130+ response: testHTTPResponse{
131+ code: 200,
132+ header: map[string][]string{
133+ gapUpstream: {"static-backend"},
134+ },
135+ raw: "Authenticated",
136+ },
137+ }),
138+ Entry("with a request to the bad HTTP backend", &proxyTableInput{
139+ target: "http://example.localhost/bad-http/bad",
140+ response: testHTTPResponse{
141+ code: 502,
142+ header: map[string][]string{
143+ gapUpstream: {"bad-http-backend"},
144+ },
145+ // This tests the error handler
146+ raw: "Bad Gateway\nError proxying to upstream server\nprefix",
147+ },
148+ }),
149+ Entry("with a request to the to an unregistered path", &proxyTableInput{
150+ target: "http://example.localhost/unregistered",
151+ response: testHTTPResponse{
152+ code: 404,
153+ header: map[string][]string{
154+ "X-Content-Type-Options": {"nosniff"},
155+ contentType: {textPlainUTF8},
156+ },
157+ raw: "404 page not found\n",
158+ },
159+ }),
160+ Entry("with a request to the to backend registered to a single path", &proxyTableInput{
161+ target: "http://example.localhost/single-path",
162+ response: testHTTPResponse{
163+ code: 200,
164+ header: map[string][]string{
165+ gapUpstream: {"single-path-backend"},
166+ },
167+ raw: "Authenticated",
168+ },
169+ }),
170+ Entry("with a request to the to a subpath of a backend registered to a single path", &proxyTableInput{
171+ target: "http://example.localhost/single-path/unregistered",
172+ response: testHTTPResponse{
173+ code: 404,
174+ header: map[string][]string{
175+ "X-Content-Type-Options": {"nosniff"},
176+ contentType: {textPlainUTF8},
177+ },
178+ raw: "404 page not found\n",
179+ },
180+ }),
181+ )
182+})
pkg/upstream/static_test.gonew file+81
@@ -0,0 +1,81 @@
1+package upstream
2+
3+import (
4+ "crypto/rand"
5+ "io"
6+ "net/http"
7+ "net/http/httptest"
8+
9+ . "github.com/onsi/ginkgo"
10+ . "github.com/onsi/ginkgo/extensions/table"
11+ . "github.com/onsi/gomega"
12+)
13+
14+var _ = Describe("Static Response Suite", func() {
15+ const authenticated = "Authenticated"
16+ var id string
17+
18+ BeforeEach(func() {
19+ // Generate a random id before each test to check the GAP-Upstream-Address
20+ // is being set correctly
21+ idBytes := make([]byte, 16)
22+ _, err := io.ReadFull(rand.Reader, idBytes)
23+ Expect(err).ToNot(HaveOccurred())
24+ id = string(idBytes)
25+ })
26+
27+ type serveHTTPTableInput struct {
28+ requestPath string
29+ staticCode int
30+ expectedBody string
31+ expectedCode int
32+ }
33+
34+ DescribeTable("staticResponse ServeHTTP",
35+ func(in *serveHTTPTableInput) {
36+ var code *int
37+ if in.staticCode != 0 {
38+ code = &in.staticCode
39+ }
40+ handler := newStaticResponseHandler(id, code)
41+
42+ req := httptest.NewRequest("", in.requestPath, nil)
43+ rw := httptest.NewRecorder()
44+ handler.ServeHTTP(rw, req)
45+
46+ Expect(rw.Header().Get("GAP-Upstream-Address")).To(Equal(id))
47+ Expect(rw.Code).To(Equal(in.expectedCode))
48+ Expect(rw.Body.String()).To(Equal(in.expectedBody))
49+ },
50+ Entry("with no given code", &serveHTTPTableInput{
51+ requestPath: "/",
52+ staticCode: 0, // Placeholder for nil
53+ expectedBody: authenticated,
54+ expectedCode: http.StatusOK,
55+ }),
56+ Entry("with status OK", &serveHTTPTableInput{
57+ requestPath: "/abc",
58+ staticCode: http.StatusOK,
59+ expectedBody: authenticated,
60+ expectedCode: http.StatusOK,
61+ }),
62+ Entry("with status NoContent", &serveHTTPTableInput{
63+ requestPath: "/def",
64+ staticCode: http.StatusNoContent,
65+ expectedBody: authenticated,
66+ expectedCode: http.StatusNoContent,
67+ }),
68+ Entry("with status NotFound", &serveHTTPTableInput{
69+ requestPath: "/ghi",
70+ staticCode: http.StatusNotFound,
71+ expectedBody: authenticated,
72+ expectedCode: http.StatusNotFound,
73+ }),
74+ Entry("with status Teapot", &serveHTTPTableInput{
75+ requestPath: "/jkl",
76+ staticCode: http.StatusTeapot,
77+ expectedBody: authenticated,
78+ expectedCode: http.StatusTeapot,
79+ }),
80+ )
81+})
pkg/upstream/upstream_suite_test.gonew file+180
@@ -0,0 +1,180 @@
1+package upstream
2+
3+import (
4+ "encoding/json"
5+ "fmt"
6+ "io/ioutil"
7+ "log"
8+ "net/http"
9+ "net/http/httptest"
10+ "os"
11+ "path"
12+ "testing"
13+
14+ "github.com/oauth2-proxy/oauth2-proxy/pkg/logger"
15+ . "github.com/onsi/ginkgo"
16+ . "github.com/onsi/gomega"
17+ "golang.org/x/net/websocket"
18+)
19+
20+var (
21+ filesDir string
22+ server *httptest.Server
23+ serverAddr string
24+ invalidServer = "http://::1"
25+)
26+
27+func TestUpstreamSuite(t *testing.T) {
28+ logger.SetOutput(GinkgoWriter)
29+ log.SetOutput(GinkgoWriter)
30+
31+ RegisterFailHandler(Fail)
32+ RunSpecs(t, "Upstream Suite")
33+}
34+
35+var _ = BeforeSuite(func() {
36+ // Set up files for serving via file servers
37+ dir, err := ioutil.TempDir("", "oauth2-proxy-upstream-suite")
38+ Expect(err).ToNot(HaveOccurred())
39+ Expect(ioutil.WriteFile(path.Join(dir, "foo"), []byte("foo"), 0644)).To(Succeed())
40+ Expect(ioutil.WriteFile(path.Join(dir, "bar"), []byte("bar"), 0644)).To(Succeed())
41+ Expect(os.Mkdir(path.Join(dir, "subdir"), os.ModePerm)).To(Succeed())
42+ Expect(ioutil.WriteFile(path.Join(dir, "subdir", "baz"), []byte("baz"), 0644)).To(Succeed())
43+ filesDir = dir
44+
45+ // Set up a webserver that reflects requests
46+ server = httptest.NewServer(&testHTTPUpstream{})
47+ serverAddr = fmt.Sprintf("http://%s", server.Listener.Addr().String())
48+})
49+
50+var _ = AfterSuite(func() {
51+ server.Close()
52+ Expect(os.RemoveAll(filesDir)).To(Succeed())
53+})
54+
55+const (
56+ contentType = "Content-Type"
57+ contentLength = "Content-Length"
58+ acceptEncoding = "Accept-Encoding"
59+ applicationJSON = "application/json"
60+ textPlainUTF8 = "text/plain; charset=utf-8"
61+ gapUpstream = "Gap-Upstream-Address"
62+ gapAuth = "Gap-Auth"
63+ gapSignature = "Gap-Signature"
64+)
65+
66+// testHTTPResponse is a struct used for checking responses in table tests
67+type testHTTPResponse struct {
68+ code int
69+ header http.Header
70+ raw string
71+ request testHTTPRequest
72+}
73+
74+// testHTTPRequest is a struct used to capture the state of a request made to
75+// an upstream during a test
76+type testHTTPRequest struct {
77+ Method string
78+ URL string
79+ Header http.Header
80+ Body []byte
81+ Host string
82+ RequestURI string
83+}
84+
85+type testWebSocketResponse struct {
86+ Message string
87+ Origin string
88+}
89+
90+type testHTTPUpstream struct{}
91+
92+func (t *testHTTPUpstream) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
93+ if req.Header.Get("Upgrade") == "websocket" {
94+ t.websocketHandler().ServeHTTP(rw, req)
95+ } else {
96+ t.serveHTTP(rw, req)
97+ }
98+}
99+
100+func (t *testHTTPUpstream) serveHTTP(rw http.ResponseWriter, req *http.Request) {
101+ request, err := toTestHTTPRequest(req)
102+ if err != nil {
103+ t.writeError(rw, err)
104+ return
105+ }
106+
107+ data, err := json.Marshal(request)
108+ if err != nil {
109+ t.writeError(rw, err)
110+ return
111+ }
112+
113+ rw.Header().Set("Content-Type", "application/json")
114+ rw.Write(data)
115+}
116+
117+func (t *testHTTPUpstream) websocketHandler() http.Handler {
118+ return websocket.Handler(func(ws *websocket.Conn) {
119+ defer ws.Close()
120+ var data []byte
121+ err := websocket.Message.Receive(ws, &data)
122+ if err != nil {
123+ websocket.Message.Send(ws, []byte(err.Error()))
124+ return
125+ }
126+
127+ wsResponse := testWebSocketResponse{
128+ Message: string(data),
129+ Origin: ws.Request().Header.Get("Origin"),
130+ }
131+ err = websocket.JSON.Send(ws, wsResponse)
132+ if err != nil {
133+ websocket.Message.Send(ws, []byte(err.Error()))
134+ return
135+ }
136+ })
137+}
138+
139+func (t *testHTTPUpstream) writeError(rw http.ResponseWriter, err error) {
140+ rw.WriteHeader(500)
141+ if err != nil {
142+ rw.Write([]byte(err.Error()))
143+ }
144+}
145+
146+func toTestHTTPRequest(req *http.Request) (testHTTPRequest, error) {
147+ requestBody := []byte{}
148+ if req.Body != http.NoBody {
149+ var err error
150+ requestBody, err = ioutil.ReadAll(req.Body)
151+ if err != nil {
152+ return testHTTPRequest{}, err
153+ }
154+ }
155+
156+ return testHTTPRequest{
157+ Method: req.Method,
158+ URL: req.URL.String(),
159+ Header: req.Header,
160+ Body: requestBody,
161+ Host: req.Host,
162+ RequestURI: req.RequestURI,
163+ }, nil
164+}
165+
166+// String headers added to the response that we do not want to test
167+func testSanitizeResponseHeader(h http.Header) {
168+ // From HTTP responses
169+ h.Del("Date")
170+ h.Del(contentLength)
171+
172+ // From File responses
173+ h.Del("Accept-Ranges")
174+ h.Del("Last-Modified")
175+}
176+
177+// Strip the accept header that is added by the HTTP Transport
178+func testSanitizeRequestHeader(h http.Header) {
179+ h.Del(acceptEncoding)
180+}