Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add preferredEmailDomain config option for GitHub connector #2740

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 55 additions & 20 deletions connector/github/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,17 @@ var (

// Config holds configuration options for github logins.
type Config struct {
ClientID string `json:"clientID"`
ClientSecret string `json:"clientSecret"`
RedirectURI string `json:"redirectURI"`
Org string `json:"org"`
Orgs []Org `json:"orgs"`
HostName string `json:"hostName"`
RootCA string `json:"rootCA"`
TeamNameField string `json:"teamNameField"`
LoadAllGroups bool `json:"loadAllGroups"`
UseLoginAsID bool `json:"useLoginAsID"`
ClientID string `json:"clientID"`
ClientSecret string `json:"clientSecret"`
RedirectURI string `json:"redirectURI"`
Org string `json:"org"`
Orgs []Org `json:"orgs"`
HostName string `json:"hostName"`
RootCA string `json:"rootCA"`
TeamNameField string `json:"teamNameField"`
LoadAllGroups bool `json:"loadAllGroups"`
UseLoginAsID bool `json:"useLoginAsID"`
PreferredEmailDomain string `json:"preferredEmailDomain"`
}

// Org holds org-team filters, in which teams are optional.
Expand All @@ -75,14 +76,15 @@ func (c *Config) Open(id string, logger log.Logger) (connector.Connector, error)
}

g := githubConnector{
redirectURI: c.RedirectURI,
org: c.Org,
orgs: c.Orgs,
clientID: c.ClientID,
clientSecret: c.ClientSecret,
apiURL: apiURL,
logger: logger,
useLoginAsID: c.UseLoginAsID,
redirectURI: c.RedirectURI,
org: c.Org,
orgs: c.Orgs,
clientID: c.ClientID,
clientSecret: c.ClientSecret,
apiURL: apiURL,
logger: logger,
useLoginAsID: c.UseLoginAsID,
preferredEmailDomain: c.PreferredEmailDomain,
}

if c.HostName != "" {
Expand Down Expand Up @@ -149,6 +151,8 @@ type githubConnector struct {
loadAllGroups bool
// if set to true will use the user's handle rather than their numeric id as the ID
useLoginAsID bool
// the domain to be preferred among the user's emails. e.g. "github.com"
preferredEmailDomain string
}

// groupsRequired returns whether dex requires GitHub's 'read:org' scope. Dex
Expand Down Expand Up @@ -548,7 +552,20 @@ type userEmail struct {
// The HTTP client is expected to be constructed by the golang.org/x/oauth2 package,
// which inserts a bearer token as part of the request.
func (c *githubConnector) userEmail(ctx context.Context, client *http.Client) (string, error) {
var (
preferredEmailDomainRegexp *regexp.Regexp
primaryEmail userEmail
preferredEmails []userEmail
)

apiURL := c.apiURL + "/user/emails"

if c.preferredEmailDomain != "" {
globExtracted := strings.ReplaceAll(c.preferredEmailDomain, "*", "[a-zA-Z0-9][A-Za-z0-9-][a-zA-Z0-9-]+")
nabokihms marked this conversation as resolved.
Show resolved Hide resolved
patten := fmt.Sprintf("^%s$", globExtracted)
preferredEmailDomainRegexp = regexp.MustCompile(patten)
}

for {
// https://developer.github.com/v3/users/emails/#list-email-addresses-for-a-user
var (
Expand All @@ -575,7 +592,17 @@ func (c *githubConnector) userEmail(ctx context.Context, client *http.Client) (s
}

if email.Verified && email.Primary {
return email.Email, nil
primaryEmail = email
}

if preferredEmailDomainRegexp != nil {
_, domainPart, ok := strings.Cut(email.Email, "@")
if !ok {
return "", errors.New("github: invalid format email is detected")
}
if email.Verified && preferredEmailDomainRegexp.Match([]byte(domainPart)) {
nobuyo marked this conversation as resolved.
Show resolved Hide resolved
preferredEmails = append(preferredEmails, email)
}
}
}

Expand All @@ -584,7 +611,15 @@ func (c *githubConnector) userEmail(ctx context.Context, client *http.Client) (s
}
}

return "", errors.New("github: user has no verified, primary email")
if len(preferredEmails) > 0 {
return preferredEmails[0].Email, nil
}

if (primaryEmail != userEmail{}) {
nobuyo marked this conversation as resolved.
Show resolved Hide resolved
return primaryEmail.Email, nil
}

return "", errors.New("github: user has no verified, primary email or preferred-domain email")
}

// userInOrg queries the GitHub API for a users' org membership.
Expand Down
196 changes: 196 additions & 0 deletions connector/github/github_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,196 @@ func TestLoginUsedAsIDWhenConfigured(t *testing.T) {
expectEquals(t, identity.Username, "Joe Bloggs")
}

func TestPreferredEmailDomainConfigured(t *testing.T) {
ctx := context.Background()
s := newTestServer(map[string]testResponse{
"/user": {data: user{Login: "some-login", ID: 12345678, Name: "Joe Bloggs"}},
"/user/emails": {
data: []userEmail{
{
Email: "some@email.com",
Verified: true,
Primary: true,
},
{
Email: "another@email.com",
Verified: true,
Primary: false,
},
{
Email: "some@preferred-domain.com",
Verified: true,
Primary: false,
},
{
Email: "another@preferred-domain.com",
Verified: true,
Primary: false,
},
},
},
})
defer s.Close()

hostURL, err := url.Parse(s.URL)
expectNil(t, err)

client := newClient()
c := githubConnector{apiURL: s.URL, hostName: hostURL.Host, httpClient: client, preferredEmailDomain: "preferred-domain.com"}

u, err := c.user(ctx, client)
expectNil(t, err)
expectEquals(t, u.Email, "some@preferred-domain.com")
}

func TestPreferredEmailDomainConfiguredWithGlob(t *testing.T) {
ctx := context.Background()
s := newTestServer(map[string]testResponse{
"/user": {data: user{Login: "some-login", ID: 12345678, Name: "Joe Bloggs"}},
"/user/emails": {
data: []userEmail{
{
Email: "some@email.com",
Verified: true,
Primary: true,
},
{
Email: "another@email.com",
Verified: true,
Primary: false,
},
{
Email: "some@another.preferred-domain.com",
Verified: true,
Primary: false,
},
{
Email: "some@sub-domain.preferred-domain.co",
Verified: true,
Primary: false,
},
},
},
})
defer s.Close()

hostURL, err := url.Parse(s.URL)
expectNil(t, err)

client := newClient()
c := githubConnector{apiURL: s.URL, hostName: hostURL.Host, httpClient: client, preferredEmailDomain: "*.preferred-domain.co"}

u, err := c.user(ctx, client)
expectNil(t, err)
expectEquals(t, u.Email, "some@sub-domain.preferred-domain.co")
}

func TestPreferredEmailDomainConfigured_UserHasNoPreferredDomainEmail(t *testing.T) {
ctx := context.Background()
s := newTestServer(map[string]testResponse{
"/user": {data: user{Login: "some-login", ID: 12345678, Name: "Joe Bloggs"}},
"/user/emails": {
data: []userEmail{
{
Email: "some@email.com",
Verified: true,
Primary: true,
},
{
Email: "another@email.com",
Verified: true,
Primary: false,
},
},
},
})
defer s.Close()

hostURL, err := url.Parse(s.URL)
expectNil(t, err)

client := newClient()
c := githubConnector{apiURL: s.URL, hostName: hostURL.Host, httpClient: client, preferredEmailDomain: "preferred-domain.com"}

u, err := c.user(ctx, client)
expectNil(t, err)
expectEquals(t, u.Email, "some@email.com")
}

func TestPreferredEmailDomainNotConfigured(t *testing.T) {
ctx := context.Background()
s := newTestServer(map[string]testResponse{
"/user": {data: user{Login: "some-login", ID: 12345678, Name: "Joe Bloggs"}},
"/user/emails": {
data: []userEmail{
{
Email: "some@email.com",
Verified: true,
Primary: true,
},
{
Email: "another@email.com",
Verified: true,
Primary: false,
},
{
Email: "some@preferred-domain.com",
Verified: true,
Primary: false,
},
},
},
})
defer s.Close()

hostURL, err := url.Parse(s.URL)
expectNil(t, err)

client := newClient()
c := githubConnector{apiURL: s.URL, hostName: hostURL.Host, httpClient: client}

u, err := c.user(ctx, client)
expectNil(t, err)
expectEquals(t, u.Email, "some@email.com")
}

func TestPreferredEmailDomainConfigured_Error_BothPrimaryAndPreferredDomainEmailNotFound(t *testing.T) {
ctx := context.Background()
s := newTestServer(map[string]testResponse{
"/user": {data: user{Login: "some-login", ID: 12345678, Name: "Joe Bloggs"}},
"/user/emails": {
data: []userEmail{
{
Email: "some@email.com",
Verified: true,
Primary: false,
},
{
Email: "another@email.com",
Verified: true,
Primary: false,
},
{
Email: "some@preferred-domain.com",
Verified: true,
Primary: false,
},
},
},
})
defer s.Close()

hostURL, err := url.Parse(s.URL)
expectNil(t, err)

client := newClient()
c := githubConnector{apiURL: s.URL, hostName: hostURL.Host, httpClient: client, preferredEmailDomain: "foo.bar"}

_, err = c.user(ctx, client)
expectNotNil(t, err, "Email not found error")
expectEquals(t, err.Error(), "github: user has no verified, primary email or preferred-domain email")
}

func newTestServer(responses map[string]testResponse) *httptest.Server {
var s *httptest.Server
s = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -231,6 +421,12 @@ func expectNil(t *testing.T, a interface{}) {
}
}

func expectNotNil(t *testing.T, a interface{}, msg string) {
if a == nil {
t.Errorf("Expected %+v to not to be nil", msg)
}
}

func expectEquals(t *testing.T, a interface{}, b interface{}) {
if !reflect.DeepEqual(a, b) {
t.Errorf("Expected %+v to equal %+v", a, b)
Expand Down