git.iko.soy/typeable/oauth2-proxy
on master help sign in
Merge branch 'master' into feature/add_oidc_userinfo_support
commitc457eeb711c85922a757f03c2d2a3c3d159334c3 authorRyan Luckie <rtluckie@users.noreply.github.com> dateMon 12 Aug 2019, 17:32 (7 years ago) parent4a6b703e1b70dc
15 files changed+532−206
.github/CODEOWNERS+3−3 .travis.yml+1−3 CHANGELOG.md+19−11 MAINTAINERS+3 README.md+4 docs/2_auth.md+56−4 docs/configuration/configuration.md+4−2 main.go+3−1 oauthproxy.go+9−3 oauthproxy_test.go+2−2 options.go+41−16 providers/gitlab.go+227−31 providers/gitlab_test.go+98−60 providers/google.go+26−55 providers/google_test.go+36−15
.github/CODEOWNERS+3−3
@@ -1,6 +1,6 @@
1−# Default owner should be a Pusher cloud-team member unless overridden by later
2−# rules in this file
3−* @pusher/cloud-team
1+# Default owner should be a Pusher cloud-team member or another maintainer
2+# unless overridden by later rules in this file
3+* @pusher/cloud-team @syscll @steakunderscore
44
55# login.gov provider
66# Note: If @timothy-spencer terms out of his appointment, your best bet
.travis.yml+1−3
@@ -3,10 +3,8 @@ go:
33 - 1.12.x
44install:
55 # Fetch dependencies
6− - wget -O dep https://github.com/golang/dep/releases/download/v0.5.0/dep-linux-amd64
7− - chmod +x dep
8− - mv dep $GOPATH/bin/dep
96 - curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $GOPATH/bin v1.17.1
7+ - GO111MODULE=on go mod download
108script:
119 - ./configure && make test
1210sudo: false
CHANGELOG.md+19−11
@@ -2,6 +2,11 @@
22
33## Breaking Changes
44
5+- [#231](https://github.com/pusher/oauth2_proxy/pull/231) Rework GitLab provider (@Overv)
6+ - This PR changes the configuration options for the GitLab provider to use
7+ a self-hosted instance. You now need to specify a `-oidc-issuer-url` rather than
8+ explicit `-login-url`, `-redeem-url` and `-validate-url` parameters.
9+
510- [#186](https://github.com/pusher/oauth2_proxy/pull/186) Make config consistent
611 - This PR changes configuration options so that all flags have a config counterpart
712 of the same name but with underscores (`_`) in place of hyphens (`-`).
@@ -31,18 +36,21 @@
3136
3237## Changes since v3.2.0
3338
34−- [#178](https://github.com/pusher/outh2_proxy/pull/178) Add Silence Ping Logging and Exclude Logging Paths flags (@kskewes)
35−- [#209](https://github.com/pusher/outh2_proxy/pull/209) Improve docker build caching of layers (@dekimsey)
39+- [#234](https://github.com/pusher/oauth2_proxy/pull/234) Added option `-ssl-upstream-insecure-skip-validation` to skip validation of upstream SSL certificates (@jansinger)
40+- [#224](https://github.com/pusher/oauth2_proxy/pull/224) Check Google group membership using hasMember to support nested groups and external users (@jpalpant)
41+- [#231](https://github.com/pusher/oauth2_proxy/pull/231) Add optional group membership and email domain checks to the GitLab provider (@Overv)
42+- [#178](https://github.com/pusher/oauth2_proxy/pull/178) Add Silence Ping Logging and Exclude Logging Paths flags (@kskewes)
43+- [#209](https://github.com/pusher/oauth2_proxy/pull/209) Improve docker build caching of layers (@dekimsey)
3644- [#186](https://github.com/pusher/oauth2_proxy/pull/186) Make config consistent (@JoelSpeed)
3745- [#187](https://github.com/pusher/oauth2_proxy/pull/187) Move root packages to pkg folder (@JoelSpeed)
3846- [#65](https://github.com/pusher/oauth2_proxy/pull/65) Improvements to authenticate requests with a JWT bearer token in the `Authorization` header via
3947 the `-skip-jwt-bearer-token` options.
4048 - Additional verifiers can be configured via the `-extra-jwt-issuers` flag if the JWT issuers is either an OpenID provider or has a JWKS URL
4149 (e.g. `https://example.com/.well-known/jwks.json`).
42−- [#180](https://github.com/pusher/outh2_proxy/pull/180) Minor refactor of core proxying path (@aeijdenberg).
43−- [#175](https://github.com/pusher/outh2_proxy/pull/175) Bump go-oidc to v2.0.0 (@aeijdenberg).
50+- [#180](https://github.com/pusher/oauth2_proxy/pull/180) Minor refactor of core proxying path (@aeijdenberg).
51+- [#175](https://github.com/pusher/oauth2_proxy/pull/175) Bump go-oidc to v2.0.0 (@aeijdenberg).
4452 - Includes fix for potential signature checking issue when OIDC discovery is skipped.
45−- [#155](https://github.com/pusher/outh2_proxy/pull/155) Add RedisSessionStore implementation (@brianv0, @JoelSpeed)
53+- [#155](https://github.com/pusher/oauth2_proxy/pull/155) Add RedisSessionStore implementation (@brianv0, @JoelSpeed)
4654 - Implement flags to configure the redis session store
4755 - `-session-store-type=redis` Sets the store type to redis
4856 - `-redis-connection-url` Sets the Redis connection URL
@@ -52,10 +60,10 @@
5260 - Introduces the concept of a session ticket. Tickets are composed of the cookie name, a session ID, and a secret.
5361 - Redis Sessions are stored encrypted with a per-session secret
5462 - Added tests for server based session stores
55−- [#168](https://github.com/pusher/outh2_proxy/pull/168) Drop Go 1.11 support in Travis (@JoelSpeed)
56−- [#169](https://github.com/pusher/outh2_proxy/pull/169) Update Alpine to 3.9 (@kskewes)
57−- [#148](https://github.com/pusher/outh2_proxy/pull/148) Implement SessionStore interface within proxy (@JoelSpeed)
58−- [#147](https://github.com/pusher/outh2_proxy/pull/147) Add SessionStore interfaces and initial implementation (@JoelSpeed)
63+- [#168](https://github.com/pusher/oauth2_proxy/pull/168) Drop Go 1.11 support in Travis (@JoelSpeed)
64+- [#169](https://github.com/pusher/oauth2_proxy/pull/169) Update Alpine to 3.9 (@kskewes)
65+- [#148](https://github.com/pusher/oauth2_proxy/pull/148) Implement SessionStore interface within proxy (@JoelSpeed)
66+- [#147](https://github.com/pusher/oauth2_proxy/pull/147) Add SessionStore interfaces and initial implementation (@JoelSpeed)
5967 - Allows for multiple different session storage implementations including client and server side
6068 - Adds tests suite for interface to ensure consistency across implementations
6169 - Refactor some configuration options (around cookies) into packages
@@ -83,8 +91,8 @@
8391- [#185](https://github.com/pusher/oauth2_proxy/pull/185) Fix an unsupported protocol scheme error during token validation when using the Azure provider (@jonas)
8492- [#141](https://github.com/pusher/oauth2_proxy/pull/141) Check google group membership based on email address (@bchess)
8593 - Google Group membership is additionally checked via email address, allowing users outside a GSuite domain to be authorized.
86−- [#195](https://github.com/pusher/outh2_proxy/pull/195) Add `-banner` flag for overriding the banner line that is displayed (@steakunderscore)
87−- [#198](https://github.com/pusher/outh2_proxy/pull/198) Switch from gometalinter to golangci-lint (@steakunderscore)
94+- [#195](https://github.com/pusher/oauth2_proxy/pull/195) Add `-banner` flag for overriding the banner line that is displayed (@steakunderscore)
95+- [#198](https://github.com/pusher/oauth2_proxy/pull/198) Switch from gometalinter to golangci-lint (@steakunderscore)
8896- [#159](https://github.com/pusher/oauth2_proxy/pull/159) Add option to skip the OIDC provider verified email check: `--insecure-oidc-allow-unverified-email`
8997- [#210](https://github.com/pusher/oauth2_proxy/pull/210) Update base image from Alpine 3.9 to 3.10 (@steakunderscore)
9098- [#211](https://github.com/pusher/oauth2_proxy/pull/211) Switch from dep to go modules (@steakunderscore)
MAINTAINERSnew file+3
@@ -0,0 +1,3 @@
1+Joel Speed <joel.speed@hotmail.co.uk> (@JoelSpeed)
2+Dan Bond (@syscll)
3+Henry Jenkins <henry@henryjenkins.name> (@steakunderscore)
README.md+4
@@ -38,6 +38,10 @@ Read the docs on our [Docs site](https://pusher.github.io/oauth2_proxy).
3838
3939![OAuth2 Proxy Architecture](https://cloud.githubusercontent.com/assets/45028/8027702/bd040b7a-0d6a-11e5-85b9-f8d953d04f39.png)
4040
41+## Getting Involved
42+
43+If you would like to reach out to the maintainers, come talk to us in the `#oauth2_proxy` channel in the [Gophers slack](http://gophers.slack.com/).
44+
4145## Contributing
4246
4347Please see our [Contributing](CONTRIBUTING.md) guidelines.
docs/2_auth.md+56−4
@@ -103,13 +103,15 @@ If you are using GitHub enterprise, make sure you set the following to the appro
103103
104104### GitLab Auth Provider
105105
106−Whether you are using GitLab.com or self-hosting GitLab, follow [these steps to add an application](http://doc.gitlab.com/ce/integration/oauth_provider.html)
106+Whether you are using GitLab.com or self-hosting GitLab, follow [these steps to add an application](http://doc.gitlab.com/ce/integration/oauth_provider.html). Make sure to enable at least the `openid`, `profile` and `email` scopes.
107+
108+Restricting by group membership is possible with the following option:
109+
110+ -gitlab-group="": restrict logins to members of any of these groups (slug), separated by a comma
107111
108112If you are using self-hosted GitLab, make sure you set the following to the appropriate URL:
109113
110− -login-url="<your gitlab url>/oauth/authorize"
111− -redeem-url="<your gitlab url>/oauth/token"
112− -validate-url="<your gitlab url>/api/v4/user"
114+ -oidc-issuer-url="<your gitlab url>"
113115
114116### LinkedIn Auth Provider
115117
@@ -144,6 +146,56 @@ OpenID Connect is a spec for OAUTH 2.0 + identity that is implemented by many ma
144146 -cookie-secure=false
145147 -email-domain example.com
146148
149+The OpenID Connect Provider (OIDC) can also be used to connect to other Identity Providers such as Okta. To configure the OIDC provider for Okta, perform
150+the following steps:
151+
152+#### Configuring the OIDC Provider with Okta
153+
154+1. Log in to Okta using an administrative account. It is suggested you try this in preview first, `example.oktapreview.com`
155+2. (OPTIONAL) If you want to configure authorization scopes and claims to be passed on to multiple applications,
156+you may wish to configure an authorization server for each application. Otherwise, the provided `default` will work.
157+* Navigate to **Security** then select **API**
158+* Click **Add Authorization Server**, if this option is not available you may require an additional license for a custom authorization server.
159+* Fill out the **Name** with something to describe the application you are protecting. e.g. 'Example App'.
160+* For **Audience**, pick the URL of the application you wish to protect: https://example.corp.com
161+* Fill out a **Description**
162+* Add any **Access Policies** you wish to configure to limit application access.
163+* The default settings will work for other options.
164+[See Okta documentation for more information on Authorization Servers](https://developer.okta.com/docs/guides/customize-authz-server/overview/)
165+3. Navigate to **Applications** then select **Add Application**.
166+* Select **Web** for the **Platform** setting.
167+* Select **OpenID Connect** and click **Create**
168+* Pick an **Application Name** such as `Example App`.
169+* Set the **Login redirect URI** to `https://example.corp.com`.
170+* Under **General** set the **Allowed grant types** to `Authorization Code` and `Refresh Token`.
171+* Leave the rest as default, taking note of the `Client ID` and `Client Secret`.
172+* Under **Assignments** select the users or groups you wish to access your application.
173+4. Create a configuration file like the following:
174+
175+```
176+provider = "oidc"
177+redirect_url = "https://example.corp.com"
178+oidc_issuer_url = "https://corp.okta.com/oauth2/abCd1234"
179+upstreams = [
180+ "https://example.corp.com"
181+]
182+email_domains = [
183+ "corp.com"
184+]
185+client_id = "XXXXX"
186+client_secret = "YYYYY"
187+pass_access_token = true
188+cookie_secret = "ZZZZZ"
189+skip_provider_button = true
190+```
191+
192+The `oidc_issuer_url` is based on URL from your **Authorization Server**'s **Issuer** field in step 2, or simply https://corp.okta.com
193+The `client_id` and `client_secret` are configured in the application settings.
194+Generate a unique `client_secret` to encrypt the cookie.
195+
196+Then you can start the oauth2_proxy with `./oauth2_proxy -config /etc/example.cfg`
197+
198+
147199### login.gov Provider
148200
149201login.gov is an OIDC provider for the US Government.
docs/configuration/configuration.md+4−2
@@ -14,7 +14,7 @@ To generate a strong cookie secret use `python -c 'import os,base64; print base6
1414
1515### Config File
1616
17−An example [oauth2_proxy.cfg](contrib/oauth2_proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `-config=/etc/oauth2_proxy.cfg`
17+An example [oauth2_proxy.cfg](https://github.com/pusher/oauth2_proxy/blob/master/contrib/oauth2_proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `-config=/etc/oauth2_proxy.cfg`
1818
1919### Command Line Options
2020
@@ -49,6 +49,7 @@ Usage of oauth2_proxy:
4949 -gcp-healthchecks: 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 (default false)
5050 -github-org string: restrict logins to members of this organisation
5151 -github-team string: restrict logins to members of any of these teams (slug), separated by a comma
52+ -gitlab-group string: restrict logins to members of any of these groups (slug), separated by a comma
5253 -google-admin-email string: the google admin to impersonate for api calls
5354 -google-group value: restrict logins to members of this google group (may be given multiple times).
5455 -google-service-account-json string: the path to the service account json credentials
@@ -98,7 +99,8 @@ Usage of oauth2_proxy:
9899 -skip-jwt-bearer-tokens: will skip requests that have verified JWT bearer tokens
99100 -skip-oidc-discovery: bypass OIDC endpoint discovery. login-url, redeem-url and oidc-jwks-url must be configured in this case
100101 -skip-provider-button: will skip sign-in-page to directly reach the next step: oauth/start
101− -ssl-insecure-skip-verify: skip validation of certificates presented when using HTTPS
102+ -ssl-insecure-skip-verify: skip validation of certificates presented when using HTTPS providers
103+ -ssl-upstream-insecure-skip-verify: skip validation of certificates presented when using HTTPS upstreams
102104 -standard-logging: Log standard runtime information (default true)
103105 -standard-logging-format string: Template for standard log lines (see "Logging Configuration" paragraph below)
104106 -tls-cert-file string: path to certificate file
main.go+3−1
@@ -47,7 +47,8 @@ func main() {
4747 flagSet.Var(&skipAuthRegex, "skip-auth-regex", "bypass authentication for requests path's that match (may be given multiple times)")
4848 flagSet.Bool("skip-provider-button", false, "will skip sign-in-page to directly reach the next step: oauth/start")
4949 flagSet.Bool("skip-auth-preflight", false, "will skip authentication for OPTIONS requests")
50− flagSet.Bool("ssl-insecure-skip-verify", false, "skip validation of certificates presented when using HTTPS")
50+ flagSet.Bool("ssl-insecure-skip-verify", false, "skip validation of certificates presented when using HTTPS providers")
51+ flagSet.Bool("ssl-upstream-insecure-skip-verify", false, "skip validation of certificates presented when using HTTPS upstreams")
5152 flagSet.Duration("flush-interval", time.Duration(1)*time.Second, "period between response flushing when streaming responses")
5253 flagSet.Bool("skip-jwt-bearer-tokens", false, "will skip requests that have verified JWT bearer tokens (default false)")
5354 flagSet.Var(&jwtIssuers, "extra-jwt-issuers", "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)")
@@ -57,6 +58,7 @@ func main() {
5758 flagSet.String("azure-tenant", "common", "go to a tenant-specific or common (tenant-independent) endpoint.")
5859 flagSet.String("github-org", "", "restrict logins to members of this organisation")
5960 flagSet.String("github-team", "", "restrict logins to members of this team")
61+ flagSet.String("gitlab-group", "", "restrict logins to members of this group")
6062 flagSet.Var(&googleGroups, "google-group", "restrict logins to members of this google group (may be given multiple times).")
6163 flagSet.String("google-admin-email", "", "the google admin to impersonate for api calls")
6264 flagSet.String("google-service-account-json", "", "the path to the service account json credentials")
oauthproxy.go+9−3
@@ -2,6 +2,7 @@ package main
22
33import (
44 "context"
5+ "crypto/tls"
56 b64 "encoding/base64"
67 "errors"
78 "fmt"
@@ -128,9 +129,14 @@ func (u *UpstreamProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
128129
129130// NewReverseProxy creates a new reverse proxy for proxying requests to upstream
130131// servers
131−func NewReverseProxy(target *url.URL, flushInterval time.Duration) (proxy *httputil.ReverseProxy) {
132+func NewReverseProxy(target *url.URL, opts *Options) (proxy *httputil.ReverseProxy) {
132133 proxy = httputil.NewSingleHostReverseProxy(target)
133− proxy.FlushInterval = flushInterval
134+ proxy.FlushInterval = opts.FlushInterval
135+ if opts.SSLUpstreamInsecureSkipVerify {
136+ proxy.Transport = &http.Transport{
137+ TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
138+ }
139+ }
134140 return proxy
135141}
136142
@@ -163,7 +169,7 @@ func NewFileServer(path string, filesystemPath string) (proxy http.Handler) {
163169// NewWebSocketOrRestReverseProxy creates a reverse proxy for REST or websocket based on url
164170func NewWebSocketOrRestReverseProxy(u *url.URL, opts *Options, auth hmacauth.HmacAuth) http.Handler {
165171 u.Path = ""
166− proxy := NewReverseProxy(u, opts.FlushInterval)
172+ proxy := NewReverseProxy(u, opts)
167173 if !opts.PassHostHeader {
168174 setProxyUpstreamHostHeader(proxy, u)
169175 } else {
oauthproxy_test.go+2−2
@@ -122,7 +122,7 @@ func TestNewReverseProxy(t *testing.T) {
122122 backendHost := net.JoinHostPort(backendHostname, backendPort)
123123 proxyURL, _ := url.Parse(backendURL.Scheme + "://" + backendHost + "/")
124124
125− proxyHandler := NewReverseProxy(proxyURL, time.Second)
125+ proxyHandler := NewReverseProxy(proxyURL, &Options{FlushInterval: time.Second})
126126 setProxyUpstreamHostHeader(proxyHandler, proxyURL)
127127 frontend := httptest.NewServer(proxyHandler)
128128 defer frontend.Close()
@@ -144,7 +144,7 @@ func TestEncodedSlashes(t *testing.T) {
144144 defer backend.Close()
145145
146146 b, _ := url.Parse(backend.URL)
147− proxyHandler := NewReverseProxy(b, time.Second)
147+ proxyHandler := NewReverseProxy(b, &Options{FlushInterval: time.Second})
148148 setProxyDirector(proxyHandler)
149149 frontend := httptest.NewServer(proxyHandler)
150150 defer frontend.Close()
options.go+41−16
@@ -46,6 +46,7 @@ type Options struct {
4646 WhitelistDomains []string `flag:"whitelist-domain" cfg:"whitelist_domains" env:"OAUTH2_PROXY_WHITELIST_DOMAINS"`
4747 GitHubOrg string `flag:"github-org" cfg:"github_org" env:"OAUTH2_PROXY_GITHUB_ORG"`
4848 GitHubTeam string `flag:"github-team" cfg:"github_team" env:"OAUTH2_PROXY_GITHUB_TEAM"`
49+ GitLabGroup string `flag:"gitlab-group" cfg:"gitlab_group" env:"OAUTH2_PROXY_GITLAB_GROUP"`
4950 GoogleGroups []string `flag:"google-group" cfg:"google_group" env:"OAUTH2_PROXY_GOOGLE_GROUPS"`
5051 GoogleAdminEmail string `flag:"google-admin-email" cfg:"google_admin_email" env:"OAUTH2_PROXY_GOOGLE_ADMIN_EMAIL"`
5152 GoogleServiceAccountJSON string `flag:"google-service-account-json" cfg:"google_service_account_json" env:"OAUTH2_PROXY_GOOGLE_SERVICE_ACCOUNT_JSON"`
@@ -61,22 +62,23 @@ type Options struct {
6162 // Embed SessionOptions
6263 options.SessionOptions
6364
64− Upstreams []string `flag:"upstream" cfg:"upstreams" env:"OAUTH2_PROXY_UPSTREAMS"`
65− SkipAuthRegex []string `flag:"skip-auth-regex" cfg:"skip_auth_regex" env:"OAUTH2_PROXY_SKIP_AUTH_REGEX"`
66− SkipJwtBearerTokens bool `flag:"skip-jwt-bearer-tokens" cfg:"skip_jwt_bearer_tokens" env:"OAUTH2_PROXY_SKIP_JWT_BEARER_TOKENS"`
67− ExtraJwtIssuers []string `flag:"extra-jwt-issuers" cfg:"extra_jwt_issuers" env:"OAUTH2_PROXY_EXTRA_JWT_ISSUERS"`
68− PassBasicAuth bool `flag:"pass-basic-auth" cfg:"pass_basic_auth" env:"OAUTH2_PROXY_PASS_BASIC_AUTH"`
69− BasicAuthPassword string `flag:"basic-auth-password" cfg:"basic_auth_password" env:"OAUTH2_PROXY_BASIC_AUTH_PASSWORD"`
70− PassAccessToken bool `flag:"pass-access-token" cfg:"pass_access_token" env:"OAUTH2_PROXY_PASS_ACCESS_TOKEN"`
71− PassHostHeader bool `flag:"pass-host-header" cfg:"pass_host_header" env:"OAUTH2_PROXY_PASS_HOST_HEADER"`
72− SkipProviderButton bool `flag:"skip-provider-button" cfg:"skip_provider_button" env:"OAUTH2_PROXY_SKIP_PROVIDER_BUTTON"`
73− PassUserHeaders bool `flag:"pass-user-headers" cfg:"pass_user_headers" env:"OAUTH2_PROXY_PASS_USER_HEADERS"`
74− SSLInsecureSkipVerify bool `flag:"ssl-insecure-skip-verify" cfg:"ssl_insecure_skip_verify" env:"OAUTH2_PROXY_SSL_INSECURE_SKIP_VERIFY"`
75− SetXAuthRequest bool `flag:"set-xauthrequest" cfg:"set_xauthrequest" env:"OAUTH2_PROXY_SET_XAUTHREQUEST"`
76− SetAuthorization bool `flag:"set-authorization-header" cfg:"set_authorization_header" env:"OAUTH2_PROXY_SET_AUTHORIZATION_HEADER"`
77− PassAuthorization bool `flag:"pass-authorization-header" cfg:"pass_authorization_header" env:"OAUTH2_PROXY_PASS_AUTHORIZATION_HEADER"`
78− SkipAuthPreflight bool `flag:"skip-auth-preflight" cfg:"skip_auth_preflight" env:"OAUTH2_PROXY_SKIP_AUTH_PREFLIGHT"`
79− FlushInterval time.Duration `flag:"flush-interval" cfg:"flush_interval" env:"OAUTH2_PROXY_FLUSH_INTERVAL"`
65+ Upstreams []string `flag:"upstream" cfg:"upstreams" env:"OAUTH2_PROXY_UPSTREAMS"`
66+ SkipAuthRegex []string `flag:"skip-auth-regex" cfg:"skip_auth_regex" env:"OAUTH2_PROXY_SKIP_AUTH_REGEX"`
67+ SkipJwtBearerTokens bool `flag:"skip-jwt-bearer-tokens" cfg:"skip_jwt_bearer_tokens" env:"OAUTH2_PROXY_SKIP_JWT_BEARER_TOKENS"`
68+ ExtraJwtIssuers []string `flag:"extra-jwt-issuers" cfg:"extra_jwt_issuers" env:"OAUTH2_PROXY_EXTRA_JWT_ISSUERS"`
69+ PassBasicAuth bool `flag:"pass-basic-auth" cfg:"pass_basic_auth" env:"OAUTH2_PROXY_PASS_BASIC_AUTH"`
70+ BasicAuthPassword string `flag:"basic-auth-password" cfg:"basic_auth_password" env:"OAUTH2_PROXY_BASIC_AUTH_PASSWORD"`
71+ PassAccessToken bool `flag:"pass-access-token" cfg:"pass_access_token" env:"OAUTH2_PROXY_PASS_ACCESS_TOKEN"`
72+ PassHostHeader bool `flag:"pass-host-header" cfg:"pass_host_header" env:"OAUTH2_PROXY_PASS_HOST_HEADER"`
73+ SkipProviderButton bool `flag:"skip-provider-button" cfg:"skip_provider_button" env:"OAUTH2_PROXY_SKIP_PROVIDER_BUTTON"`
74+ PassUserHeaders bool `flag:"pass-user-headers" cfg:"pass_user_headers" env:"OAUTH2_PROXY_PASS_USER_HEADERS"`
75+ SSLInsecureSkipVerify bool `flag:"ssl-insecure-skip-verify" cfg:"ssl_insecure_skip_verify" env:"OAUTH2_PROXY_SSL_INSECURE_SKIP_VERIFY"`
76+ SSLUpstreamInsecureSkipVerify bool `flag:"ssl-upstream-insecure-skip-verify" cfg:"ssl_upstream_insecure_skip_verify" env:"OAUTH2_PROXY_SSL_UPSTREAM_INSECURE_SKIP_VERIFY"`
77+ SetXAuthRequest bool `flag:"set-xauthrequest" cfg:"set_xauthrequest" env:"OAUTH2_PROXY_SET_XAUTHREQUEST"`
78+ SetAuthorization bool `flag:"set-authorization-header" cfg:"set_authorization_header" env:"OAUTH2_PROXY_SET_AUTHORIZATION_HEADER"`
79+ PassAuthorization bool `flag:"pass-authorization-header" cfg:"pass_authorization_header" env:"OAUTH2_PROXY_PASS_AUTHORIZATION_HEADER"`
80+ SkipAuthPreflight bool `flag:"skip-auth-preflight" cfg:"skip_auth_preflight" env:"OAUTH2_PROXY_SKIP_AUTH_PREFLIGHT"`
81+ FlushInterval time.Duration `flag:"flush-interval" cfg:"flush_interval" env:"OAUTH2_PROXY_FLUSH_INTERVAL"`
8082
8183 // These options allow for other providers besides Google, with
8284 // potential overrides.
@@ -410,6 +412,29 @@ func parseProviderInfo(o *Options, msgs []string) []string {
410412 } else {
411413 p.Verifier = o.oidcVerifier
412414 }
415+ case *providers.GitLabProvider:
416+ p.AllowUnverifiedEmail = o.InsecureOIDCAllowUnverifiedEmail
417+ p.Group = o.GitLabGroup
418+ p.EmailDomains = o.EmailDomains
419+
420+ if o.oidcVerifier != nil {
421+ p.Verifier = o.oidcVerifier
422+ } else {
423+ // Initialize with default verifier for gitlab.com
424+ ctx := context.Background()
425+
426+ provider, err := oidc.NewProvider(ctx, "https://gitlab.com")
427+ if err != nil {
428+ msgs = append(msgs, "failed to initialize oidc provider for gitlab.com")
429+ } else {
430+ p.Verifier = provider.Verifier(&oidc.Config{
431+ ClientID: o.ClientID,
432+ })
433+
434+ p.LoginURL, msgs = parseURL(provider.Endpoint().AuthURL, "login", msgs)
435+ p.RedeemURL, msgs = parseURL(provider.Endpoint().TokenURL, "redeem", msgs)
436+ }
437+ }
413438 case *providers.LoginGovProvider:
414439 p.AcrValues = o.AcrValues
415440 p.PubJWKURL, msgs = parseURL(o.PubJWKURL, "pubjwk", msgs)
providers/gitlab.go+227−31
@@ -1,62 +1,258 @@
11package providers
22
33import (
4+ "context"
5+ "encoding/json"
6+ "fmt"
7+ "io/ioutil"
48 "net/http"
5− "net/url"
9+ "strings"
10+ "time"
611
12+ oidc "github.com/coreos/go-oidc"
713 "github.com/pusher/oauth2_proxy/pkg/apis/sessions"
8− "github.com/pusher/oauth2_proxy/pkg/logger"
9− "github.com/pusher/oauth2_proxy/pkg/requests"
14+ "golang.org/x/oauth2"
1015)
1116
12−// GitLabProvider represents an GitLab based Identity Provider
17+// GitLabProvider represents a GitLab based Identity Provider
1318type GitLabProvider struct {
1419 *ProviderData
20+
21+ Group string
22+ EmailDomains []string
23+
24+ Verifier *oidc.IDTokenVerifier
25+ AllowUnverifiedEmail bool
1526}
1627
1728// NewGitLabProvider initiates a new GitLabProvider
1829func NewGitLabProvider(p *ProviderData) *GitLabProvider {
1930 p.ProviderName = "GitLab"
20− if p.LoginURL == nil || p.LoginURL.String() == "" {
21− p.LoginURL = &url.URL{
22− Scheme: "https",
23− Host: "gitlab.com",
24− Path: "/oauth/authorize",
25− }
31+
32+ if p.Scope == "" {
33+ p.Scope = "openid email"
34+ }
35+
36+ return &GitLabProvider{ProviderData: p}
37+}
38+
39+// Redeem exchanges the OAuth2 authentication token for an ID token
40+func (p *GitLabProvider) Redeem(redirectURL, code string) (s *sessions.SessionState, err error) {
41+ ctx := context.Background()
42+ c := oauth2.Config{
43+ ClientID: p.ClientID,
44+ ClientSecret: p.ClientSecret,
45+ Endpoint: oauth2.Endpoint{
46+ TokenURL: p.RedeemURL.String(),
47+ },
48+ RedirectURL: redirectURL,
49+ }
50+ token, err := c.Exchange(ctx, code)
51+ if err != nil {
52+ return nil, fmt.Errorf("token exchange: %v", err)
53+ }
54+ s, err = p.createSessionState(ctx, token)
55+ if err != nil {
56+ return nil, fmt.Errorf("unable to update session: %v", err)
57+ }
58+ return
59+}
60+
61+// RefreshSessionIfNeeded checks if the session has expired and uses the
62+// RefreshToken to fetch a new ID token if required
63+func (p *GitLabProvider) RefreshSessionIfNeeded(s *sessions.SessionState) (bool, error) {
64+ if s == nil || s.ExpiresOn.After(time.Now()) || s.RefreshToken == "" {
65+ return false, nil
66+ }
67+
68+ origExpiration := s.ExpiresOn
69+
70+ err := p.redeemRefreshToken(s)
71+ if err != nil {
72+ return false, fmt.Errorf("unable to redeem refresh token: %v", err)
73+ }
74+
75+ fmt.Printf("refreshed id token %s (expired on %s)\n", s, origExpiration)
76+ return true, nil
77+}
78+
79+func (p *GitLabProvider) redeemRefreshToken(s *sessions.SessionState) (err error) {
80+ c := oauth2.Config{
81+ ClientID: p.ClientID,
82+ ClientSecret: p.ClientSecret,
83+ Endpoint: oauth2.Endpoint{
84+ TokenURL: p.RedeemURL.String(),
85+ },
86+ }
87+ ctx := context.Background()
88+ t := &oauth2.Token{
89+ RefreshToken: s.RefreshToken,
90+ Expiry: time.Now().Add(-time.Hour),
91+ }
92+ token, err := c.TokenSource(ctx, t).Token()
93+ if err != nil {
94+ return fmt.Errorf("failed to get token: %v", err)
95+ }
96+ newSession, err := p.createSessionState(ctx, token)
97+ if err != nil {
98+ return fmt.Errorf("unable to update session: %v", err)
99+ }
100+ s.AccessToken = newSession.AccessToken
101+ s.IDToken = newSession.IDToken
102+ s.RefreshToken = newSession.RefreshToken
103+ s.CreatedAt = newSession.CreatedAt
104+ s.ExpiresOn = newSession.ExpiresOn
105+ s.Email = newSession.Email
106+ return
107+}
108+
109+type gitlabUserInfo struct {
110+ Username string `json:"nickname"`
111+ Email string `json:"email"`
112+ EmailVerified bool `json:"email_verified"`
113+ Groups []string `json:"groups"`
114+}
115+
116+func (p *GitLabProvider) getUserInfo(s *sessions.SessionState) (*gitlabUserInfo, error) {
117+ // Retrieve user info JSON
118+ // https://docs.gitlab.com/ee/integration/openid_connect_provider.html#shared-information
119+
120+ // Build user info url from login url of GitLab instance
121+ userInfoURL := *p.LoginURL
122+ userInfoURL.Path = "/oauth/userinfo"
123+
124+ req, err := http.NewRequest("GET", userInfoURL.String(), nil)
125+ if err != nil {
126+ return nil, fmt.Errorf("failed to create user info request: %v", err)
127+ }
128+ req.Header.Set("Authorization", "Bearer "+s.AccessToken)
129+
130+ resp, err := http.DefaultClient.Do(req)
131+ if err != nil {
132+ return nil, fmt.Errorf("failed to perform user info request: %v", err)
133+ }
134+ var body []byte
135+ body, err = ioutil.ReadAll(resp.Body)
136+ resp.Body.Close()
137+ if err != nil {
138+ return nil, fmt.Errorf("failed to read user info response: %v", err)
26139 }
27− if p.RedeemURL == nil || p.RedeemURL.String() == "" {
28− p.RedeemURL = &url.URL{
29− Scheme: "https",
30− Host: "gitlab.com",
31− Path: "/oauth/token",
140+
141+ if resp.StatusCode != 200 {
142+ return nil, fmt.Errorf("got %d during user info request: %s", resp.StatusCode, body)
143+ }
144+
145+ var userInfo gitlabUserInfo
146+ err = json.Unmarshal(body, &userInfo)
147+ if err != nil {
148+ return nil, fmt.Errorf("failed to parse user info: %v", err)
149+ }
150+
151+ return &userInfo, nil
152+}
153+
154+func (p *GitLabProvider) verifyGroupMembership(userInfo *gitlabUserInfo) error {
155+ if p.Group == "" {
156+ return nil
157+ }
158+
159+ // Collect user group memberships
160+ membershipSet := make(map[string]bool)
161+ for _, group := range userInfo.Groups {
162+ membershipSet[group] = true
163+ }
164+
165+ // Find a valid group that they are a member of
166+ validGroups := strings.Split(p.Group, " ")
167+ for _, validGroup := range validGroups {
168+ if _, ok := membershipSet[validGroup]; ok {
169+ return nil
32170 }
33171 }
34− if p.ValidateURL == nil || p.ValidateURL.String() == "" {
35− p.ValidateURL = &url.URL{
36− Scheme: "https",
37− Host: "gitlab.com",
38− Path: "/api/v4/user",
172+
173+ return fmt.Errorf("user is not a member of '%s'", p.Group)
174+}
175+
176+func (p *GitLabProvider) verifyEmailDomain(userInfo *gitlabUserInfo) error {
177+ if len(p.EmailDomains) == 0 || p.EmailDomains[0] == "*" {
178+ return nil
179+ }
180+
181+ for _, domain := range p.EmailDomains {
182+ if strings.HasSuffix(userInfo.Email, domain) {
183+ return nil
39184 }
40185 }
41− if p.Scope == "" {
42− p.Scope = "read_user"
186+
187+ return fmt.Errorf("user email is not one of the valid domains '%v'", p.EmailDomains)
188+}
189+
190+func (p *GitLabProvider) createSessionState(ctx context.Context, token *oauth2.Token) (*sessions.SessionState, error) {
191+ rawIDToken, ok := token.Extra("id_token").(string)
192+ if !ok {
193+ return nil, fmt.Errorf("token response did not contain an id_token")
43194 }
44− return &GitLabProvider{ProviderData: p}
195+
196+ // Parse and verify ID Token payload.
197+ idToken, err := p.Verifier.Verify(ctx, rawIDToken)
198+ if err != nil {
199+ return nil, fmt.Errorf("could not verify id_token: %v", err)
200+ }
201+
202+ return &sessions.SessionState{
203+ AccessToken: token.AccessToken,
204+ IDToken: rawIDToken,
205+ RefreshToken: token.RefreshToken,
206+ CreatedAt: time.Now(),
207+ ExpiresOn: idToken.Expiry,
208+ }, nil
209+}
210+
211+// ValidateSessionState checks that the session's IDToken is still valid
212+func (p *GitLabProvider) ValidateSessionState(s *sessions.SessionState) bool {
213+ ctx := context.Background()
214+ _, err := p.Verifier.Verify(ctx, s.IDToken)
215+ if err != nil {
216+ return false
217+ }
218+
219+ return true
45220}
46221
47222// GetEmailAddress returns the Account email address
48223func (p *GitLabProvider) GetEmailAddress(s *sessions.SessionState) (string, error) {
224+ // Retrieve user info
225+ userInfo, err := p.getUserInfo(s)
226+ if err != nil {
227+ return "", fmt.Errorf("failed to retrieve user info: %v", err)
228+ }
229+
230+ // Check if email is verified
231+ if !p.AllowUnverifiedEmail && !userInfo.EmailVerified {
232+ return "", fmt.Errorf("user email is not verified")
233+ }
234+
235+ // Check if email has valid domain
236+ err = p.verifyEmailDomain(userInfo)
237+ if err != nil {
238+ return "", fmt.Errorf("email domain check failed: %v", err)
239+ }
49240
50− req, err := http.NewRequest("GET",
51− p.ValidateURL.String()+"?access_token="+s.AccessToken, nil)
241+ // Check group membership
242+ err = p.verifyGroupMembership(userInfo)
52243 if err != nil {
53− logger.Printf("failed building request %s", err)
54− return "", err
244+ return "", fmt.Errorf("group membership check failed: %v", err)
55245 }
56− json, err := requests.Request(req)
246+
247+ return userInfo.Email, nil
248+}
249+
250+// GetUserName returns the Account user name
251+func (p *GitLabProvider) GetUserName(s *sessions.SessionState) (string, error) {
252+ userInfo, err := p.getUserInfo(s)
57253 if err != nil {
58− logger.Printf("failed making request %s", err)
59− return "", err
254+ return "", fmt.Errorf("failed to retrieve user info: %v", err)
60255 }
61− return json.Get("email").String()
256+
257+ return userInfo.Username, nil
62258}
providers/gitlab_test.go+98−60
@@ -25,104 +25,142 @@ func testGitLabProvider(hostname string) *GitLabProvider {
2525 updateURL(p.Data().ProfileURL, hostname)
2626 updateURL(p.Data().ValidateURL, hostname)
2727 }
28+
2829 return p
2930}
3031
31−func testGitLabBackend(payload string) *httptest.Server {
32− path := "/api/v4/user"
33− query := "access_token=imaginary_access_token"
32+func testGitLabBackend() *httptest.Server {
33+ userInfo := `
34+ {
35+ "nickname": "FooBar",
36+ "email": "foo@bar.com",
37+ "email_verified": false,
38+ "groups": ["foo", "bar"]
39+ }
40+ `
41+ authHeader := "Bearer gitlab_access_token"
3442
3543 return httptest.NewServer(http.HandlerFunc(
3644 func(w http.ResponseWriter, r *http.Request) {
37− if r.URL.Path != path || r.URL.RawQuery != query {
38− w.WriteHeader(404)
45+ if r.URL.Path == "/oauth/userinfo" {
46+ if r.Header["Authorization"][0] == authHeader {
47+ w.WriteHeader(200)
48+ w.Write([]byte(userInfo))
49+ } else {
50+ w.WriteHeader(401)
51+ }
3952 } else {
40− w.WriteHeader(200)
41− w.Write([]byte(payload))
53+ w.WriteHeader(404)
4254 }
4355 }))
4456}
4557
46−func TestGitLabProviderDefaults(t *testing.T) {
47− p := testGitLabProvider("")
48− assert.NotEqual(t, nil, p)
49− assert.Equal(t, "GitLab", p.Data().ProviderName)
50− assert.Equal(t, "https://gitlab.com/oauth/authorize",
51− p.Data().LoginURL.String())
52− assert.Equal(t, "https://gitlab.com/oauth/token",
53− p.Data().RedeemURL.String())
54− assert.Equal(t, "https://gitlab.com/api/v4/user",
55− p.Data().ValidateURL.String())
56− assert.Equal(t, "read_user", p.Data().Scope)
58+func TestGitLabProviderBadToken(t *testing.T) {
59+ b := testGitLabBackend()
60+ defer b.Close()
61+
62+ bURL, _ := url.Parse(b.URL)
63+ p := testGitLabProvider(bURL.Host)
64+
65+ session := &sessions.SessionState{AccessToken: "unexpected_gitlab_access_token"}
66+ _, err := p.GetEmailAddress(session)
67+ assert.NotEqual(t, nil, err)
5768}
5869
59−func TestGitLabProviderOverrides(t *testing.T) {
60− p := NewGitLabProvider(
61− &ProviderData{
62− LoginURL: &url.URL{
63− Scheme: "https",
64− Host: "example.com",
65− Path: "/oauth/auth"},
66− RedeemURL: &url.URL{
67− Scheme: "https",
68− Host: "example.com",
69− Path: "/oauth/token"},
70− ValidateURL: &url.URL{
71− Scheme: "https",
72− Host: "example.com",
73− Path: "/api/v4/user"},
74− Scope: "profile"})
75− assert.NotEqual(t, nil, p)
76− assert.Equal(t, "GitLab", p.Data().ProviderName)
77− assert.Equal(t, "https://example.com/oauth/auth",
78− p.Data().LoginURL.String())
79− assert.Equal(t, "https://example.com/oauth/token",
80− p.Data().RedeemURL.String())
81− assert.Equal(t, "https://example.com/api/v4/user",
82− p.Data().ValidateURL.String())
83− assert.Equal(t, "profile", p.Data().Scope)
70+func TestGitLabProviderUnverifiedEmailDenied(t *testing.T) {
71+ b := testGitLabBackend()
72+ defer b.Close()
73+
74+ bURL, _ := url.Parse(b.URL)
75+ p := testGitLabProvider(bURL.Host)
76+
77+ session := &sessions.SessionState{AccessToken: "gitlab_access_token"}
78+ _, err := p.GetEmailAddress(session)
79+ assert.NotEqual(t, nil, err)
8480}
8581
86−func TestGitLabProviderGetEmailAddress(t *testing.T) {
87− b := testGitLabBackend("{\"email\": \"michael.bland@gsa.gov\"}")
82+func TestGitLabProviderUnverifiedEmailAllowed(t *testing.T) {
83+ b := testGitLabBackend()
8884 defer b.Close()
8985
9086 bURL, _ := url.Parse(b.URL)
9187 p := testGitLabProvider(bURL.Host)
88+ p.AllowUnverifiedEmail = true
9289
93− session := &sessions.SessionState{AccessToken: "imaginary_access_token"}
90+ session := &sessions.SessionState{AccessToken: "gitlab_access_token"}
9491 email, err := p.GetEmailAddress(session)
9592 assert.Equal(t, nil, err)
96− assert.Equal(t, "michael.bland@gsa.gov", email)
93+ assert.Equal(t, "foo@bar.com", email)
9794}
9895
99−// Note that trying to trigger the "failed building request" case is not
100−// practical, since the only way it can fail is if the URL fails to parse.
101−func TestGitLabProviderGetEmailAddressFailedRequest(t *testing.T) {
102− b := testGitLabBackend("unused payload")
96+func TestGitLabProviderUsername(t *testing.T) {
97+ b := testGitLabBackend()
10398 defer b.Close()
10499
105100 bURL, _ := url.Parse(b.URL)
106101 p := testGitLabProvider(bURL.Host)
102+ p.AllowUnverifiedEmail = true
107103
108− // We'll trigger a request failure by using an unexpected access
109− // token. Alternatively, we could allow the parsing of the payload as
110− // JSON to fail.
111− session := &sessions.SessionState{AccessToken: "unexpected_access_token"}
104+ session := &sessions.SessionState{AccessToken: "gitlab_access_token"}
105+ username, err := p.GetUserName(session)
106+ assert.Equal(t, nil, err)
107+ assert.Equal(t, "FooBar", username)
108+}
109+
110+func TestGitLabProviderGroupMembershipValid(t *testing.T) {
111+ b := testGitLabBackend()
112+ defer b.Close()
113+
114+ bURL, _ := url.Parse(b.URL)
115+ p := testGitLabProvider(bURL.Host)
116+ p.AllowUnverifiedEmail = true
117+ p.Group = "foo"
118+
119+ session := &sessions.SessionState{AccessToken: "gitlab_access_token"}
112120 email, err := p.GetEmailAddress(session)
121+ assert.Equal(t, nil, err)
122+ assert.Equal(t, "foo@bar.com", email)
123+}
124+
125+func TestGitLabProviderGroupMembershipMissing(t *testing.T) {
126+ b := testGitLabBackend()
127+ defer b.Close()
128+
129+ bURL, _ := url.Parse(b.URL)
130+ p := testGitLabProvider(bURL.Host)
131+ p.AllowUnverifiedEmail = true
132+ p.Group = "baz"
133+
134+ session := &sessions.SessionState{AccessToken: "gitlab_access_token"}
135+ _, err := p.GetEmailAddress(session)
113136 assert.NotEqual(t, nil, err)
114− assert.Equal(t, "", email)
115137}
116138
117−func TestGitLabProviderGetEmailAddressEmailNotPresentInPayload(t *testing.T) {
118− b := testGitLabBackend("{\"foo\": \"bar\"}")
139+func TestGitLabProviderEmailDomainValid(t *testing.T) {
140+ b := testGitLabBackend()
119141 defer b.Close()
120142
121143 bURL, _ := url.Parse(b.URL)
122144 p := testGitLabProvider(bURL.Host)
145+ p.AllowUnverifiedEmail = true
146+ p.EmailDomains = []string{"bar.com"}
123147
124− session := &sessions.SessionState{AccessToken: "imaginary_access_token"}
148+ session := &sessions.SessionState{AccessToken: "gitlab_access_token"}
125149 email, err := p.GetEmailAddress(session)
150+ assert.Equal(t, nil, err)
151+ assert.Equal(t, "foo@bar.com", email)
152+}
153+
154+func TestGitLabProviderEmailDomainInvalid(t *testing.T) {
155+ b := testGitLabBackend()
156+ defer b.Close()
157+
158+ bURL, _ := url.Parse(b.URL)
159+ p := testGitLabProvider(bURL.Host)
160+ p.AllowUnverifiedEmail = true
161+ p.EmailDomains = []string{"baz.com"}
162+
163+ session := &sessions.SessionState{AccessToken: "gitlab_access_token"}
164+ _, err := p.GetEmailAddress(session)
126165 assert.NotEqual(t, nil, err)
127− assert.Equal(t, "", email)
128166}
providers/google.go+26−55
@@ -189,71 +189,42 @@ func getAdminService(adminEmail string, credentialsReader io.Reader) *admin.Serv
189189}
190190
191191func userInGroup(service *admin.Service, groups []string, email string) bool {
192− user, err := fetchUser(service, email)
193− if err != nil {
194− logger.Printf("Warning: unable to fetch user: %v", err)
195− user = nil
196− }
197−
198192 for _, group := range groups {
199− members, err := fetchGroupMembers(service, group)
193+ // Use the HasMember API to checking for the user's presence in each group or nested subgroups
194+ req := service.Members.HasMember(group, email)
195+ r, err := req.Do()
200196 if err != nil {
201− if err, ok := err.(*googleapi.Error); ok && err.Code == 404 {
202− logger.Printf("error fetching members for group %s: group does not exist", group)
203− } else {
204− logger.Printf("error fetching group members: %v", err)
205− return false
206− }
207− }
197+ err, ok := err.(*googleapi.Error)
198+ if ok && err.Code == 404 {
199+ logger.Printf("error checking membership in group %s: group does not exist", group)
200+ } else if ok && err.Code == 400 {
201+ // It is possible for Members.HasMember to return false even if the email is a group member.
202+ // One case that can cause this is if the user email is from a different domain than the group,
203+ // e.g. "member@otherdomain.com" in the group "group@mydomain.com" will result in a 400 error
204+ // from the HasMember API. In that case, attempt to query the member object directly from the group.
205+ req := service.Members.Get(group, email)
206+ r, err := req.Do()
208207
209− for _, member := range members {
210− if member.Email == email {
211− return true
212− }
213− if user == nil {
214− continue
215− }
216− switch member.Type {
217− case "CUSTOMER":
218− if member.Id == user.CustomerId {
219− return true
208+ if err != nil {
209+ logger.Printf("error using get API to check member %s of google group %s: user not in the group", email, group)
210+ continue
220211 }
221− case "USER":
222− if member.Id == user.Id {
212+
213+ // If the non-domain user is found within the group, still verify that they are "ACTIVE".
214+ // Do not count the user as belonging to a group if they have another status ("ARCHIVED", "SUSPENDED", or "UNKNOWN").
215+ if r.Status == "ACTIVE" {
223216 return true
224217 }
218+ } else {
219+ logger.Printf("error checking group membership: %v", err)
225220 }
221+ continue
226222 }
227− }
228− return false
229−}
230−
231−func fetchUser(service *admin.Service, email string) (*admin.User, error) {
232− user, err := service.Users.Get(email).Do()
233− return user, err
234−}
235−
236−func fetchGroupMembers(service *admin.Service, group string) ([]*admin.Member, error) {
237− members := []*admin.Member{}
238− pageToken := ""
239− for {
240− req := service.Members.List(group)
241− if pageToken != "" {
242− req.PageToken(pageToken)
243− }
244− r, err := req.Do()
245− if err != nil {
246− return nil, err
247− }
248− for _, member := range r.Members {
249− members = append(members, member)
250− }
251− if r.NextPageToken == "" {
252− break
223+ if r.IsMember {
224+ return true
253225 }
254− pageToken = r.NextPageToken
255226 }
256− return members, nil
227+ return false
257228}
258229
259230// ValidateGroup validates that the provided email exists in the configured Google
providers/google_test.go+36−15
@@ -1,6 +1,7 @@
11package providers
22
33import (
4+ "context"
45 "encoding/base64"
56 "encoding/json"
67 "fmt"
@@ -12,6 +13,7 @@ import (
1213 "github.com/stretchr/testify/assert"
1314
1415 admin "google.golang.org/api/admin/directory/v1"
16+ option "google.golang.org/api/option"
1517)
1618
1719func newRedeemServer(body []byte) (*url.URL, *httptest.Server) {
@@ -185,34 +187,53 @@ func TestGoogleProviderGetEmailAddressEmailMissing(t *testing.T) {
185187
186188func TestGoogleProviderUserInGroup(t *testing.T) {
187189 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
188− if r.URL.Path == "/users/member-by-email@example.com" {
189− fmt.Fprintln(w, "{}")
190− } else if r.URL.Path == "/users/non-member-by-email@example.com" {
191− fmt.Fprintln(w, "{}")
192− } else if r.URL.Path == "/users/member-by-id@example.com" {
193− fmt.Fprintln(w, "{\"id\": \"member-id\"}")
194− } else if r.URL.Path == "/users/non-member-by-id@example.com" {
195− fmt.Fprintln(w, "{\"id\": \"non-member-id\"}")
196− } else if r.URL.Path == "/groups/group@example.com/members" {
197− fmt.Fprintln(w, "{\"members\": [{\"email\": \"member-by-email@example.com\"}, {\"id\": \"member-id\", \"type\": \"USER\"}]}")
190+ if r.URL.Path == "/groups/group@example.com/hasMember/member-in-domain@example.com" {
191+ fmt.Fprintln(w, `{"isMember": true}`)
192+ } else if r.URL.Path == "/groups/group@example.com/hasMember/non-member-in-domain@example.com" {
193+ fmt.Fprintln(w, `{"isMember": false}`)
194+ } else if r.URL.Path == "/groups/group@example.com/hasMember/member-out-of-domain@otherexample.com" {
195+ http.Error(
196+ w,
197+ `{"error": {"errors": [{"domain": "global","reason": "invalid","message": "Invalid Input: memberKey"}],"code": 400,"message": "Invalid Input: memberKey"}}`,
198+ http.StatusBadRequest,
199+ )
200+ } else if r.URL.Path == "/groups/group@example.com/hasMember/non-member-out-of-domain@otherexample.com" {
201+ http.Error(
202+ w,
203+ `{"error": {"errors": [{"domain": "global","reason": "invalid","message": "Invalid Input: memberKey"}],"code": 400,"message": "Invalid Input: memberKey"}}`,
204+ http.StatusBadRequest,
205+ )
206+ } else if r.URL.Path == "/groups/group@example.com/members/non-member-out-of-domain@otherexample.com" {
207+ // note that the client currently doesn't care what this response text or code is - any error here results in failure to match the group
208+ http.Error(
209+ w,
210+ `{"error": {"errors": [{"domain": "global","reason": "notFound","message": "Resource Not Found: memberKey"}],"code": 404,"message": "Resource Not Found: memberKey"}}`,
211+ http.StatusNotFound,
212+ )
213+ } else if r.URL.Path == "/groups/group@example.com/members/member-out-of-domain@otherexample.com" {
214+ fmt.Fprintln(w,
215+ `{"kind": "admin#directory#member","etag":"12345","id":"1234567890","email": "member-out-of-domain@otherexample.com","role": "MEMBER","type": "USER","status": "ACTIVE","delivery_settings": "ALL_MAIL"}}`,
216+ )
198217 }
199218 }))
200219 defer ts.Close()
201220
202221 client := ts.Client()
203− service, err := admin.New(client)
222+ ctx := context.Background()
223+
224+ service, err := admin.NewService(ctx, option.WithHTTPClient(client))
204225 service.BasePath = ts.URL
205226 assert.Equal(t, nil, err)
206227
207− result := userInGroup(service, []string{"group@example.com"}, "member-by-email@example.com")
228+ result := userInGroup(service, []string{"group@example.com"}, "member-in-domain@example.com")
208229 assert.True(t, result)
209230
210− result = userInGroup(service, []string{"group@example.com"}, "member-by-id@example.com")
231+ result = userInGroup(service, []string{"group@example.com"}, "member-out-of-domain@otherexample.com")
211232 assert.True(t, result)
212233
213− result = userInGroup(service, []string{"group@example.com"}, "non-member-by-id@example.com")
234+ result = userInGroup(service, []string{"group@example.com"}, "non-member-in-domain@example.com")
214235 assert.False(t, result)
215236
216− result = userInGroup(service, []string{"group@example.com"}, "non-member-by-email@example.com")
237+ result = userInGroup(service, []string{"group@example.com"}, "non-member-out-of-domain@otherexample.com")
217238 assert.False(t, result)
218239}