git.iko.soy/typeable/oauth2-proxy
on master help sign in
Merge branch 'master' into ap-gh-pagination-with-lastpage
commiteb89047e3a3544393852ae7c843f1cfa103e1e0f authortoshi-miura <toshihiko.miura@gmail.com> dateThu 24 Oct 2019, 11:23 (7 years ago) parent535f6b835f2ae9
10 files changed+105−22
.gitignore+1 .travis.yml−1 CHANGELOG.md+4−1 docs/configuration/configuration.md+1 http.go+11 http_test.go+50 main.go+3−2 options.go+2 pkg/requests/requests.go+15−6 pkg/requests/requests_test.go+18−12
.gitignore+1
@@ -16,6 +16,7 @@ release
1616# Folders
1717_obj
1818_test
19+.idea/
1920
2021# Architecture specific extensions/prefixes
2122*.[568vq]
.travis.yml−1
@@ -1,6 +1,5 @@
11language: go
22go:
3− - 1.12.x
43 - 1.13.x
54install:
65 # Fetch dependencies
CHANGELOG.md+4−1
@@ -3,11 +3,14 @@
33## Changes since v4.0.0
44
55- [#227](https://github.com/pusher/oauth2_proxy/pull/227) Add Keycloak provider (@Ofinka)
6+- [#259](https://github.com/pusher/oauth2_proxy/pull/259) Redirect to HTTPS (@jmickey)
67- [#273](https://github.com/pusher/oauth2_proxy/pull/273) Support Go 1.13 (@dio)
78- [#275](https://github.com/pusher/oauth2_proxy/pull/275) docker: build from debian buster (@syscll)
89- [#258](https://github.com/pusher/oauth2_proxy/pull/258) Add IDToken for Azure provider
910 - This PR adds the IDToken into the session for the Azure provider allowing requests to a backend to be identified as a specific user. As a consequence, if you are using a cookie to store the session the cookie will now exceed the 4kb size limit and be split into multiple cookies. This can cause problems when using nginx as a proxy, resulting in no cookie being passed at all. Either increase the proxy_buffer_size in nginx or implement the redis session storage (see https://pusher.github.io/oauth2_proxy/configuration#redis-storage)
10−- [#274](https://github.com/pusher/oauth2_proxy/pull/274) Supports many github teams with api pagination support (@toshi-miura, @apratina)
11+- [#274](https://github.com/pusher/oauth2_proxy/pull/274) Supports many github teams with api pagination support (@toshi-miura,@apratina)
12+- [#286](https://github.com/pusher/oauth2_proxy/pull/286) Requests.go updated with useful error messages (@biotom)
13+
1114
1215# v4.0.0
1316
docs/configuration/configuration.md+1
@@ -44,6 +44,7 @@ An example [oauth2_proxy.cfg]({{ site.gitweb }}/contrib/oauth2_proxy.cfg.example
4444| `-extra-jwt-issuers` | string | if `-skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | |
4545| `-exclude-logging-paths` | string | comma separated list of paths to exclude from logging, eg: `"/ping,/path2"` |`""` (no paths excluded) |
4646| `-flush-interval` | duration | period between flushing response buffers when streaming responses | `"1s"` |
47+| `-force-https` | bool | enforce https redirect | `false` |
4748| `-banner` | string | custom banner string. Use `"-"` to disable default banner. | |
4849| `-footer` | string | custom footer string. Use `"-"` to disable default footer. | |
4950| `-gcp-healthchecks` | bool | will enable `/liveness_check`, `/readiness_check`, and `/` (with the proper user-agent) endpoints that will make it work well with GCP App Engine and GKE Ingresses | false |
http.go+11
@@ -152,3 +152,14 @@ func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
152152 tc.SetKeepAlivePeriod(3 * time.Minute)
153153 return tc, nil
154154}
155+
156+func redirectToHTTPS(opts *Options, h http.Handler) http.Handler {
157+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
158+ proto := r.Header.Get("X-Forwarded-Proto")
159+ if opts.ForceHTTPS && (r.TLS == nil || (proto != "" && strings.ToLower(proto) != "https")) {
160+ http.Redirect(w, r, opts.HTTPSAddress, http.StatusPermanentRedirect)
161+ }
162+
163+ h.ServeHTTP(w, r)
164+ })
165+}
http_test.go+50
@@ -106,3 +106,53 @@ func TestGCPHealthcheckNotIngressPut(t *testing.T) {
106106
107107 assert.Equal(t, "test", rw.Body.String())
108108}
109+
110+func TestRedirectToHTTPSTrue(t *testing.T) {
111+ opts := NewOptions()
112+ opts.ForceHTTPS = true
113+ handler := func(w http.ResponseWriter, req *http.Request) {
114+ w.Write([]byte("test"))
115+ }
116+
117+ h := redirectToHTTPS(opts, http.HandlerFunc(handler))
118+ rw := httptest.NewRecorder()
119+ r, _ := http.NewRequest("GET", "/", nil)
120+ h.ServeHTTP(rw, r)
121+
122+ assert.Equal(t, http.StatusPermanentRedirect, rw.Code, "status code should be %d, got: %d", http.StatusPermanentRedirect, rw.Code)
123+}
124+
125+func TestRedirectToHTTPSFalse(t *testing.T) {
126+ opts := NewOptions()
127+ handler := func(w http.ResponseWriter, req *http.Request) {
128+ w.Write([]byte("test"))
129+ }
130+
131+ h := redirectToHTTPS(opts, http.HandlerFunc(handler))
132+ rw := httptest.NewRecorder()
133+ r, _ := http.NewRequest("GET", "/", nil)
134+ h.ServeHTTP(rw, r)
135+
136+ assert.Equal(t, http.StatusOK, rw.Code, "status code should be %d, got: %d", http.StatusOK, rw.Code)
137+}
138+
139+func TestRedirectNotWhenHTTPS(t *testing.T) {
140+ opts := NewOptions()
141+ opts.ForceHTTPS = true
142+ handler := func(w http.ResponseWriter, req *http.Request) {
143+ w.Write([]byte("test"))
144+ }
145+
146+ h := redirectToHTTPS(opts, http.HandlerFunc(handler))
147+ s := httptest.NewTLSServer(h)
148+ defer s.Close()
149+
150+ opts.HTTPSAddress = s.URL
151+ client := s.Client()
152+ res, err := client.Get(s.URL)
153+ if err != nil {
154+ t.Fatalf("request to test server failed with error: %v", err)
155+ }
156+
157+ assert.Equal(t, http.StatusOK, res.StatusCode, "status code should be %d, got: %d", http.StatusOK, res.StatusCode)
158+}
main.go+3−2
@@ -32,6 +32,7 @@ func main() {
3232
3333 flagSet.String("http-address", "127.0.0.1:4180", "[http://]<addr>:<port> or unix://<path> to listen on for HTTP clients")
3434 flagSet.String("https-address", ":443", "<addr>:<port> to listen on for HTTPS clients")
35+ flagSet.Bool("force-https", false, "force HTTPS redirect for HTTP requests")
3536 flagSet.String("tls-cert-file", "", "path to certificate file")
3637 flagSet.String("tls-key-file", "", "path to private key file")
3738 flagSet.String("redirect-url", "", "the OAuth Redirect URL. ie: \"https://internalapp.yourcompany.com/oauth2/callback\"")
@@ -185,9 +186,9 @@ func main() {
185186
186187 var handler http.Handler
187188 if opts.GCPHealthChecks {
188− handler = gcpHealthcheck(LoggingHandler(oauthproxy))
189+ handler = redirectToHTTPS(opts, gcpHealthcheck(LoggingHandler(oauthproxy)))
189190 } else {
190− handler = LoggingHandler(oauthproxy)
191+ handler = redirectToHTTPS(opts, LoggingHandler(oauthproxy))
191192 }
192193 s := &Server{
193194 Handler: handler,
options.go+2
@@ -34,6 +34,7 @@ type Options struct {
3434 ProxyWebSockets bool `flag:"proxy-websockets" cfg:"proxy_websockets" env:"OAUTH2_PROXY_PROXY_WEBSOCKETS"`
3535 HTTPAddress string `flag:"http-address" cfg:"http_address" env:"OAUTH2_PROXY_HTTP_ADDRESS"`
3636 HTTPSAddress string `flag:"https-address" cfg:"https_address" env:"OAUTH2_PROXY_HTTPS_ADDRESS"`
37+ ForceHTTPS bool `flag:"force-https" cfg:"force_https" env:"OAUTH2_PROXY_FORCE_HTTPS"`
3738 RedirectURL string `flag:"redirect-url" cfg:"redirect_url" env:"OAUTH2_PROXY_REDIRECT_URL"`
3839 ClientID string `flag:"client-id" cfg:"client_id" env:"OAUTH2_PROXY_CLIENT_ID"`
3940 ClientSecret string `flag:"client-secret" cfg:"client_secret" env:"OAUTH2_PROXY_CLIENT_SECRET"`
@@ -145,6 +146,7 @@ func NewOptions() *Options {
145146 ProxyWebSockets: true,
146147 HTTPAddress: "127.0.0.1:4180",
147148 HTTPSAddress: ":443",
149+ ForceHTTPS: false,
148150 DisplayHtpasswdForm: true,
149151 CookieOptions: options.CookieOptions{
150152 CookieName: "_oauth2_proxy",
pkg/requests/requests.go+15−6
@@ -18,17 +18,23 @@ func Request(req *http.Request) (*simplejson.Json, error) {
1818 return nil, err
1919 }
2020 body, err := ioutil.ReadAll(resp.Body)
21− resp.Body.Close()
21+ if body != nil {
22+ defer resp.Body.Close()
23+ }
24+
2225 logger.Printf("%d %s %s %s", resp.StatusCode, req.Method, req.URL, body)
26+
2327 if err != nil {
24− return nil, err
28+ return nil, fmt.Errorf("problem reading http request body: %w", err)
2529 }
30+
2631 if resp.StatusCode != 200 {
2732 return nil, fmt.Errorf("got %d %s", resp.StatusCode, body)
2833 }
34+
2935 data, err := simplejson.NewJson(body)
3036 if err != nil {
31− return nil, err
37+ return nil, fmt.Errorf("error unmarshalling json: %w", err)
3238 }
3339 return data, nil
3440}
@@ -41,10 +47,13 @@ func RequestJSON(req *http.Request, v interface{}) error {
4147 return err
4248 }
4349 body, err := ioutil.ReadAll(resp.Body)
44− resp.Body.Close()
50+ if body != nil {
51+ defer resp.Body.Close()
52+ }
53+
4554 logger.Printf("%d %s %s %s", resp.StatusCode, req.Method, req.URL, body)
4655 if err != nil {
47− return err
56+ return fmt.Errorf("error reading body from http response: %w", err)
4857 }
4958 if resp.StatusCode != 200 {
5059 return fmt.Errorf("got %d %s", resp.StatusCode, body)
@@ -56,7 +65,7 @@ func RequestJSON(req *http.Request, v interface{}) error {
5665func RequestUnparsedResponse(url string, header http.Header) (resp *http.Response, err error) {
5766 req, err := http.NewRequest("GET", url, nil)
5867 if err != nil {
59− return nil, err
68+ return nil, fmt.Errorf("error performing get request: %w", err)
6069 }
6170 req.Header = header
6271
pkg/requests/requests_test.go+18−12
@@ -8,20 +8,21 @@ import (
88 "testing"
99
1010 "github.com/bitly/go-simplejson"
11−
1211 "github.com/stretchr/testify/assert"
12+ "github.com/stretchr/testify/require"
1313)
1414
15−func testBackend(responseCode int, payload string) *httptest.Server {
15+func testBackend(t *testing.T, responseCode int, payload string) *httptest.Server {
1616 return httptest.NewServer(http.HandlerFunc(
1717 func(w http.ResponseWriter, r *http.Request) {
1818 w.WriteHeader(responseCode)
19− w.Write([]byte(payload))
19+ _, err := w.Write([]byte(payload))
20+ require.NoError(t, err)
2021 }))
2122}
2223
2324func TestRequest(t *testing.T) {
24− backend := testBackend(200, "{\"foo\": \"bar\"}")
25+ backend := testBackend(t, 200, "{\"foo\": \"bar\"}")
2526 defer backend.Close()
2627
2728 req, _ := http.NewRequest("GET", backend.URL, nil)
@@ -35,7 +36,7 @@ func TestRequest(t *testing.T) {
3536func TestRequestFailure(t *testing.T) {
3637 // Create a backend to generate a test URL, then close it to cause a
3738 // connection error.
38− backend := testBackend(200, "{\"foo\": \"bar\"}")
39+ backend := testBackend(t, 200, "{\"foo\": \"bar\"}")
3940 backend.Close()
4041
4142 req, err := http.NewRequest("GET", backend.URL, nil)
@@ -49,7 +50,7 @@ func TestRequestFailure(t *testing.T) {
4950}
5051
5152func TestHttpErrorCode(t *testing.T) {
52− backend := testBackend(404, "{\"foo\": \"bar\"}")
53+ backend := testBackend(t, 404, "{\"foo\": \"bar\"}")
5354 defer backend.Close()
5455
5556 req, err := http.NewRequest("GET", backend.URL, nil)
@@ -60,7 +61,7 @@ func TestHttpErrorCode(t *testing.T) {
6061}
6162
6263func TestJsonParsingError(t *testing.T) {
63− backend := testBackend(200, "not well-formed JSON")
64+ backend := testBackend(t, 200, "not well-formed JSON")
6465 defer backend.Close()
6566
6667 req, err := http.NewRequest("GET", backend.URL, nil)
@@ -77,7 +78,8 @@ func TestRequestUnparsedResponseUsingAccessTokenParameter(t *testing.T) {
7778 token := r.FormValue("access_token")
7879 if r.URL.Path == "/" && token == "my_token" {
7980 w.WriteHeader(200)
80− w.Write([]byte("some payload"))
81+ _, err := w.Write([]byte("some payload"))
82+ require.NoError(t, err)
8183 } else {
8284 w.WriteHeader(403)
8385 }
@@ -86,16 +88,17 @@ func TestRequestUnparsedResponseUsingAccessTokenParameter(t *testing.T) {
8688
8789 response, err := RequestUnparsedResponse(
8890 backend.URL+"?access_token=my_token", nil)
91+ defer response.Body.Close()
92+
8993 assert.Equal(t, nil, err)
9094 assert.Equal(t, 200, response.StatusCode)
9195 body, err := ioutil.ReadAll(response.Body)
9296 assert.Equal(t, nil, err)
93− response.Body.Close()
9497 assert.Equal(t, "some payload", string(body))
9598}
9699
97100func TestRequestUnparsedResponseUsingAccessTokenParameterFailedResponse(t *testing.T) {
98− backend := testBackend(200, "some payload")
101+ backend := testBackend(t, 200, "some payload")
99102 // Close the backend now to force a request failure.
100103 backend.Close()
101104
@@ -110,7 +113,8 @@ func TestRequestUnparsedResponseUsingHeaders(t *testing.T) {
110113 func(w http.ResponseWriter, r *http.Request) {
111114 if r.URL.Path == "/" && r.Header["Auth"][0] == "my_token" {
112115 w.WriteHeader(200)
113− w.Write([]byte("some payload"))
116+ _, err := w.Write([]byte("some payload"))
117+ require.NoError(t, err)
114118 } else {
115119 w.WriteHeader(403)
116120 }
@@ -120,10 +124,12 @@ func TestRequestUnparsedResponseUsingHeaders(t *testing.T) {
120124 headers := make(http.Header)
121125 headers.Set("Auth", "my_token")
122126 response, err := RequestUnparsedResponse(backend.URL, headers)
127+ defer response.Body.Close()
128+
123129 assert.Equal(t, nil, err)
124130 assert.Equal(t, 200, response.StatusCode)
125131 body, err := ioutil.ReadAll(response.Body)
126132 assert.Equal(t, nil, err)
127− response.Body.Close()
133+
128134 assert.Equal(t, "some payload", string(body))
129135}