oauth2_proxy/providers/github.go

305 lines
7.1 KiB
Go
Raw Permalink Normal View History

2015-05-21 03:23:48 +00:00
package providers
import (
"encoding/json"
2015-06-06 18:15:43 +00:00
"fmt"
2015-05-21 03:23:48 +00:00
"io/ioutil"
"net/http"
"net/url"
2016-06-20 12:12:07 +00:00
"path"
"strconv"
2016-06-20 11:17:39 +00:00
"strings"
2019-05-24 16:08:48 +00:00
"github.com/pusher/oauth2_proxy/pkg/logger"
2019-05-05 12:33:13 +00:00
"github.com/pusher/oauth2_proxy/pkg/apis/sessions"
2015-05-21 03:23:48 +00:00
)
// GitHubProvider represents an GitHub based Identity Provider
2015-05-21 03:23:48 +00:00
type GitHubProvider struct {
*ProviderData
Org string
Team string
}
// NewGitHubProvider initiates a new GitHubProvider
2015-05-21 03:23:48 +00:00
func NewGitHubProvider(p *ProviderData) *GitHubProvider {
p.ProviderName = "GitHub"
if p.LoginURL == nil || p.LoginURL.String() == "" {
p.LoginURL = &url.URL{
2015-05-21 03:23:48 +00:00
Scheme: "https",
Host: "github.com",
Path: "/login/oauth/authorize",
}
}
if p.RedeemURL == nil || p.RedeemURL.String() == "" {
p.RedeemURL = &url.URL{
2015-05-21 03:23:48 +00:00
Scheme: "https",
Host: "github.com",
Path: "/login/oauth/access_token",
}
}
2016-06-20 12:12:07 +00:00
// ValidationURL is the API Base URL
if p.ValidateURL == nil || p.ValidateURL.String() == "" {
p.ValidateURL = &url.URL{
2015-05-21 03:23:48 +00:00
Scheme: "https",
Host: "api.github.com",
2016-06-20 12:12:07 +00:00
Path: "/",
2015-05-21 03:23:48 +00:00
}
}
if p.Scope == "" {
p.Scope = "user:email"
}
return &GitHubProvider{ProviderData: p}
}
// SetOrgTeam adds GitHub org reading parameters to the OAuth2 scope
2015-05-21 03:23:48 +00:00
func (p *GitHubProvider) SetOrgTeam(org, team string) {
p.Org = org
p.Team = team
if org != "" || team != "" {
p.Scope += " read:org"
}
}
func (p *GitHubProvider) hasOrg(accessToken string) (bool, error) {
// https://developer.github.com/v3/orgs/#list-your-organizations
var orgs []struct {
Login string `json:"login"`
}
type orgsPage []struct {
Login string `json:"login"`
}
pn := 1
for {
params := url.Values{
"limit": {"200"},
"page": {strconv.Itoa(pn)},
}
endpoint := &url.URL{
Scheme: p.ValidateURL.Scheme,
Host: p.ValidateURL.Host,
Path: path.Join(p.ValidateURL.Path, "/user/orgs"),
RawQuery: params.Encode(),
}
req, _ := http.NewRequest("GET", endpoint.String(), nil)
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("Authorization", fmt.Sprintf("token %s", accessToken))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return false, err
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return false, err
}
if resp.StatusCode != 200 {
return false, fmt.Errorf(
"got %d from %q %s", resp.StatusCode, endpoint.String(), body)
}
var op orgsPage
if err := json.Unmarshal(body, &op); err != nil {
return false, err
}
if len(op) == 0 {
break
}
orgs = append(orgs, op...)
2018-11-29 14:26:41 +00:00
pn++
}
var presentOrgs []string
for _, org := range orgs {
if p.Org == org.Login {
logger.Printf("Found Github Organization: %q", org.Login)
return true, nil
}
presentOrgs = append(presentOrgs, org.Login)
}
logger.Printf("Missing Organization:%q in %v", p.Org, presentOrgs)
return false, nil
}
2015-05-21 03:23:48 +00:00
func (p *GitHubProvider) hasOrgAndTeam(accessToken string) (bool, error) {
// https://developer.github.com/v3/orgs/teams/#list-user-teams
2015-05-21 03:23:48 +00:00
var teams []struct {
Name string `json:"name"`
Slug string `json:"slug"`
Org struct {
Login string `json:"login"`
} `json:"organization"`
}
params := url.Values{
"limit": {"200"},
2015-05-21 03:23:48 +00:00
}
2016-06-20 12:12:07 +00:00
endpoint := &url.URL{
Scheme: p.ValidateURL.Scheme,
Host: p.ValidateURL.Host,
Path: path.Join(p.ValidateURL.Path, "/user/teams"),
RawQuery: params.Encode(),
}
req, _ := http.NewRequest("GET", endpoint.String(), nil)
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("Authorization", fmt.Sprintf("token %s", accessToken))
2015-05-21 03:23:48 +00:00
resp, err := http.DefaultClient.Do(req)
if err != nil {
return false, err
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return false, err
}
2015-06-06 18:15:43 +00:00
if resp.StatusCode != 200 {
return false, fmt.Errorf(
"got %d from %q %s", resp.StatusCode, endpoint.String(), body)
2015-06-06 18:15:43 +00:00
}
2015-05-21 03:23:48 +00:00
if err := json.Unmarshal(body, &teams); err != nil {
2015-06-06 18:15:43 +00:00
return false, fmt.Errorf("%s unmarshaling %s", err, body)
2015-05-21 03:23:48 +00:00
}
var hasOrg bool
presentOrgs := make(map[string]bool)
var presentTeams []string
2015-05-21 03:23:48 +00:00
for _, team := range teams {
presentOrgs[team.Org.Login] = true
2015-05-21 03:23:48 +00:00
if p.Org == team.Org.Login {
hasOrg = true
2016-02-17 10:21:27 +00:00
ts := strings.Split(p.Team, ",")
for _, t := range ts {
if t == team.Slug {
logger.Printf("Found Github Organization:%q Team:%q (Name:%q)", team.Org.Login, team.Slug, team.Name)
2016-02-17 10:21:27 +00:00
return true, nil
}
2015-05-21 03:23:48 +00:00
}
presentTeams = append(presentTeams, team.Slug)
}
}
if hasOrg {
logger.Printf("Missing Team:%q from Org:%q in teams: %v", p.Team, p.Org, presentTeams)
} else {
var allOrgs []string
2018-11-29 14:26:41 +00:00
for org := range presentOrgs {
allOrgs = append(allOrgs, org)
2015-05-21 03:23:48 +00:00
}
logger.Printf("Missing Organization:%q in %#v", p.Org, allOrgs)
2015-05-21 03:23:48 +00:00
}
return false, nil
}
// GetEmailAddress returns the Account email address
2019-05-05 12:33:13 +00:00
func (p *GitHubProvider) GetEmailAddress(s *sessions.SessionState) (string, error) {
2015-05-21 03:23:48 +00:00
var emails []struct {
2019-03-11 17:52:08 +00:00
Email string `json:"email"`
Primary bool `json:"primary"`
2019-03-11 17:52:08 +00:00
Verified bool `json:"verified"`
2015-05-21 03:23:48 +00:00
}
// if we require an Org or Team, check that first
if p.Org != "" {
if p.Team != "" {
if ok, err := p.hasOrgAndTeam(s.AccessToken); err != nil || !ok {
return "", err
}
} else {
if ok, err := p.hasOrg(s.AccessToken); err != nil || !ok {
return "", err
}
2015-05-21 03:23:48 +00:00
}
}
2016-06-20 12:12:07 +00:00
endpoint := &url.URL{
Scheme: p.ValidateURL.Scheme,
Host: p.ValidateURL.Host,
Path: path.Join(p.ValidateURL.Path, "/user/emails"),
2016-06-20 12:12:07 +00:00
}
req, _ := http.NewRequest("GET", endpoint.String(), nil)
req.Header.Set("Authorization", fmt.Sprintf("token %s", s.AccessToken))
resp, err := http.DefaultClient.Do(req)
2015-05-21 03:23:48 +00:00
if err != nil {
return "", err
}
body, err := ioutil.ReadAll(resp.Body)
2015-05-21 03:23:48 +00:00
resp.Body.Close()
if err != nil {
return "", err
}
2015-06-06 18:15:43 +00:00
if resp.StatusCode != 200 {
return "", fmt.Errorf("got %d from %q %s",
resp.StatusCode, endpoint.String(), body)
2015-06-06 18:15:43 +00:00
}
2015-05-21 03:23:48 +00:00
logger.Printf("got %d from %q %s", resp.StatusCode, endpoint.String(), body)
2015-05-21 03:23:48 +00:00
if err := json.Unmarshal(body, &emails); err != nil {
2015-06-06 18:15:43 +00:00
return "", fmt.Errorf("%s unmarshaling %s", err, body)
2015-05-21 03:23:48 +00:00
}
for _, email := range emails {
if email.Primary && email.Verified {
2015-05-21 03:23:48 +00:00
return email.Email, nil
}
}
2015-07-24 20:23:19 +00:00
return "", nil
2015-05-21 03:23:48 +00:00
}
// GetUserName returns the Account user name
2019-05-05 12:33:13 +00:00
func (p *GitHubProvider) GetUserName(s *sessions.SessionState) (string, error) {
var user struct {
Login string `json:"login"`
Email string `json:"email"`
}
endpoint := &url.URL{
Scheme: p.ValidateURL.Scheme,
Host: p.ValidateURL.Host,
Path: path.Join(p.ValidateURL.Path, "/user"),
}
req, err := http.NewRequest("GET", endpoint.String(), nil)
if err != nil {
return "", fmt.Errorf("could not create new GET request: %v", err)
}
req.Header.Set("Authorization", fmt.Sprintf("token %s", s.AccessToken))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
body, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return "", err
}
if resp.StatusCode != 200 {
return "", fmt.Errorf("got %d from %q %s",
resp.StatusCode, endpoint.String(), body)
}
logger.Printf("got %d from %q %s", resp.StatusCode, endpoint.String(), body)
if err := json.Unmarshal(body, &user); err != nil {
return "", fmt.Errorf("%s unmarshaling %s", err, body)
}
return user.Login, nil
}