git.iko.soy/typeable/oauth2-proxy
on master help sign in
Merge branch 'master' into fix-set-basic-default
commit5fc6bd0e6ff3eb7fd7ed2341caca1f20fa63e1a5 authorDan Bond <pm@danbond.io> dateTue 14 Apr 2020, 09:37 (7 years ago) parent581475fdd05e7f
21 files changed+88−79
.golangci.yml+23−1 CHANGELOG.md+1 oauthproxy.go+6−10 oauthproxy_test.go+13−17 options.go+4−4 options_test.go+6−6 pkg/logger/logger.go+5−5 pkg/requests/requests_test.go+2−2 pkg/sessions/cookie/session_store.go+3−6 pkg/sessions/redis/redis_store.go+3−3 providers/bitbucket.go+2−2 providers/github.go+1−1 providers/gitlab.go+1−5 providers/google.go+5−3 providers/keycloak.go+1−1 providers/logingov.go+2−3 providers/oidc.go+1−5 providers/oidc_test.go+6−1 providers/provider_data.go+1−1 providers/provider_default.go+1−2 watcher.go+1−1
.golangci.yml+23−1
@@ -9,5 +9,27 @@ linters:
99 - deadcode
1010 - gofmt
1111 - 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
1327 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 @@
1919
2020## Changes since v5.1.0
2121
22+- [#486](https://github.com/oauth2-proxy/oauth2-proxy/pull/486) Add new linters (@johejo)
2223- [#440](https://github.com/oauth2-proxy/oauth2-proxy/pull/440) Switch Azure AD Graph API to Microsoft Graph API (@johejo)
2324- [#453](https://github.com/oauth2-proxy/oauth2-proxy/pull/453) Prevent browser caching during auth flow (@johejo)
2425- [#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 {
324324 if p.redirectURL.Host != "" {
325325 return p.redirectURL.String()
326326 }
327− var u url.URL
328− u = *p.redirectURL
327+ u := *p.redirectURL
329328 if u.Scheme == "" {
330329 if p.CookieSecure {
331330 u.Scheme = httpsScheme
@@ -695,7 +694,7 @@ func (p *OAuthProxy) SignIn(rw http.ResponseWriter, req *http.Request) {
695694 if ok {
696695 session := &sessionsapi.SessionState{User: user}
697696 p.SaveSession(rw, req, session)
698− http.Redirect(rw, req, redirect, 302)
697+ http.Redirect(rw, req, redirect, http.StatusFound)
699698 } else {
700699 if p.SkipProviderButton {
701700 p.OAuthStart(rw, req)
@@ -734,7 +733,7 @@ func (p *OAuthProxy) SignOut(rw http.ResponseWriter, req *http.Request) {
734733 return
735734 }
736735 p.ClearSessionCookie(rw, req)
737− http.Redirect(rw, req, redirect, 302)
736+ http.Redirect(rw, req, redirect, http.StatusFound)
738737}
739738
740739// OAuthStart starts the OAuth2 authentication flow
@@ -754,7 +753,7 @@ func (p *OAuthProxy) OAuthStart(rw http.ResponseWriter, req *http.Request) {
754753 return
755754 }
756755 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)
758757}
759758
760759// OAuthCallback is the OAuth2 authentication flow callback that finishes the
@@ -817,7 +816,7 @@ func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) {
817816 p.ErrorPage(rw, 500, "Internal Error", "Internal Error")
818817 return
819818 }
820− http.Redirect(rw, req, redirect, 302)
819+ http.Redirect(rw, req, redirect, http.StatusFound)
821820 } else {
822821 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: unauthorized")
823822 p.ErrorPage(rw, 403, "Permission Denied", "Invalid Account")
@@ -1096,10 +1095,7 @@ func (p *OAuthProxy) CheckBasicAuth(req *http.Request) (*sessionsapi.SessionStat
10961095
10971096// isAjax checks if a request is an ajax request
10981097func isAjax(req *http.Request) bool {
1099− acceptValues, ok := req.Header["accept"]
1100− if !ok {
1101− acceptValues = req.Header["Accept"]
1102− }
1098+ acceptValues := req.Header.Values("Accept")
11031099 const ajaxReq = applicationJSON
11041100 for _, v := range acceptValues {
11051101 if v == ajaxReq {
oauthproxy_test.go+13−17
@@ -64,7 +64,6 @@ func TestWebSocketProxy(t *testing.T) {
6464 if err != nil {
6565 t.Fatalf("err %s", err)
6666 }
67− return
6867 }),
6968 }
7069 backend := httptest.NewServer(&handler)
@@ -426,7 +425,7 @@ func TestBasicAuthPassword(t *testing.T) {
426425 if rw.Code >= 400 {
427426 t.Fatalf("expected 3xx got %d", rw.Code)
428427 }
429− cookie := rw.HeaderMap["Set-Cookie"][1]
428+ cookie := rw.Header().Values("Set-Cookie")[1]
430429
431430 cookieName := proxy.CookieName
432431 var value string
@@ -614,7 +613,7 @@ func (patTest *PassAccessTokenTest) getCallbackEndpoint() (httpCode int,
614613 }
615614 req.AddCookie(patTest.proxy.MakeCSRFCookie(req, "nonce", time.Hour, time.Now()))
616615 patTest.proxy.ServeHTTP(rw, req)
617− return rw.Code, rw.HeaderMap["Set-Cookie"][1]
616+ return rw.Code, rw.Header().Values("Set-Cookie")[1]
618617}
619618
620619// getEndpointWithCookie makes a requests againt the oauthproxy with passed requestPath
@@ -691,7 +690,7 @@ func TestStaticProxyUpstream(t *testing.T) {
691690 }
692691 assert.NotEqual(t, nil, cookie)
693692
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
695694 // the returned status code through the static proxy.
696695 code, payload := patTest.getEndpointWithCookie(cookie, "/static-proxy")
697696 if code != 200 {
@@ -824,8 +823,6 @@ type ProcessCookieTest struct {
824823 proxy *OAuthProxy
825824 rw *httptest.ResponseRecorder
826825 req *http.Request
827− provider TestProvider
828− responseCode int
829826 validateUser bool
830827}
831828
@@ -910,7 +907,7 @@ func TestProcessCookieNoCookieError(t *testing.T) {
910907 pcTest := NewProcessCookieTestWithDefaults()
911908
912909 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())
914911 if session != nil {
915912 t.Errorf("expected nil session. got %#v", session)
916913 }
@@ -1072,8 +1069,8 @@ func TestAuthOnlyEndpointSetXAuthRequestHeaders(t *testing.T) {
10721069
10731070 pcTest.proxy.ServeHTTP(pcTest.rw, pcTest.req)
10741071 assert.Equal(t, http.StatusAccepted, pcTest.rw.Code)
1075− assert.Equal(t, "oauth_user", pcTest.rw.HeaderMap["X-Auth-Request-User"][0])
1076− assert.Equal(t, "oauth_user@example.com", pcTest.rw.HeaderMap["X-Auth-Request-Email"][0])
1072+ assert.Equal(t, "oauth_user", pcTest.rw.Header().Get("X-Auth-Request-User"))
1073+ assert.Equal(t, "oauth_user@example.com", pcTest.rw.Header().Get("X-Auth-Request-Email"))
10771074}
10781075
10791076func TestAuthOnlyEndpointSetBasicAuthTrueRequestHeaders(t *testing.T) {
@@ -1103,10 +1100,10 @@ func TestAuthOnlyEndpointSetBasicAuthTrueRequestHeaders(t *testing.T) {
11031100
11041101 pcTest.proxy.ServeHTTP(pcTest.rw, pcTest.req)
11051102 assert.Equal(t, http.StatusAccepted, pcTest.rw.Code)
1106− assert.Equal(t, "oauth_user", pcTest.rw.HeaderMap["X-Auth-Request-User"][0])
1107− assert.Equal(t, "oauth_user@example.com", pcTest.rw.HeaderMap["X-Auth-Request-Email"][0])
1103+ assert.Equal(t, "oauth_user", pcTest.rw.Header().Values("X-Auth-Request-User")[0])
1104+ assert.Equal(t, "oauth_user@example.com", pcTest.rw.Header().Values("X-Auth-Request-Email")[0])
11081105 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])
11101107}
11111108
11121109func TestAuthOnlyEndpointSetBasicAuthFalseRequestHeaders(t *testing.T) {
@@ -1136,9 +1133,9 @@ func TestAuthOnlyEndpointSetBasicAuthFalseRequestHeaders(t *testing.T) {
11361133
11371134 pcTest.proxy.ServeHTTP(pcTest.rw, pcTest.req)
11381135 assert.Equal(t, http.StatusAccepted, pcTest.rw.Code)
1139− assert.Equal(t, "oauth_user", pcTest.rw.HeaderMap["X-Auth-Request-User"][0])
1140− assert.Equal(t, "oauth_user@example.com", pcTest.rw.HeaderMap["X-Auth-Request-Email"][0])
1141− assert.Equal(t, 0, len(pcTest.rw.HeaderMap["Authorization"]), "should not have Authorization header entries")
1136+ assert.Equal(t, "oauth_user", pcTest.rw.Header().Values("X-Auth-Request-User")[0])
1137+ assert.Equal(t, "oauth_user@example.com", pcTest.rw.Header().Values("X-Auth-Request-Email")[0])
1138+ assert.Equal(t, 0, len(pcTest.rw.Header().Values("Authorization")), "should not have Authorization header entries")
11421139}
11431140
11441141func TestAuthSkippedForPreflightRequests(t *testing.T) {
@@ -1462,8 +1459,7 @@ type NoOpKeySet struct {
14621459func (NoOpKeySet) VerifySignature(ctx context.Context, jwt string) (payload []byte, err error) {
14631460 splitStrings := strings.Split(jwt, ".")
14641461 payloadString := splitStrings[1]
1465− jsonString, err := base64.RawURLEncoding.DecodeString(payloadString)
1466− return []byte(jsonString), err
1462+ return base64.RawURLEncoding.DecodeString(payloadString)
14671463}
14681464
14691465func TestGetJwtSession(t *testing.T) {
options.go+4−4
@@ -290,7 +290,7 @@ func (o *Options) Validate() error {
290290 }
291291 }
292292
293− if o.PreferEmailToUser == true && o.PassBasicAuth == false && o.PassUserHeaders == false {
293+ if o.PreferEmailToUser && !o.PassBasicAuth && !o.PassUserHeaders {
294294 msgs = append(msgs, "PreferEmailToUser should only be used with PassBasicAuth or PassUserHeaders")
295295 }
296296
@@ -349,7 +349,7 @@ func (o *Options) Validate() error {
349349 if string(secretBytes(o.CookieSecret)) != o.CookieSecret {
350350 decoded = true
351351 }
352− if validCookieSecretSize == false {
352+ if !validCookieSecretSize {
353353 var suffix string
354354 if decoded {
355355 suffix = fmt.Sprintf(" note: cookie secret was base64 decoded from %q", o.CookieSecret)
@@ -414,7 +414,7 @@ func (o *Options) Validate() error {
414414 msgs = setupLogger(o, msgs)
415415
416416 if len(msgs) != 0 {
417− return fmt.Errorf("Invalid configuration:\n %s",
417+ return fmt.Errorf("invalid configuration:\n %s",
418418 strings.Join(msgs, "\n "))
419419 }
420420 return nil
@@ -545,7 +545,7 @@ func parseSignatureKey(o *Options, msgs []string) []string {
545545// parseJwtIssuers takes in an array of strings in the form of issuer=audience
546546// and parses to an array of jwtIssuer structs.
547547func parseJwtIssuers(issuers []string, msgs []string) ([]jwtIssuer, []string) {
548− var parsedIssuers []jwtIssuer
548+ parsedIssuers := make([]jwtIssuer, 0, len(issuers))
549549 for _, jwtVerifier := range issuers {
550550 components := strings.Split(jwtVerifier, "=")
551551 if len(components) < 2 {
options_test.go+6−6
@@ -31,7 +31,7 @@ func testOptions() *Options {
3131
3232func errorMsg(msgs []string) string {
3333 result := make([]string, 0)
34− result = append(result, "Invalid configuration:")
34+ result = append(result, "invalid configuration:")
3535 result = append(result, msgs...)
3636 return strings.Join(result, "\n ")
3737}
@@ -278,7 +278,7 @@ func TestValidateSignatureKeyInvalidSpec(t *testing.T) {
278278 o := testOptions()
279279 o.SignatureKey = "invalid spec"
280280 err := o.Validate()
281− assert.Equal(t, err.Error(), "Invalid configuration:\n"+
281+ assert.Equal(t, err.Error(), "invalid configuration:\n"+
282282 " invalid signature hash:key spec: "+o.SignatureKey)
283283}
284284
@@ -286,7 +286,7 @@ func TestValidateSignatureKeyUnsupportedAlgorithm(t *testing.T) {
286286 o := testOptions()
287287 o.SignatureKey = "unsupported:default secret"
288288 err := o.Validate()
289− assert.Equal(t, err.Error(), "Invalid configuration:\n"+
289+ assert.Equal(t, err.Error(), "invalid configuration:\n"+
290290 " unsupported signature hash algorithm: "+o.SignatureKey)
291291}
292292
@@ -300,7 +300,7 @@ func TestValidateCookieBadName(t *testing.T) {
300300 o := testOptions()
301301 o.CookieName = "_bad_cookie_name{}"
302302 err := o.Validate()
303− assert.Equal(t, err.Error(), "Invalid configuration:\n"+
303+ assert.Equal(t, err.Error(), "invalid configuration:\n"+
304304 fmt.Sprintf(" invalid cookie name: %q", o.CookieName))
305305}
306306
@@ -311,8 +311,8 @@ func TestSkipOIDCDiscovery(t *testing.T) {
311311 o.SkipOIDCDiscovery = true
312312
313313 err := o.Validate()
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())
314+ assert.Equal(t, "invalid configuration:\n"+
315+ " missing setting: login-url\n missing setting: redeem-url\n missing setting: oidc-jwks-url", err.Error())
316316
317317 o.LoginURL = "https://login.microsoftonline.com/fabrikamb2c.onmicrosoft.com/oauth2/v2.0/authorize?p=b2c_1_sign_in"
318318 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) {
139139 l.writer.Write([]byte("\n"))
140140}
141141
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
143143// log request details. Remaining arguments are handled in the manner of
144144// 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{}) {
146146 if !l.authEnabled {
147147 return
148148 }
@@ -166,7 +166,7 @@ func (l *Logger) PrintAuth(username string, req *http.Request, status AuthStatus
166166 Timestamp: FormatTimestamp(now),
167167 UserAgent: fmt.Sprintf("%q", req.UserAgent()),
168168 Username: username,
169− Status: fmt.Sprintf("%s", status),
169+ Status: string(status),
170170 Message: fmt.Sprintf(format, a...),
171171 })
172172
@@ -185,7 +185,7 @@ func (l *Logger) PrintReq(username, upstream string, req *http.Request, url url.
185185 return
186186 }
187187
188− duration := float64(time.Now().Sub(ts)) / float64(time.Second)
188+ duration := float64(time.Since(ts)) / float64(time.Second)
189189
190190 if username == "" {
191191 username = "-"
@@ -481,7 +481,7 @@ func Panicln(v ...interface{}) {
481481// PrintAuthf writes authentication details to the standard logger.
482482// Arguments are handled in the manner of fmt.Printf.
483483func 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...)
485485}
486486
487487// PrintReq writes request details to the standard logger.
pkg/requests/requests_test.go+2−2
@@ -88,9 +88,9 @@ func TestRequestUnparsedResponseUsingAccessTokenParameter(t *testing.T) {
8888
8989 response, err := RequestUnparsedResponse(
9090 backend.URL+"?access_token=my_token", nil)
91+ assert.Equal(t, nil, err)
9192 defer response.Body.Close()
9293
93− assert.Equal(t, nil, err)
9494 assert.Equal(t, 200, response.StatusCode)
9595 body, err := ioutil.ReadAll(response.Body)
9696 assert.Equal(t, nil, err)
@@ -124,9 +124,9 @@ func TestRequestUnparsedResponseUsingHeaders(t *testing.T) {
124124 headers := make(http.Header)
125125 headers.Set("Auth", "my_token")
126126 response, err := RequestUnparsedResponse(backend.URL, headers)
127+ assert.Equal(t, nil, err)
127128 defer response.Body.Close()
128129
129− assert.Equal(t, nil, err)
130130 assert.Equal(t, 200, response.StatusCode)
131131 body, err := ioutil.ReadAll(response.Body)
132132 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) {
5252 c, err := loadCookie(req, s.CookieOptions.CookieName)
5353 if err != nil {
5454 // 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)
5656 }
5757 val, _, ok := encryption.Validate(c, s.CookieOptions.CookieSecret, s.CookieOptions.CookieExpire)
5858 if !ok {
59− return nil, errors.New("Cookie Signature not valid")
59+ return nil, errors.New("cookie signature not valid")
6060 }
6161
6262 session, err := utils.SessionFromCookie(val, s.CookieCipher)
@@ -69,8 +69,6 @@ func (s *SessionStore) Load(req *http.Request) (*sessions.SessionState, error) {
6969// Clear clears any saved session information by writing a cookie to
7070// clear the session
7171func (s *SessionStore) Clear(rw http.ResponseWriter, req *http.Request) error {
72− var cookies []*http.Cookie
73−
7472 // matches CookieName, CookieName_<number>
7573 var cookieNameRegex = regexp.MustCompile(fmt.Sprintf("^%s(_\\d+)?$", s.CookieOptions.CookieName))
7674
@@ -79,7 +77,6 @@ func (s *SessionStore) Clear(rw http.ResponseWriter, req *http.Request) error {
7977 clearCookie := s.makeCookie(req, c.Name, "", time.Hour*-1, time.Now())
8078
8179 http.SetCookie(rw, clearCookie)
82− cookies = append(cookies, clearCookie)
8380 }
8481 }
8582
@@ -174,7 +171,7 @@ func loadCookie(req *http.Request, cookieName string) (*http.Cookie, error) {
174171 }
175172 }
176173 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)
178175 }
179176 return joinCookies(cookies)
180177}
pkg/sessions/redis/redis_store.go+3−3
@@ -79,7 +79,7 @@ func newRedisCmdable(opts options.RedisStoreOptions) (Client, error) {
7979 return nil, fmt.Errorf("unable to parse redis url: %s", err)
8080 }
8181
82− if opts.RedisInsecureTLS != false {
82+ if opts.RedisInsecureTLS {
8383 opt.TLSConfig.InsecureSkipVerify = true
8484 }
8585
@@ -149,7 +149,7 @@ func (store *SessionStore) Load(req *http.Request) (*sessions.SessionState, erro
149149
150150 val, _, ok := encryption.Validate(requestCookie, store.CookieOptions.CookieSecret, store.CookieOptions.CookieExpire)
151151 if !ok {
152− return nil, fmt.Errorf("Cookie Signature not valid")
152+ return nil, fmt.Errorf("cookie signature not valid")
153153 }
154154 ctx := req.Context()
155155 session, err := store.loadSessionFromString(ctx, val)
@@ -209,7 +209,7 @@ func (store *SessionStore) Clear(rw http.ResponseWriter, req *http.Request) erro
209209
210210 val, _, ok := encryption.Validate(requestCookie, store.CookieOptions.CookieSecret, store.CookieOptions.CookieExpire)
211211 if !ok {
212− return fmt.Errorf("Cookie Signature not valid")
212+ return fmt.Errorf("cookie signature not valid")
213213 }
214214
215215 // 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
116116 break
117117 }
118118 }
119− if found != true {
119+ if !found {
120120 logger.Print("team membership test failed, access denied")
121121 return "", nil
122122 }
@@ -147,7 +147,7 @@ func (p *BitbucketProvider) GetEmailAddress(s *sessions.SessionState) (string, e
147147 break
148148 }
149149 }
150− if found != true {
150+ if !found {
151151 logger.Print("repository access test failed, access denied")
152152 return "", nil
153153 }
providers/github.go+1−1
@@ -122,7 +122,7 @@ func (p *GitHubProvider) hasOrg(accessToken string) (bool, error) {
122122 pn++
123123 }
124124
125− var presentOrgs []string
125+ presentOrgs := make([]string, 0, len(orgs))
126126 for _, org := range orgs {
127127 if p.Org == org.Login {
128128 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
222222func (p *GitLabProvider) ValidateSessionState(s *sessions.SessionState) bool {
223223 ctx := context.Background()
224224 _, err := p.Verifier.Verify(ctx, s.IDToken)
225− if err != nil {
226− return false
227− }
228−
229− return true
225+ return err == nil
230226}
231227
232228// GetEmailAddress returns the Account email address
providers/google.go+5−3
@@ -2,6 +2,7 @@ package providers
22
33import (
44 "bytes"
5+ "context"
56 "encoding/base64"
67 "encoding/json"
78 "errors"
@@ -15,10 +16,10 @@ import (
1516
1617 "github.com/oauth2-proxy/oauth2-proxy/pkg/apis/sessions"
1718 "github.com/oauth2-proxy/oauth2-proxy/pkg/logger"
18− "golang.org/x/oauth2"
1919 "golang.org/x/oauth2/google"
2020 admin "google.golang.org/api/admin/directory/v1"
2121 "google.golang.org/api/googleapi"
22+ "google.golang.org/api/option"
2223)
2324
2425// GoogleProvider represents an Google based Identity Provider
@@ -184,8 +185,9 @@ func getAdminService(adminEmail string, credentialsReader io.Reader) *admin.Serv
184185 }
185186 conf.Subject = adminEmail
186187
187− client := conf.Client(oauth2.NoContext)
188− adminService, err := admin.New(client)
188+ ctx := context.Background()
189+ client := conf.Client(ctx)
190+ adminService, err := admin.NewService(ctx, option.WithHTTPClient(client))
189191 if err != nil {
190192 logger.Fatal(err)
191193 }
providers/keycloak.go+1−1
@@ -76,7 +76,7 @@ func (p *KeycloakProvider) GetEmailAddress(s *sessions.SessionState) (string, er
7676 }
7777 }
7878
79− if found != true {
79+ if !found {
8080 logger.Printf("group not found, access denied")
8181 return "", nil
8282 }
providers/logingov.go+2−3
@@ -183,7 +183,7 @@ func (p *LoginGovProvider) Redeem(redirectURL, code string) (s *sessions.Session
183183 Issuer: p.ClientID,
184184 Subject: p.ClientID,
185185 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(),
187187 Id: randSeq(32),
188188 }
189189 token := jwt.NewWithClaims(jwt.GetSigningMethod("RS256"), claims)
@@ -260,8 +260,7 @@ func (p *LoginGovProvider) Redeem(redirectURL, code string) (s *sessions.Session
260260
261261// GetLoginURL overrides GetLoginURL to add login.gov parameters
262262func (p *LoginGovProvider) GetLoginURL(redirectURI, state string) string {
263− var a url.URL
264− a = *p.LoginURL
263+ a := *p.LoginURL
265264 params, _ := url.ParseQuery(a.RawQuery)
266265 params.Set("redirect_uri", redirectURI)
267266 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
180180func (p *OIDCProvider) ValidateSessionState(s *sessions.SessionState) bool {
181181 ctx := context.Background()
182182 _, err := p.Verifier.Verify(ctx, s.IDToken)
183− if err != nil {
184− return false
185− }
186−
187− return true
183+ return err == nil
188184}
189185
190186func getOIDCHeader(accessToken string) http.Header {
providers/oidc_test.go+6−1
@@ -62,6 +62,9 @@ type fakeKeySetStub struct{}
6262
6363func (fakeKeySetStub) VerifySignature(_ context.Context, jwt string) (payload []byte, err error) {
6464 decodeString, err := base64.RawURLEncoding.DecodeString(strings.Split(jwt, ".")[1])
65+ if err != nil {
66+ return nil, err
67+ }
6568 tokenClaims := &idTokenClaims{}
6669 err = json.Unmarshal(decodeString, tokenClaims)
6770
@@ -242,7 +245,9 @@ func TestOIDCProvider_findVerifiedIdToken(t *testing.T) {
242245
243246 verifiedIDToken, err := provider.findVerifiedIDToken(context.Background(), tokenWithIDToken)
244247 assert.Equal(t, true, err == nil)
245− assert.Equal(t, true, verifiedIDToken != nil)
248+ if verifiedIDToken == nil {
249+ t.Fatal("verifiedIDToken is nil")
250+ }
246251 assert.Equal(t, defaultIDToken.Issuer, verifiedIDToken.Issuer)
247252 assert.Equal(t, defaultIDToken.Subject, verifiedIDToken.Subject)
248253
providers/provider_data.go+1−1
@@ -31,7 +31,7 @@ type ProviderData struct {
3131// Data returns the ProviderData
3232func (p *ProviderData) Data() *ProviderData { return p }
3333
34−func (p *ProviderData) GetClientSecret() (ClientSecret string, err error) {
34+func (p *ProviderData) GetClientSecret() (clientSecret string, err error) {
3535 if p.ClientSecret != "" || p.ClientSecretFile == "" {
3636 return p.ClientSecret, nil
3737 }
providers/provider_default.go+1−2
@@ -86,8 +86,7 @@ func (p *ProviderData) Redeem(redirectURL, code string) (s *sessions.SessionStat
8686
8787// GetLoginURL with typical oauth parameters
8888func (p *ProviderData) GetLoginURL(redirectURI, state string) string {
89− var a url.URL
90− a = *p.LoginURL
89+ a := *p.LoginURL
9190 params, _ := url.ParseQuery(a.RawQuery)
9291 params.Set("redirect_uri", redirectURI)
9392 params.Add("acr_values", p.AcrValues)
watcher.go+1−1
@@ -44,7 +44,7 @@ func WatchForUpdates(filename string, done <-chan bool, action func()) {
4444 defer watcher.Close()
4545 for {
4646 select {
47− case _ = <-done:
47+ case <-done:
4848 logger.Printf("Shutting down watcher for: %s", filename)
4949 return
5050 case event := <-watcher.Events: