git.iko.soy/typeable/oauth2-proxy
on master help sign in
Merge branch 'master' into fix-set-basic-default
5fc6bd0Dan Bond
.golangci.yml+23−1
@@ -9,5 +9,27 @@ linters:
9 - deadcode
9 - deadcode
10 - gofmt
10 - gofmt
11 - goimports
11 - goimports
12− enable-all: false
12+ - gosimple
13+ - staticcheck
14+ - structcheck
15+ - typecheck
16+ - unused
17+ - varcheck
18+ - bodyclose
19+ - dogsled
20+ - goprintffuncname
21+ - misspell
22+ - prealloc
23+ - scopelint
24+ - stylecheck
25+ - unconvert
26+ - gocritic
13 disable-all: true
27 disable-all: true
28+issues:
29+ exclude-rules:
30+ - path: _test\.go
31+ linters:
32+ - scopelint
33+ - bodyclose
34+ - unconvert
35+ - gocritic
CHANGELOG.md+1
@@ -19,6 +19,7 @@
19
19
20## Changes since v5.1.0
20## Changes since v5.1.0
21
21
22+- [#486](https://github.com/oauth2-proxy/oauth2-proxy/pull/486) Add new linters (@johejo)
22- [#440](https://github.com/oauth2-proxy/oauth2-proxy/pull/440) Switch Azure AD Graph API to Microsoft Graph API (@johejo)
23- [#440](https://github.com/oauth2-proxy/oauth2-proxy/pull/440) Switch Azure AD Graph API to Microsoft Graph API (@johejo)
23- [#453](https://github.com/oauth2-proxy/oauth2-proxy/pull/453) Prevent browser caching during auth flow (@johejo)
24- [#453](https://github.com/oauth2-proxy/oauth2-proxy/pull/453) Prevent browser caching during auth flow (@johejo)
24- [#481](https://github.com/oauth2-proxy/oauth2-proxy/pull/481) Update Okta docs (@trevorbox)
25- [#481](https://github.com/oauth2-proxy/oauth2-proxy/pull/481) Update Okta docs (@trevorbox)
oauthproxy.go+6−10
@@ -324,8 +324,7 @@ func (p *OAuthProxy) GetRedirectURI(host string) string {
324 if p.redirectURL.Host != "" {
324 if p.redirectURL.Host != "" {
325 return p.redirectURL.String()
325 return p.redirectURL.String()
326 }
326 }
327− var u url.URL
328− u = *p.redirectURL
327+ u := *p.redirectURL
329 if u.Scheme == "" {
328 if u.Scheme == "" {
330 if p.CookieSecure {
329 if p.CookieSecure {
331 u.Scheme = httpsScheme
330 u.Scheme = httpsScheme
@@ -695,7 +694,7 @@ func (p *OAuthProxy) SignIn(rw http.ResponseWriter, req *http.Request) {
695 if ok {
694 if ok {
696 session := &sessionsapi.SessionState{User: user}
695 session := &sessionsapi.SessionState{User: user}
697 p.SaveSession(rw, req, session)
696 p.SaveSession(rw, req, session)
698− http.Redirect(rw, req, redirect, 302)
697+ http.Redirect(rw, req, redirect, http.StatusFound)
699 } else {
698 } else {
700 if p.SkipProviderButton {
699 if p.SkipProviderButton {
701 p.OAuthStart(rw, req)
700 p.OAuthStart(rw, req)
@@ -734,7 +733,7 @@ func (p *OAuthProxy) SignOut(rw http.ResponseWriter, req *http.Request) {
734 return
733 return
735 }
734 }
736 p.ClearSessionCookie(rw, req)
735 p.ClearSessionCookie(rw, req)
737− http.Redirect(rw, req, redirect, 302)
736+ http.Redirect(rw, req, redirect, http.StatusFound)
738}
737}
739
738
740// OAuthStart starts the OAuth2 authentication flow
739// OAuthStart starts the OAuth2 authentication flow
@@ -754,7 +753,7 @@ func (p *OAuthProxy) OAuthStart(rw http.ResponseWriter, req *http.Request) {
754 return
753 return
755 }
754 }
756 redirectURI := p.GetRedirectURI(req.Host)
755 redirectURI := p.GetRedirectURI(req.Host)
757− http.Redirect(rw, req, p.provider.GetLoginURL(redirectURI, fmt.Sprintf("%v:%v", nonce, redirect)), 302)
756+ http.Redirect(rw, req, p.provider.GetLoginURL(redirectURI, fmt.Sprintf("%v:%v", nonce, redirect)), http.StatusFound)
758}
757}
759
758
760// OAuthCallback is the OAuth2 authentication flow callback that finishes the
759// OAuthCallback is the OAuth2 authentication flow callback that finishes the
@@ -817,7 +816,7 @@ func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) {
817 p.ErrorPage(rw, 500, "Internal Error", "Internal Error")
816 p.ErrorPage(rw, 500, "Internal Error", "Internal Error")
818 return
817 return
819 }
818 }
820− http.Redirect(rw, req, redirect, 302)
819+ http.Redirect(rw, req, redirect, http.StatusFound)
821 } else {
820 } else {
822 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: unauthorized")
821 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: unauthorized")
823 p.ErrorPage(rw, 403, "Permission Denied", "Invalid Account")
822 p.ErrorPage(rw, 403, "Permission Denied", "Invalid Account")
@@ -1096,10 +1095,7 @@ func (p *OAuthProxy) CheckBasicAuth(req *http.Request) (*sessionsapi.SessionStat
1096
1095
1097// isAjax checks if a request is an ajax request
1096// isAjax checks if a request is an ajax request
1098func isAjax(req *http.Request) bool {
1097func isAjax(req *http.Request) bool {
1099− acceptValues, ok := req.Header["accept"]
1098+ acceptValues := req.Header.Values("Accept")
1100− if !ok {
1101− acceptValues = req.Header["Accept"]
1102− }
1103 const ajaxReq = applicationJSON
1099 const ajaxReq = applicationJSON
1104 for _, v := range acceptValues {
1100 for _, v := range acceptValues {
1105 if v == ajaxReq {
1101 if v == ajaxReq {
oauthproxy_test.go+13−17
@@ -64,7 +64,6 @@ func TestWebSocketProxy(t *testing.T) {
64 if err != nil {
64 if err != nil {
65 t.Fatalf("err %s", err)
65 t.Fatalf("err %s", err)
66 }
66 }
67− return
68 }),
67 }),
69 }
68 }
70 backend := httptest.NewServer(&handler)
69 backend := httptest.NewServer(&handler)
@@ -426,7 +425,7 @@ func TestBasicAuthPassword(t *testing.T) {
426 if rw.Code >= 400 {
425 if rw.Code >= 400 {
427 t.Fatalf("expected 3xx got %d", rw.Code)
426 t.Fatalf("expected 3xx got %d", rw.Code)
428 }
427 }
429− cookie := rw.HeaderMap["Set-Cookie"][1]
428+ cookie := rw.Header().Values("Set-Cookie")[1]
430
429
431 cookieName := proxy.CookieName
430 cookieName := proxy.CookieName
432 var value string
431 var value string
@@ -614,7 +613,7 @@ func (patTest *PassAccessTokenTest) getCallbackEndpoint() (httpCode int,
614 }
613 }
615 req.AddCookie(patTest.proxy.MakeCSRFCookie(req, "nonce", time.Hour, time.Now()))
614 req.AddCookie(patTest.proxy.MakeCSRFCookie(req, "nonce", time.Hour, time.Now()))
616 patTest.proxy.ServeHTTP(rw, req)
615 patTest.proxy.ServeHTTP(rw, req)
617− return rw.Code, rw.HeaderMap["Set-Cookie"][1]
616+ return rw.Code, rw.Header().Values("Set-Cookie")[1]
618}
617}
619
618
620// getEndpointWithCookie makes a requests againt the oauthproxy with passed requestPath
619// getEndpointWithCookie makes a requests againt the oauthproxy with passed requestPath
@@ -691,7 +690,7 @@ func TestStaticProxyUpstream(t *testing.T) {
691 }
690 }
692 assert.NotEqual(t, nil, cookie)
691 assert.NotEqual(t, nil, cookie)
693
692
694− // Now we make a regular request againts the upstream proxy; And validate
693+ // Now we make a regular request against the upstream proxy; And validate
695 // the returned status code through the static proxy.
694 // the returned status code through the static proxy.
696 code, payload := patTest.getEndpointWithCookie(cookie, "/static-proxy")
695 code, payload := patTest.getEndpointWithCookie(cookie, "/static-proxy")
697 if code != 200 {
696 if code != 200 {
@@ -824,8 +823,6 @@ type ProcessCookieTest struct {
824 proxy *OAuthProxy
823 proxy *OAuthProxy
825 rw *httptest.ResponseRecorder
824 rw *httptest.ResponseRecorder
826 req *http.Request
825 req *http.Request
827− provider TestProvider
828− responseCode int
829 validateUser bool
826 validateUser bool
830}
827}
831
828
@@ -910,7 +907,7 @@ func TestProcessCookieNoCookieError(t *testing.T) {
910 pcTest := NewProcessCookieTestWithDefaults()
907 pcTest := NewProcessCookieTestWithDefaults()
911
908
912 session, err := pcTest.LoadCookiedSession()
909 session, err := pcTest.LoadCookiedSession()
913− assert.Equal(t, "Cookie \"_oauth2_proxy\" not present", err.Error())
910+ assert.Equal(t, "cookie \"_oauth2_proxy\" not present", err.Error())
914 if session != nil {
911 if session != nil {
915 t.Errorf("expected nil session. got %#v", session)
912 t.Errorf("expected nil session. got %#v", session)
916 }
913 }
@@ -1072,8 +1069,8 @@ func TestAuthOnlyEndpointSetXAuthRequestHeaders(t *testing.T) {
1072
1069
1073 pcTest.proxy.ServeHTTP(pcTest.rw, pcTest.req)
1070 pcTest.proxy.ServeHTTP(pcTest.rw, pcTest.req)
1074 assert.Equal(t, http.StatusAccepted, pcTest.rw.Code)
1071 assert.Equal(t, http.StatusAccepted, pcTest.rw.Code)
1075− assert.Equal(t, "oauth_user", pcTest.rw.HeaderMap["X-Auth-Request-User"][0])
1072+ assert.Equal(t, "oauth_user", pcTest.rw.Header().Get("X-Auth-Request-User"))
1076− assert.Equal(t, "oauth_user@example.com", pcTest.rw.HeaderMap["X-Auth-Request-Email"][0])
1073+ assert.Equal(t, "oauth_user@example.com", pcTest.rw.Header().Get("X-Auth-Request-Email"))
1077}
1074}
1078
1075
1079func TestAuthOnlyEndpointSetBasicAuthTrueRequestHeaders(t *testing.T) {
1076func TestAuthOnlyEndpointSetBasicAuthTrueRequestHeaders(t *testing.T) {
@@ -1103,10 +1100,10 @@ func TestAuthOnlyEndpointSetBasicAuthTrueRequestHeaders(t *testing.T) {
1103
1100
1104 pcTest.proxy.ServeHTTP(pcTest.rw, pcTest.req)
1101 pcTest.proxy.ServeHTTP(pcTest.rw, pcTest.req)
1105 assert.Equal(t, http.StatusAccepted, pcTest.rw.Code)
1102 assert.Equal(t, http.StatusAccepted, pcTest.rw.Code)
1106− assert.Equal(t, "oauth_user", pcTest.rw.HeaderMap["X-Auth-Request-User"][0])
1103+ assert.Equal(t, "oauth_user", pcTest.rw.Header().Values("X-Auth-Request-User")[0])
1107− assert.Equal(t, "oauth_user@example.com", pcTest.rw.HeaderMap["X-Auth-Request-Email"][0])
1104+ assert.Equal(t, "oauth_user@example.com", pcTest.rw.Header().Values("X-Auth-Request-Email")[0])
1108 expectedHeader := "Basic " + base64.StdEncoding.EncodeToString([]byte("oauth_user:"+pcTest.opts.BasicAuthPassword))
1105 expectedHeader := "Basic " + base64.StdEncoding.EncodeToString([]byte("oauth_user:"+pcTest.opts.BasicAuthPassword))
1109− assert.Equal(t, expectedHeader, pcTest.rw.HeaderMap["Authorization"][0])
1106+ assert.Equal(t, expectedHeader, pcTest.rw.Header().Values("Authorization")[0])
1110}
1107}
1111
1108
1112func TestAuthOnlyEndpointSetBasicAuthFalseRequestHeaders(t *testing.T) {
1109func TestAuthOnlyEndpointSetBasicAuthFalseRequestHeaders(t *testing.T) {
@@ -1136,9 +1133,9 @@ func TestAuthOnlyEndpointSetBasicAuthFalseRequestHeaders(t *testing.T) {
1136
1133
1137 pcTest.proxy.ServeHTTP(pcTest.rw, pcTest.req)
1134 pcTest.proxy.ServeHTTP(pcTest.rw, pcTest.req)
1138 assert.Equal(t, http.StatusAccepted, pcTest.rw.Code)
1135 assert.Equal(t, http.StatusAccepted, pcTest.rw.Code)
1139− assert.Equal(t, "oauth_user", pcTest.rw.HeaderMap["X-Auth-Request-User"][0])
1136+ assert.Equal(t, "oauth_user", pcTest.rw.Header().Values("X-Auth-Request-User")[0])
1140− assert.Equal(t, "oauth_user@example.com", pcTest.rw.HeaderMap["X-Auth-Request-Email"][0])
1137+ assert.Equal(t, "oauth_user@example.com", pcTest.rw.Header().Values("X-Auth-Request-Email")[0])
1141− assert.Equal(t, 0, len(pcTest.rw.HeaderMap["Authorization"]), "should not have Authorization header entries")
1138+ assert.Equal(t, 0, len(pcTest.rw.Header().Values("Authorization")), "should not have Authorization header entries")
1142}
1139}
1143
1140
1144func TestAuthSkippedForPreflightRequests(t *testing.T) {
1141func TestAuthSkippedForPreflightRequests(t *testing.T) {
@@ -1462,8 +1459,7 @@ type NoOpKeySet struct {
1462func (NoOpKeySet) VerifySignature(ctx context.Context, jwt string) (payload []byte, err error) {
1459func (NoOpKeySet) VerifySignature(ctx context.Context, jwt string) (payload []byte, err error) {
1463 splitStrings := strings.Split(jwt, ".")
1460 splitStrings := strings.Split(jwt, ".")
1464 payloadString := splitStrings[1]
1461 payloadString := splitStrings[1]
1465− jsonString, err := base64.RawURLEncoding.DecodeString(payloadString)
1462+ return base64.RawURLEncoding.DecodeString(payloadString)
1466− return []byte(jsonString), err
1467}
1463}
1468
1464
1469func TestGetJwtSession(t *testing.T) {
1465func TestGetJwtSession(t *testing.T) {
options.go+4−4
@@ -290,7 +290,7 @@ func (o *Options) Validate() error {
290 }
290 }
291 }
291 }
292
292
293− if o.PreferEmailToUser == true && o.PassBasicAuth == false && o.PassUserHeaders == false {
293+ if o.PreferEmailToUser && !o.PassBasicAuth && !o.PassUserHeaders {
294 msgs = append(msgs, "PreferEmailToUser should only be used with PassBasicAuth or PassUserHeaders")
294 msgs = append(msgs, "PreferEmailToUser should only be used with PassBasicAuth or PassUserHeaders")
295 }
295 }
296
296
@@ -349,7 +349,7 @@ func (o *Options) Validate() error {
349 if string(secretBytes(o.CookieSecret)) != o.CookieSecret {
349 if string(secretBytes(o.CookieSecret)) != o.CookieSecret {
350 decoded = true
350 decoded = true
351 }
351 }
352− if validCookieSecretSize == false {
352+ if !validCookieSecretSize {
353 var suffix string
353 var suffix string
354 if decoded {
354 if decoded {
355 suffix = fmt.Sprintf(" note: cookie secret was base64 decoded from %q", o.CookieSecret)
355 suffix = fmt.Sprintf(" note: cookie secret was base64 decoded from %q", o.CookieSecret)
@@ -414,7 +414,7 @@ func (o *Options) Validate() error {
414 msgs = setupLogger(o, msgs)
414 msgs = setupLogger(o, msgs)
415
415
416 if len(msgs) != 0 {
416 if len(msgs) != 0 {
417− return fmt.Errorf("Invalid configuration:\n %s",
417+ return fmt.Errorf("invalid configuration:\n %s",
418 strings.Join(msgs, "\n "))
418 strings.Join(msgs, "\n "))
419 }
419 }
420 return nil
420 return nil
@@ -545,7 +545,7 @@ func parseSignatureKey(o *Options, msgs []string) []string {
545// parseJwtIssuers takes in an array of strings in the form of issuer=audience
545// parseJwtIssuers takes in an array of strings in the form of issuer=audience
546// and parses to an array of jwtIssuer structs.
546// and parses to an array of jwtIssuer structs.
547func parseJwtIssuers(issuers []string, msgs []string) ([]jwtIssuer, []string) {
547func parseJwtIssuers(issuers []string, msgs []string) ([]jwtIssuer, []string) {
548− var parsedIssuers []jwtIssuer
548+ parsedIssuers := make([]jwtIssuer, 0, len(issuers))
549 for _, jwtVerifier := range issuers {
549 for _, jwtVerifier := range issuers {
550 components := strings.Split(jwtVerifier, "=")
550 components := strings.Split(jwtVerifier, "=")
551 if len(components) < 2 {
551 if len(components) < 2 {
options_test.go+6−6
@@ -31,7 +31,7 @@ func testOptions() *Options {
31
31
32func errorMsg(msgs []string) string {
32func errorMsg(msgs []string) string {
33 result := make([]string, 0)
33 result := make([]string, 0)
34− result = append(result, "Invalid configuration:")
34+ result = append(result, "invalid configuration:")
35 result = append(result, msgs...)
35 result = append(result, msgs...)
36 return strings.Join(result, "\n ")
36 return strings.Join(result, "\n ")
37}
37}
@@ -278,7 +278,7 @@ func TestValidateSignatureKeyInvalidSpec(t *testing.T) {
278 o := testOptions()
278 o := testOptions()
279 o.SignatureKey = "invalid spec"
279 o.SignatureKey = "invalid spec"
280 err := o.Validate()
280 err := o.Validate()
281− assert.Equal(t, err.Error(), "Invalid configuration:\n"+
281+ assert.Equal(t, err.Error(), "invalid configuration:\n"+
282 " invalid signature hash:key spec: "+o.SignatureKey)
282 " invalid signature hash:key spec: "+o.SignatureKey)
283}
283}
284
284
@@ -286,7 +286,7 @@ func TestValidateSignatureKeyUnsupportedAlgorithm(t *testing.T) {
286 o := testOptions()
286 o := testOptions()
287 o.SignatureKey = "unsupported:default secret"
287 o.SignatureKey = "unsupported:default secret"
288 err := o.Validate()
288 err := o.Validate()
289− assert.Equal(t, err.Error(), "Invalid configuration:\n"+
289+ assert.Equal(t, err.Error(), "invalid configuration:\n"+
290 " unsupported signature hash algorithm: "+o.SignatureKey)
290 " unsupported signature hash algorithm: "+o.SignatureKey)
291}
291}
292
292
@@ -300,7 +300,7 @@ func TestValidateCookieBadName(t *testing.T) {
300 o := testOptions()
300 o := testOptions()
301 o.CookieName = "_bad_cookie_name{}"
301 o.CookieName = "_bad_cookie_name{}"
302 err := o.Validate()
302 err := o.Validate()
303− assert.Equal(t, err.Error(), "Invalid configuration:\n"+
303+ assert.Equal(t, err.Error(), "invalid configuration:\n"+
304 fmt.Sprintf(" invalid cookie name: %q", o.CookieName))
304 fmt.Sprintf(" invalid cookie name: %q", o.CookieName))
305}
305}
306
306
@@ -311,8 +311,8 @@ func TestSkipOIDCDiscovery(t *testing.T) {
311 o.SkipOIDCDiscovery = true
311 o.SkipOIDCDiscovery = true
312
312
313 err := o.Validate()
313 err := o.Validate()
314− assert.Equal(t, "Invalid configuration:\n"+
314+ assert.Equal(t, "invalid configuration:\n"+
315− fmt.Sprintf(" missing setting: login-url\n missing setting: redeem-url\n missing setting: oidc-jwks-url"), err.Error())
315+ " missing setting: login-url\n missing setting: redeem-url\n missing setting: oidc-jwks-url", err.Error())
316
316
317 o.LoginURL = "https://login.microsoftonline.com/fabrikamb2c.onmicrosoft.com/oauth2/v2.0/authorize?p=b2c_1_sign_in"
317 o.LoginURL = "https://login.microsoftonline.com/fabrikamb2c.onmicrosoft.com/oauth2/v2.0/authorize?p=b2c_1_sign_in"
318 o.RedeemURL = "https://login.microsoftonline.com/fabrikamb2c.onmicrosoft.com/oauth2/v2.0/token?p=b2c_1_sign_in"
318 o.RedeemURL = "https://login.microsoftonline.com/fabrikamb2c.onmicrosoft.com/oauth2/v2.0/token?p=b2c_1_sign_in"
pkg/logger/logger.go+5−5
@@ -139,10 +139,10 @@ func (l *Logger) Output(calldepth int, message string) {
139 l.writer.Write([]byte("\n"))
139 l.writer.Write([]byte("\n"))
140}
140}
141
141
142−// PrintAuth writes auth info to the logger. Requires an http.Request to
142+// PrintAuthf writes auth info to the logger. Requires an http.Request to
143// log request details. Remaining arguments are handled in the manner of
143// log request details. Remaining arguments are handled in the manner of
144// fmt.Sprintf. Writes a final newline to the end of every message.
144// fmt.Sprintf. Writes a final newline to the end of every message.
145−func (l *Logger) PrintAuth(username string, req *http.Request, status AuthStatus, format string, a ...interface{}) {
145+func (l *Logger) PrintAuthf(username string, req *http.Request, status AuthStatus, format string, a ...interface{}) {
146 if !l.authEnabled {
146 if !l.authEnabled {
147 return
147 return
148 }
148 }
@@ -166,7 +166,7 @@ func (l *Logger) PrintAuth(username string, req *http.Request, status AuthStatus
166 Timestamp: FormatTimestamp(now),
166 Timestamp: FormatTimestamp(now),
167 UserAgent: fmt.Sprintf("%q", req.UserAgent()),
167 UserAgent: fmt.Sprintf("%q", req.UserAgent()),
168 Username: username,
168 Username: username,
169− Status: fmt.Sprintf("%s", status),
169+ Status: string(status),
170 Message: fmt.Sprintf(format, a...),
170 Message: fmt.Sprintf(format, a...),
171 })
171 })
172
172
@@ -185,7 +185,7 @@ func (l *Logger) PrintReq(username, upstream string, req *http.Request, url url.
185 return
185 return
186 }
186 }
187
187
188− duration := float64(time.Now().Sub(ts)) / float64(time.Second)
188+ duration := float64(time.Since(ts)) / float64(time.Second)
189
189
190 if username == "" {
190 if username == "" {
191 username = "-"
191 username = "-"
@@ -481,7 +481,7 @@ func Panicln(v ...interface{}) {
481// PrintAuthf writes authentication details to the standard logger.
481// PrintAuthf writes authentication details to the standard logger.
482// Arguments are handled in the manner of fmt.Printf.
482// Arguments are handled in the manner of fmt.Printf.
483func PrintAuthf(username string, req *http.Request, status AuthStatus, format string, a ...interface{}) {
483func PrintAuthf(username string, req *http.Request, status AuthStatus, format string, a ...interface{}) {
484− std.PrintAuth(username, req, status, format, a...)
484+ std.PrintAuthf(username, req, status, format, a...)
485}
485}
486
486
487// PrintReq writes request details to the standard logger.
487// PrintReq writes request details to the standard logger.
pkg/requests/requests_test.go+2−2
@@ -88,9 +88,9 @@ func TestRequestUnparsedResponseUsingAccessTokenParameter(t *testing.T) {
88
88
89 response, err := RequestUnparsedResponse(
89 response, err := RequestUnparsedResponse(
90 backend.URL+"?access_token=my_token", nil)
90 backend.URL+"?access_token=my_token", nil)
91+ assert.Equal(t, nil, err)
91 defer response.Body.Close()
92 defer response.Body.Close()
92
93
93− assert.Equal(t, nil, err)
94 assert.Equal(t, 200, response.StatusCode)
94 assert.Equal(t, 200, response.StatusCode)
95 body, err := ioutil.ReadAll(response.Body)
95 body, err := ioutil.ReadAll(response.Body)
96 assert.Equal(t, nil, err)
96 assert.Equal(t, nil, err)
@@ -124,9 +124,9 @@ func TestRequestUnparsedResponseUsingHeaders(t *testing.T) {
124 headers := make(http.Header)
124 headers := make(http.Header)
125 headers.Set("Auth", "my_token")
125 headers.Set("Auth", "my_token")
126 response, err := RequestUnparsedResponse(backend.URL, headers)
126 response, err := RequestUnparsedResponse(backend.URL, headers)
127+ assert.Equal(t, nil, err)
127 defer response.Body.Close()
128 defer response.Body.Close()
128
129
129− assert.Equal(t, nil, err)
130 assert.Equal(t, 200, response.StatusCode)
130 assert.Equal(t, 200, response.StatusCode)
131 body, err := ioutil.ReadAll(response.Body)
131 body, err := ioutil.ReadAll(response.Body)
132 assert.Equal(t, nil, err)
132 assert.Equal(t, nil, err)
pkg/sessions/cookie/session_store.go+3−6
@@ -52,11 +52,11 @@ func (s *SessionStore) Load(req *http.Request) (*sessions.SessionState, error) {
52 c, err := loadCookie(req, s.CookieOptions.CookieName)
52 c, err := loadCookie(req, s.CookieOptions.CookieName)
53 if err != nil {
53 if err != nil {
54 // always http.ErrNoCookie
54 // always http.ErrNoCookie
55− return nil, fmt.Errorf("Cookie %q not present", s.CookieOptions.CookieName)
55+ return nil, fmt.Errorf("cookie %q not present", s.CookieOptions.CookieName)
56 }
56 }
57 val, _, ok := encryption.Validate(c, s.CookieOptions.CookieSecret, s.CookieOptions.CookieExpire)
57 val, _, ok := encryption.Validate(c, s.CookieOptions.CookieSecret, s.CookieOptions.CookieExpire)
58 if !ok {
58 if !ok {
59− return nil, errors.New("Cookie Signature not valid")
59+ return nil, errors.New("cookie signature not valid")
60 }
60 }
61
61
62 session, err := utils.SessionFromCookie(val, s.CookieCipher)
62 session, err := utils.SessionFromCookie(val, s.CookieCipher)
@@ -69,8 +69,6 @@ func (s *SessionStore) Load(req *http.Request) (*sessions.SessionState, error) {
69// Clear clears any saved session information by writing a cookie to
69// Clear clears any saved session information by writing a cookie to
70// clear the session
70// clear the session
71func (s *SessionStore) Clear(rw http.ResponseWriter, req *http.Request) error {
71func (s *SessionStore) Clear(rw http.ResponseWriter, req *http.Request) error {
72− var cookies []*http.Cookie
73−
74 // matches CookieName, CookieName_<number>
72 // matches CookieName, CookieName_<number>
75 var cookieNameRegex = regexp.MustCompile(fmt.Sprintf("^%s(_\\d+)?$", s.CookieOptions.CookieName))
73 var cookieNameRegex = regexp.MustCompile(fmt.Sprintf("^%s(_\\d+)?$", s.CookieOptions.CookieName))
76
74
@@ -79,7 +77,6 @@ func (s *SessionStore) Clear(rw http.ResponseWriter, req *http.Request) error {
79 clearCookie := s.makeCookie(req, c.Name, "", time.Hour*-1, time.Now())
77 clearCookie := s.makeCookie(req, c.Name, "", time.Hour*-1, time.Now())
80
78
81 http.SetCookie(rw, clearCookie)
79 http.SetCookie(rw, clearCookie)
82− cookies = append(cookies, clearCookie)
83 }
80 }
84 }
81 }
85
82
@@ -174,7 +171,7 @@ func loadCookie(req *http.Request, cookieName string) (*http.Cookie, error) {
174 }
171 }
175 }
172 }
176 if len(cookies) == 0 {
173 if len(cookies) == 0 {
177− return nil, fmt.Errorf("Could not find cookie %s", cookieName)
174+ return nil, fmt.Errorf("could not find cookie %s", cookieName)
178 }
175 }
179 return joinCookies(cookies)
176 return joinCookies(cookies)
180}
177}
pkg/sessions/redis/redis_store.go+3−3
@@ -79,7 +79,7 @@ func newRedisCmdable(opts options.RedisStoreOptions) (Client, error) {
79 return nil, fmt.Errorf("unable to parse redis url: %s", err)
79 return nil, fmt.Errorf("unable to parse redis url: %s", err)
80 }
80 }
81
81
82− if opts.RedisInsecureTLS != false {
82+ if opts.RedisInsecureTLS {
83 opt.TLSConfig.InsecureSkipVerify = true
83 opt.TLSConfig.InsecureSkipVerify = true
84 }
84 }
85
85
@@ -149,7 +149,7 @@ func (store *SessionStore) Load(req *http.Request) (*sessions.SessionState, erro
149
149
150 val, _, ok := encryption.Validate(requestCookie, store.CookieOptions.CookieSecret, store.CookieOptions.CookieExpire)
150 val, _, ok := encryption.Validate(requestCookie, store.CookieOptions.CookieSecret, store.CookieOptions.CookieExpire)
151 if !ok {
151 if !ok {
152− return nil, fmt.Errorf("Cookie Signature not valid")
152+ return nil, fmt.Errorf("cookie signature not valid")
153 }
153 }
154 ctx := req.Context()
154 ctx := req.Context()
155 session, err := store.loadSessionFromString(ctx, val)
155 session, err := store.loadSessionFromString(ctx, val)
@@ -209,7 +209,7 @@ func (store *SessionStore) Clear(rw http.ResponseWriter, req *http.Request) erro
209
209
210 val, _, ok := encryption.Validate(requestCookie, store.CookieOptions.CookieSecret, store.CookieOptions.CookieExpire)
210 val, _, ok := encryption.Validate(requestCookie, store.CookieOptions.CookieSecret, store.CookieOptions.CookieExpire)
211 if !ok {
211 if !ok {
212− return fmt.Errorf("Cookie Signature not valid")
212+ return fmt.Errorf("cookie signature not valid")
213 }
213 }
214
214
215 // We only return an error if we had an issue with redis
215 // We only return an error if we had an issue with redis
providers/bitbucket.go+2−2
@@ -116,7 +116,7 @@ func (p *BitbucketProvider) GetEmailAddress(s *sessions.SessionState) (string, e
116 break
116 break
117 }
117 }
118 }
118 }
119− if found != true {
119+ if !found {
120 logger.Print("team membership test failed, access denied")
120 logger.Print("team membership test failed, access denied")
121 return "", nil
121 return "", nil
122 }
122 }
@@ -147,7 +147,7 @@ func (p *BitbucketProvider) GetEmailAddress(s *sessions.SessionState) (string, e
147 break
147 break
148 }
148 }
149 }
149 }
150− if found != true {
150+ if !found {
151 logger.Print("repository access test failed, access denied")
151 logger.Print("repository access test failed, access denied")
152 return "", nil
152 return "", nil
153 }
153 }
providers/github.go+1−1
@@ -122,7 +122,7 @@ func (p *GitHubProvider) hasOrg(accessToken string) (bool, error) {
122 pn++
122 pn++
123 }
123 }
124
124
125− var presentOrgs []string
125+ presentOrgs := make([]string, 0, len(orgs))
126 for _, org := range orgs {
126 for _, org := range orgs {
127 if p.Org == org.Login {
127 if p.Org == org.Login {
128 logger.Printf("Found Github Organization: %q", org.Login)
128 logger.Printf("Found Github Organization: %q", org.Login)
providers/gitlab.go+1−5
@@ -222,11 +222,7 @@ func (p *GitLabProvider) createSessionState(ctx context.Context, token *oauth2.T
222func (p *GitLabProvider) ValidateSessionState(s *sessions.SessionState) bool {
222func (p *GitLabProvider) ValidateSessionState(s *sessions.SessionState) bool {
223 ctx := context.Background()
223 ctx := context.Background()
224 _, err := p.Verifier.Verify(ctx, s.IDToken)
224 _, err := p.Verifier.Verify(ctx, s.IDToken)
225− if err != nil {
225+ return err == nil
226− return false
227− }
228−
229− return true
230}
226}
231
227
232// GetEmailAddress returns the Account email address
228// GetEmailAddress returns the Account email address
providers/google.go+5−3
@@ -2,6 +2,7 @@ package providers
2
2
3import (
3import (
4 "bytes"
4 "bytes"
5+ "context"
5 "encoding/base64"
6 "encoding/base64"
6 "encoding/json"
7 "encoding/json"
7 "errors"
8 "errors"
@@ -15,10 +16,10 @@ import (
15
16
16 "github.com/oauth2-proxy/oauth2-proxy/pkg/apis/sessions"
17 "github.com/oauth2-proxy/oauth2-proxy/pkg/apis/sessions"
17 "github.com/oauth2-proxy/oauth2-proxy/pkg/logger"
18 "github.com/oauth2-proxy/oauth2-proxy/pkg/logger"
18− "golang.org/x/oauth2"
19 "golang.org/x/oauth2/google"
19 "golang.org/x/oauth2/google"
20 admin "google.golang.org/api/admin/directory/v1"
20 admin "google.golang.org/api/admin/directory/v1"
21 "google.golang.org/api/googleapi"
21 "google.golang.org/api/googleapi"
22+ "google.golang.org/api/option"
22)
23)
23
24
24// GoogleProvider represents an Google based Identity Provider
25// GoogleProvider represents an Google based Identity Provider
@@ -184,8 +185,9 @@ func getAdminService(adminEmail string, credentialsReader io.Reader) *admin.Serv
184 }
185 }
185 conf.Subject = adminEmail
186 conf.Subject = adminEmail
186
187
188+ ctx := context.Background()
187− client := conf.Client(oauth2.NoContext)
189+ client := conf.Client(ctx)
188− adminService, err := admin.New(client)
190+ adminService, err := admin.NewService(ctx, option.WithHTTPClient(client))
189 if err != nil {
191 if err != nil {
190 logger.Fatal(err)
192 logger.Fatal(err)
191 }
193 }
providers/keycloak.go+1−1
@@ -76,7 +76,7 @@ func (p *KeycloakProvider) GetEmailAddress(s *sessions.SessionState) (string, er
76 }
76 }
77 }
77 }
78
78
79− if found != true {
79+ if !found {
80 logger.Printf("group not found, access denied")
80 logger.Printf("group not found, access denied")
81 return "", nil
81 return "", nil
82 }
82 }
providers/logingov.go+2−3
@@ -183,7 +183,7 @@ func (p *LoginGovProvider) Redeem(redirectURL, code string) (s *sessions.Session
183 Issuer: p.ClientID,
183 Issuer: p.ClientID,
184 Subject: p.ClientID,
184 Subject: p.ClientID,
185 Audience: p.RedeemURL.String(),
185 Audience: p.RedeemURL.String(),
186− ExpiresAt: int64(time.Now().Add(time.Duration(5 * time.Minute)).Unix()),
186+ ExpiresAt: time.Now().Add(5 * time.Minute).Unix(),
187 Id: randSeq(32),
187 Id: randSeq(32),
188 }
188 }
189 token := jwt.NewWithClaims(jwt.GetSigningMethod("RS256"), claims)
189 token := jwt.NewWithClaims(jwt.GetSigningMethod("RS256"), claims)
@@ -260,8 +260,7 @@ func (p *LoginGovProvider) Redeem(redirectURL, code string) (s *sessions.Session
260
260
261// GetLoginURL overrides GetLoginURL to add login.gov parameters
261// GetLoginURL overrides GetLoginURL to add login.gov parameters
262func (p *LoginGovProvider) GetLoginURL(redirectURI, state string) string {
262func (p *LoginGovProvider) GetLoginURL(redirectURI, state string) string {
263− var a url.URL
264− a = *p.LoginURL
263+ a := *p.LoginURL
265 params, _ := url.ParseQuery(a.RawQuery)
264 params, _ := url.ParseQuery(a.RawQuery)
266 params.Set("redirect_uri", redirectURI)
265 params.Set("redirect_uri", redirectURI)
267 params.Set("approval_prompt", p.ApprovalPrompt)
266 params.Set("approval_prompt", p.ApprovalPrompt)
providers/oidc.go+1−5
@@ -180,11 +180,7 @@ func (p *OIDCProvider) createSessionState(token *oauth2.Token, idToken *oidc.IDT
180func (p *OIDCProvider) ValidateSessionState(s *sessions.SessionState) bool {
180func (p *OIDCProvider) ValidateSessionState(s *sessions.SessionState) bool {
181 ctx := context.Background()
181 ctx := context.Background()
182 _, err := p.Verifier.Verify(ctx, s.IDToken)
182 _, err := p.Verifier.Verify(ctx, s.IDToken)
183− if err != nil {
183+ return err == nil
184− return false
185− }
186−
187− return true
188}
184}
189
185
190func getOIDCHeader(accessToken string) http.Header {
186func getOIDCHeader(accessToken string) http.Header {
providers/oidc_test.go+6−1
@@ -62,6 +62,9 @@ type fakeKeySetStub struct{}
62
62
63func (fakeKeySetStub) VerifySignature(_ context.Context, jwt string) (payload []byte, err error) {
63func (fakeKeySetStub) VerifySignature(_ context.Context, jwt string) (payload []byte, err error) {
64 decodeString, err := base64.RawURLEncoding.DecodeString(strings.Split(jwt, ".")[1])
64 decodeString, err := base64.RawURLEncoding.DecodeString(strings.Split(jwt, ".")[1])
65+ if err != nil {
66+ return nil, err
67+ }
65 tokenClaims := &idTokenClaims{}
68 tokenClaims := &idTokenClaims{}
66 err = json.Unmarshal(decodeString, tokenClaims)
69 err = json.Unmarshal(decodeString, tokenClaims)
67
70
@@ -242,7 +245,9 @@ func TestOIDCProvider_findVerifiedIdToken(t *testing.T) {
242
245
243 verifiedIDToken, err := provider.findVerifiedIDToken(context.Background(), tokenWithIDToken)
246 verifiedIDToken, err := provider.findVerifiedIDToken(context.Background(), tokenWithIDToken)
244 assert.Equal(t, true, err == nil)
247 assert.Equal(t, true, err == nil)
248+ if verifiedIDToken == nil {
245− assert.Equal(t, true, verifiedIDToken != nil)
249+ t.Fatal("verifiedIDToken is nil")
250+ }
246 assert.Equal(t, defaultIDToken.Issuer, verifiedIDToken.Issuer)
251 assert.Equal(t, defaultIDToken.Issuer, verifiedIDToken.Issuer)
247 assert.Equal(t, defaultIDToken.Subject, verifiedIDToken.Subject)
252 assert.Equal(t, defaultIDToken.Subject, verifiedIDToken.Subject)
248
253
providers/provider_data.go+1−1
@@ -31,7 +31,7 @@ type ProviderData struct {
31// Data returns the ProviderData
31// Data returns the ProviderData
32func (p *ProviderData) Data() *ProviderData { return p }
32func (p *ProviderData) Data() *ProviderData { return p }
33
33
34−func (p *ProviderData) GetClientSecret() (ClientSecret string, err error) {
34+func (p *ProviderData) GetClientSecret() (clientSecret string, err error) {
35 if p.ClientSecret != "" || p.ClientSecretFile == "" {
35 if p.ClientSecret != "" || p.ClientSecretFile == "" {
36 return p.ClientSecret, nil
36 return p.ClientSecret, nil
37 }
37 }
providers/provider_default.go+1−2
@@ -86,8 +86,7 @@ func (p *ProviderData) Redeem(redirectURL, code string) (s *sessions.SessionStat
86
86
87// GetLoginURL with typical oauth parameters
87// GetLoginURL with typical oauth parameters
88func (p *ProviderData) GetLoginURL(redirectURI, state string) string {
88func (p *ProviderData) GetLoginURL(redirectURI, state string) string {
89− var a url.URL
90− a = *p.LoginURL
89+ a := *p.LoginURL
91 params, _ := url.ParseQuery(a.RawQuery)
90 params, _ := url.ParseQuery(a.RawQuery)
92 params.Set("redirect_uri", redirectURI)
91 params.Set("redirect_uri", redirectURI)
93 params.Add("acr_values", p.AcrValues)
92 params.Add("acr_values", p.AcrValues)
watcher.go+1−1
@@ -44,7 +44,7 @@ func WatchForUpdates(filename string, done <-chan bool, action func()) {
44 defer watcher.Close()
44 defer watcher.Close()
45 for {
45 for {
46 select {
46 select {
47− case _ = <-done:
47+ case <-done:
48 logger.Printf("Shutting down watcher for: %s", filename)
48 logger.Printf("Shutting down watcher for: %s", filename)
49 return
49 return
50 case event := <-watcher.Events:
50 case event := <-watcher.Events: