14 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
15 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
16 "github.com/oauth2-proxy/oauth2-proxy/v7/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) {
105// EnrichSessionState updates the User & Email after the initial Redeem
106func (p *GitHubProvider) EnrichSessionState(ctx context.Context, s *sessions.SessionState) error {
107 err := p.getEmail(ctx, s)
111 return p.getUser(ctx, s)
114// ValidateSessionState validates the AccessToken
115func (p *GitHubProvider) ValidateSessionState(ctx context.Context, s *sessions.SessionState) bool {
116 return validateToken(ctx, p, s.AccessToken, makeGitHubHeader(s.AccessToken))
119func (p *GitHubProvider) hasOrg(ctx context.Context, accessToken string) (bool, error) {
120 // https://developer.github.com/v3/orgs/#list-your-organizations
123 Login string `json:"login"`
126 type orgsPage []struct {
127 Login string `json:"login"`
132 params := url.Values{
134 "page": {strconv.Itoa(pn)},
137 endpoint := &url.URL{
138 Scheme: p.ValidateURL.Scheme,
139 Host: p.ValidateURL.Host,
140 Path: path.Join(p.ValidateURL.Path, "/user/orgs"),
141 RawQuery: params.Encode(),
145 err := requests.New(endpoint.String()).
147 WithHeaders(makeGitHubHeader(accessToken)).
158 orgs = append(orgs, op...)
162 presentOrgs := make([]string, 0, len(orgs))
163 for _, org := range orgs {
164 if p.Org == org.Login {
165 logger.Printf("Found Github Organization: %q", org.Login)
168 presentOrgs = append(presentOrgs, org.Login)
171 logger.Printf("Missing Organization:%q in %v", p.Org, presentOrgs)
175func (p *GitHubProvider) hasOrgAndTeam(ctx context.Context, accessToken string) (bool, error) {
176 // https://developer.github.com/v3/orgs/teams/#list-user-teams
179 Name string `json:"name"`
180 Slug string `json:"slug"`
182 Login string `json:"login"`
183 } `json:"organization"`
186 type teamsPage []struct {
187 Name string `json:"name"`
188 Slug string `json:"slug"`
190 Login string `json:"login"`
191 } `json:"organization"`
197 params := url.Values{
199 "page": {strconv.Itoa(pn)},
202 endpoint := &url.URL{
203 Scheme: p.ValidateURL.Scheme,
204 Host: p.ValidateURL.Host,
205 Path: path.Join(p.ValidateURL.Path, "/user/teams"),
206 RawQuery: params.Encode(),
209 // bodyclose cannot detect that the body is being closed later in requests.Into,
210 // so have to skip the linting for the next line.
212 result := requests.New(endpoint.String()).
214 WithHeaders(makeGitHubHeader(accessToken)).
216 if result.Error() != nil {
217 return false, result.Error()
221 // link header may not be obtained
222 // When paging is not required and all data can be retrieved with a single call
224 // Conditions for obtaining the link header.
225 // 1. When paging is required (Example: When the data size is 100 and the page size is 99 or less)
226 // 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)
228 // link header at not last page
229 // <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"
230 // link header at last page (doesn't exist last info)
231 // <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"
233 link := result.Headers().Get("Link")
234 rep1 := regexp.MustCompile(`(?s).*\<https://api.github.com/user/teams\?page=(.)&per_page=[0-9]+\>; rel="last".*`)
235 i, converr := strconv.Atoi(rep1.ReplaceAllString(link, "$1"))
237 // If the last page cannot be taken from the link in the http header, the last variable remains zero
244 if err := result.UnmarshalInto(&tp); err != nil {
251 teams = append(teams, tp...)
264 presentOrgs := make(map[string]bool)
265 var presentTeams []string
266 for _, team := range teams {
267 presentOrgs[team.Org.Login] = true
268 if p.Org == team.Org.Login {
270 ts := strings.Split(p.Team, ",")
271 for _, t := range ts {
273 logger.Printf("Found Github Organization:%q Team:%q (Name:%q)", team.Org.Login, team.Slug, team.Name)
277 presentTeams = append(presentTeams, team.Slug)
281 logger.Printf("Missing Team:%q from Org:%q in teams: %v", p.Team, p.Org, presentTeams)
284 for org := range presentOrgs {
285 allOrgs = append(allOrgs, org)
287 logger.Printf("Missing Organization:%q in %#v", p.Org, allOrgs)
292func (p *GitHubProvider) hasRepo(ctx context.Context, accessToken string) (bool, error) {
293 // https://developer.github.com/v3/repos/#get-a-repository
295 type permissions struct {
296 Pull bool `json:"pull"`
297 Push bool `json:"push"`
300 type repository struct {
301 Permissions permissions `json:"permissions"`
302 Private bool `json:"private"`
305 endpoint := &url.URL{
306 Scheme: p.ValidateURL.Scheme,
307 Host: p.ValidateURL.Host,
308 Path: path.Join(p.ValidateURL.Path, "/repo/", p.Repo),
312 err := requests.New(endpoint.String()).
314 WithHeaders(makeGitHubHeader(accessToken)).
321 // Every user can implicitly pull from a public repo, so only grant access
322 // if they have push access or the repo is private and they can pull
323 return repo.Permissions.Push || (repo.Private && repo.Permissions.Pull), nil
326func (p *GitHubProvider) hasUser(ctx context.Context, accessToken string) (bool, error) {
327 // https://developer.github.com/v3/users/#get-the-authenticated-user
330 Login string `json:"login"`
331 Email string `json:"email"`
334 endpoint := &url.URL{
335 Scheme: p.ValidateURL.Scheme,
336 Host: p.ValidateURL.Host,
337 Path: path.Join(p.ValidateURL.Path, "/user"),
340 err := requests.New(endpoint.String()).
342 WithHeaders(makeGitHubHeader(accessToken)).
349 if p.isVerifiedUser(user.Login) {
355func (p *GitHubProvider) isCollaborator(ctx context.Context, username, accessToken string) (bool, error) {
356 //https://developer.github.com/v3/repos/collaborators/#check-if-a-user-is-a-collaborator
358 endpoint := &url.URL{
359 Scheme: p.ValidateURL.Scheme,
360 Host: p.ValidateURL.Host,
361 Path: path.Join(p.ValidateURL.Path, "/repos/", p.Repo, "/collaborators/", username),
363 result := requests.New(endpoint.String()).
365 WithHeaders(makeGitHubHeader(accessToken)).
367 if result.Error() != nil {
368 return false, result.Error()
371 if result.StatusCode() != 204 {
372 return false, fmt.Errorf("got %d from %q %s",
373 result.StatusCode(), endpoint.String(), result.Body())
376 logger.Printf("got %d from %q %s", result.StatusCode(), endpoint.String(), result.Body())
381// getEmail updates the SessionState Email
382func (p *GitHubProvider) getEmail(ctx context.Context, s *sessions.SessionState) error {
384 var emails []struct {
385 Email string `json:"email"`
386 Primary bool `json:"primary"`
387 Verified bool `json:"verified"`
390 // If usernames are set, check that first
391 verifiedUser := false
392 if len(p.Users) > 0 {
394 verifiedUser, err = p.hasUser(ctx, s.AccessToken)
398 // org and repository options are not configured
399 if !verifiedUser && p.Org == "" && p.Repo == "" {
400 return errors.New("missing github user")
403 // If a user is verified by username options, skip the following restrictions
407 if ok, err := p.hasOrgAndTeam(ctx, s.AccessToken); err != nil || !ok {
411 if ok, err := p.hasOrg(ctx, s.AccessToken); err != nil || !ok {
415 } else if p.Repo != "" && p.Token == "" { // If we have a token we'll do the collaborator check in GetUserName
416 if ok, err := p.hasRepo(ctx, s.AccessToken); err != nil || !ok {
422 endpoint := &url.URL{
423 Scheme: p.ValidateURL.Scheme,
424 Host: p.ValidateURL.Host,
425 Path: path.Join(p.ValidateURL.Path, "/user/emails"),
427 err := requests.New(endpoint.String()).
429 WithHeaders(makeGitHubHeader(s.AccessToken)).
431 UnmarshalInto(&emails)
436 for _, email := range emails {
439 s.Email = email.Email
448// getUser updates the SessionState User
449func (p *GitHubProvider) getUser(ctx context.Context, s *sessions.SessionState) error {
451 Login string `json:"login"`
452 Email string `json:"email"`
455 endpoint := &url.URL{
456 Scheme: p.ValidateURL.Scheme,
457 Host: p.ValidateURL.Host,
458 Path: path.Join(p.ValidateURL.Path, "/user"),
461 err := requests.New(endpoint.String()).
463 WithHeaders(makeGitHubHeader(s.AccessToken)).
470 // Now that we have the username we can check collaborator status
471 if !p.isVerifiedUser(user.Login) && p.Org == "" && p.Repo != "" && p.Token != "" {
472 if ok, err := p.isCollaborator(ctx, user.Login, p.Token); err != nil || !ok {
482func (p *GitHubProvider) isVerifiedUser(username string) bool {
483 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