14 "github.com/oauth2-proxy/oauth2-proxy/pkg/apis/sessions"
15 "github.com/oauth2-proxy/oauth2-proxy/pkg/logger"
16 "github.com/oauth2-proxy/oauth2-proxy/pkg/requests"
19// GitHubProvider represents an GitHub based Identity Provider
20type GitHubProvider struct {
29var _ Provider = (*GitHubProvider)(nil)
32 githubProviderName = "GitHub"
33 githubDefaultScope = "user:email"
37 // Default Login URL for GitHub.
38 // Pre-parsed URL of https://github.org/login/oauth/authorize.
39 githubDefaultLoginURL = &url.URL{
42 Path: "/login/oauth/authorize",
45 // Default Redeem URL for GitHub.
46 // Pre-parsed URL of https://github.org/login/oauth/access_token.
47 githubDefaultRedeemURL = &url.URL{
50 Path: "/login/oauth/access_token",
53 // Default Validation URL for GitHub.
54 // ValidationURL is the API Base URL.
55 // Other API requests are based off of this (eg to fetch users/groups).
56 // Pre-parsed URL of https://api.github.com/.
57 githubDefaultValidateURL = &url.URL{
59 Host: "api.github.com",
64// NewGitHubProvider initiates a new GitHubProvider
65func NewGitHubProvider(p *ProviderData) *GitHubProvider {
66 p.setProviderDefaults(providerDefaults{
67 name: githubProviderName,
68 loginURL: githubDefaultLoginURL,
69 redeemURL: githubDefaultRedeemURL,
71 validateURL: githubDefaultValidateURL,
72 scope: githubDefaultScope,
74 return &GitHubProvider{ProviderData: p}
77func makeGitHubHeader(accessToken string) http.Header {
78 // extra headers required by the GitHub API when making authenticated requests
79 extraHeaders := map[string]string{
80 acceptHeader: "application/vnd.github.v3+json",
82 return makeAuthorizationHeader(tokenTypeToken, accessToken, extraHeaders)
85// SetOrgTeam adds GitHub org reading parameters to the OAuth2 scope
86func (p *GitHubProvider) SetOrgTeam(org, team string) {
89 if org != "" || team != "" {
90 p.Scope += " read:org"
94// SetRepo configures the target repository and optional token to use
95func (p *GitHubProvider) SetRepo(repo, token string) {
100// SetUsers configures allowed usernames
101func (p *GitHubProvider) SetUsers(users []string) {
105func (p *GitHubProvider) hasOrg(ctx context.Context, accessToken string) (bool, error) {
106 // https://developer.github.com/v3/orgs/#list-your-organizations
109 Login string `json:"login"`
112 type orgsPage []struct {
113 Login string `json:"login"`
118 params := url.Values{
120 "page": {strconv.Itoa(pn)},
123 endpoint := &url.URL{
124 Scheme: p.ValidateURL.Scheme,
125 Host: p.ValidateURL.Host,
126 Path: path.Join(p.ValidateURL.Path, "/user/orgs"),
127 RawQuery: params.Encode(),
131 err := requests.New(endpoint.String()).
133 WithHeaders(makeGitHubHeader(accessToken)).
144 orgs = append(orgs, op...)
148 presentOrgs := make([]string, 0, len(orgs))
149 for _, org := range orgs {
150 if p.Org == org.Login {
151 logger.Printf("Found Github Organization: %q", org.Login)
154 presentOrgs = append(presentOrgs, org.Login)
157 logger.Printf("Missing Organization:%q in %v", p.Org, presentOrgs)
161func (p *GitHubProvider) hasOrgAndTeam(ctx context.Context, accessToken string) (bool, error) {
162 // https://developer.github.com/v3/orgs/teams/#list-user-teams
165 Name string `json:"name"`
166 Slug string `json:"slug"`
168 Login string `json:"login"`
169 } `json:"organization"`
172 type teamsPage []struct {
173 Name string `json:"name"`
174 Slug string `json:"slug"`
176 Login string `json:"login"`
177 } `json:"organization"`
183 params := url.Values{
185 "page": {strconv.Itoa(pn)},
188 endpoint := &url.URL{
189 Scheme: p.ValidateURL.Scheme,
190 Host: p.ValidateURL.Host,
191 Path: path.Join(p.ValidateURL.Path, "/user/teams"),
192 RawQuery: params.Encode(),
195 // bodyclose cannot detect that the body is being closed later in requests.Into,
196 // so have to skip the linting for the next line.
198 result := requests.New(endpoint.String()).
200 WithHeaders(makeGitHubHeader(accessToken)).
202 if result.Error() != nil {
203 return false, result.Error()
207 // link header may not be obtained
208 // When paging is not required and all data can be retrieved with a single call
210 // Conditions for obtaining the link header.
211 // 1. When paging is required (Example: When the data size is 100 and the page size is 99 or less)
212 // 2. When it exceeds the paging frame (Example: When there is only 10 records but the second page is called with a page size of 100)
214 // link header at not last page
215 // <https://api.github.com/user/teams?page=1&per_page=100>; rel="prev", <https://api.github.com/user/teams?page=1&per_page=100>; rel="last", <https://api.github.com/user/teams?page=1&per_page=100>; rel="first"
216 // link header at last page (doesn't exist last info)
217 // <https://api.github.com/user/teams?page=3&per_page=10>; rel="prev", <https://api.github.com/user/teams?page=1&per_page=10>; rel="first"
219 link := result.Headers().Get("Link")
220 rep1 := regexp.MustCompile(`(?s).*\<https://api.github.com/user/teams\?page=(.)&per_page=[0-9]+\>; rel="last".*`)
221 i, converr := strconv.Atoi(rep1.ReplaceAllString(link, "$1"))
223 // If the last page cannot be taken from the link in the http header, the last variable remains zero
230 if err := result.UnmarshalInto(&tp); err != nil {
237 teams = append(teams, tp...)
250 presentOrgs := make(map[string]bool)
251 var presentTeams []string
252 for _, team := range teams {
253 presentOrgs[team.Org.Login] = true
254 if p.Org == team.Org.Login {
256 ts := strings.Split(p.Team, ",")
257 for _, t := range ts {
259 logger.Printf("Found Github Organization:%q Team:%q (Name:%q)", team.Org.Login, team.Slug, team.Name)
263 presentTeams = append(presentTeams, team.Slug)
267 logger.Printf("Missing Team:%q from Org:%q in teams: %v", p.Team, p.Org, presentTeams)
270 for org := range presentOrgs {
271 allOrgs = append(allOrgs, org)
273 logger.Printf("Missing Organization:%q in %#v", p.Org, allOrgs)
278func (p *GitHubProvider) hasRepo(ctx context.Context, accessToken string) (bool, error) {
279 // https://developer.github.com/v3/repos/#get-a-repository
281 type permissions struct {
282 Pull bool `json:"pull"`
283 Push bool `json:"push"`
286 type repository struct {
287 Permissions permissions `json:"permissions"`
288 Private bool `json:"private"`
291 endpoint := &url.URL{
292 Scheme: p.ValidateURL.Scheme,
293 Host: p.ValidateURL.Host,
294 Path: path.Join(p.ValidateURL.Path, "/repo/", p.Repo),
298 err := requests.New(endpoint.String()).
300 WithHeaders(makeGitHubHeader(accessToken)).
307 // Every user can implicitly pull from a public repo, so only grant access
308 // if they have push access or the repo is private and they can pull
309 return repo.Permissions.Push || (repo.Private && repo.Permissions.Pull), nil
312func (p *GitHubProvider) hasUser(ctx context.Context, accessToken string) (bool, error) {
313 // https://developer.github.com/v3/users/#get-the-authenticated-user
316 Login string `json:"login"`
317 Email string `json:"email"`
320 endpoint := &url.URL{
321 Scheme: p.ValidateURL.Scheme,
322 Host: p.ValidateURL.Host,
323 Path: path.Join(p.ValidateURL.Path, "/user"),
326 err := requests.New(endpoint.String()).
328 WithHeaders(makeGitHubHeader(accessToken)).
335 if p.isVerifiedUser(user.Login) {
341func (p *GitHubProvider) isCollaborator(ctx context.Context, username, accessToken string) (bool, error) {
342 //https://developer.github.com/v3/repos/collaborators/#check-if-a-user-is-a-collaborator
344 endpoint := &url.URL{
345 Scheme: p.ValidateURL.Scheme,
346 Host: p.ValidateURL.Host,
347 Path: path.Join(p.ValidateURL.Path, "/repos/", p.Repo, "/collaborators/", username),
349 result := requests.New(endpoint.String()).
351 WithHeaders(makeGitHubHeader(accessToken)).
353 if result.Error() != nil {
354 return false, result.Error()
357 if result.StatusCode() != 204 {
358 return false, fmt.Errorf("got %d from %q %s",
359 result.StatusCode(), endpoint.String(), result.Body())
362 logger.Printf("got %d from %q %s", result.StatusCode(), endpoint.String(), result.Body())
367// GetEmailAddress returns the Account email address
368func (p *GitHubProvider) GetEmailAddress(ctx context.Context, s *sessions.SessionState) (string, error) {
370 var emails []struct {
371 Email string `json:"email"`
372 Primary bool `json:"primary"`
373 Verified bool `json:"verified"`
376 // If usernames are set, check that first
377 verifiedUser := false
378 if len(p.Users) > 0 {
380 verifiedUser, err = p.hasUser(ctx, s.AccessToken)
384 // org and repository options are not configured
385 if !verifiedUser && p.Org == "" && p.Repo == "" {
386 return "", errors.New("missing github user")
389 // If a user is verified by username options, skip the following restrictions
393 if ok, err := p.hasOrgAndTeam(ctx, s.AccessToken); err != nil || !ok {
397 if ok, err := p.hasOrg(ctx, s.AccessToken); err != nil || !ok {
401 } else if p.Repo != "" && p.Token == "" { // If we have a token we'll do the collaborator check in GetUserName
402 if ok, err := p.hasRepo(ctx, s.AccessToken); err != nil || !ok {
408 endpoint := &url.URL{
409 Scheme: p.ValidateURL.Scheme,
410 Host: p.ValidateURL.Host,
411 Path: path.Join(p.ValidateURL.Path, "/user/emails"),
413 err := requests.New(endpoint.String()).
415 WithHeaders(makeGitHubHeader(s.AccessToken)).
417 UnmarshalInto(&emails)
423 for _, email := range emails {
425 returnEmail = email.Email
427 return returnEmail, nil
432 return returnEmail, nil
435// GetUserName returns the Account user name
436func (p *GitHubProvider) GetUserName(ctx context.Context, s *sessions.SessionState) (string, error) {
438 Login string `json:"login"`
439 Email string `json:"email"`
442 endpoint := &url.URL{
443 Scheme: p.ValidateURL.Scheme,
444 Host: p.ValidateURL.Host,
445 Path: path.Join(p.ValidateURL.Path, "/user"),
448 err := requests.New(endpoint.String()).
450 WithHeaders(makeGitHubHeader(s.AccessToken)).
457 // Now that we have the username we can check collaborator status
458 if !p.isVerifiedUser(user.Login) && p.Org == "" && p.Repo != "" && p.Token != "" {
459 if ok, err := p.isCollaborator(ctx, user.Login, p.Token); err != nil || !ok {
464 return user.Login, nil
467// ValidateSessionState validates the AccessToken
468func (p *GitHubProvider) ValidateSessionState(ctx context.Context, s *sessions.SessionState) bool {
469 return validateToken(ctx, p, s.AccessToken, makeGitHubHeader(s.AccessToken))
473func (p *GitHubProvider) isVerifiedUser(username string) bool {
474 for _, u := range p.Users {
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list