git.iko.soy/typeable/oauth2-proxy
on master help sign in
Rework GitLab provider (#231)

* Initial version of OIDC based GitLab provider * Add support for email domain check to GitLab provider * Add gitlab.com as default issuer for GitLab provider * Update documentation for GitLab provider * Update unit tests for new GitLab provider implementation * Update CHANGELOG for GitLab provider * Rename GitLab test access token as response to linter

commit4de49983fb682e15460d9cd1670e37a15f7782ab authorAlexander Overvoorde <overv161@gmail.com> dateTue 6 Aug 2019, 13:20 (7 years ago) parent7d910c0
7 files changed+363−95
CHANGELOG.md+6 docs/2_auth.md+6−4 docs/configuration/configuration.md+1 main.go+1 options.go+24 providers/gitlab.go+227−31 providers/gitlab_test.go+98−60
CHANGELOG.md+6
@@ -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 (`-`).
@@ -32,6 +37,7 @@
3237## Changes since v3.2.0
3338
3439- [#224](https://github.com/pusher/oauth2_proxy/pull/224) Check Google group membership using hasMember to support nested groups and external users (@jpalpant)
40+- [#231](https://github.com/pusher/oauth2_proxy/pull/231) Add optional group membership and email domain checks to the GitLab provider (@Overv)
3541- [#178](https://github.com/pusher/outh2_proxy/pull/178) Add Silence Ping Logging and Exclude Logging Paths flags (@kskewes)
3642- [#209](https://github.com/pusher/outh2_proxy/pull/209) Improve docker build caching of layers (@dekimsey)
3743- [#186](https://github.com/pusher/oauth2_proxy/pull/186) Make config consistent (@JoelSpeed)
docs/2_auth.md+6−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
docs/configuration/configuration.md+1
@@ -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
main.go+1
@@ -57,6 +57,7 @@ func main() {
5757 flagSet.String("azure-tenant", "common", "go to a tenant-specific or common (tenant-independent) endpoint.")
5858 flagSet.String("github-org", "", "restrict logins to members of this organisation")
5959 flagSet.String("github-team", "", "restrict logins to members of this team")
60+ flagSet.String("gitlab-group", "", "restrict logins to members of this group")
6061 flagSet.Var(&googleGroups, "google-group", "restrict logins to members of this google group (may be given multiple times).")
6162 flagSet.String("google-admin-email", "", "the google admin to impersonate for api calls")
6263 flagSet.String("google-service-account-json", "", "the path to the service account json credentials")
options.go+24
@@ -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"`
@@ -410,6 +411,29 @@ func parseProviderInfo(o *Options, msgs []string) []string {
410411 } else {
411412 p.Verifier = o.oidcVerifier
412413 }
414+ case *providers.GitLabProvider:
415+ p.AllowUnverifiedEmail = o.InsecureOIDCAllowUnverifiedEmail
416+ p.Group = o.GitLabGroup
417+ p.EmailDomains = o.EmailDomains
418+
419+ if o.oidcVerifier != nil {
420+ p.Verifier = o.oidcVerifier
421+ } else {
422+ // Initialize with default verifier for gitlab.com
423+ ctx := context.Background()
424+
425+ provider, err := oidc.NewProvider(ctx, "https://gitlab.com")
426+ if err != nil {
427+ msgs = append(msgs, "failed to initialize oidc provider for gitlab.com")
428+ } else {
429+ p.Verifier = provider.Verifier(&oidc.Config{
430+ ClientID: o.ClientID,
431+ })
432+
433+ p.LoginURL, msgs = parseURL(provider.Endpoint().AuthURL, "login", msgs)
434+ p.RedeemURL, msgs = parseURL(provider.Endpoint().TokenURL, "redeem", msgs)
435+ }
436+ }
413437 case *providers.LoginGovProvider:
414438 p.AcrValues = o.AcrValues
415439 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}