14 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
15 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
16 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
17 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests"
20// GitHubProvider represents an GitHub based Identity Provider
21type GitHubProvider struct {
30var _ Provider = (*GitHubProvider)(nil)
33 githubProviderName = "GitHub"
34 githubDefaultScope = "user:email"
38 // Default Login URL for GitHub.
39 // Pre-parsed URL of https://github.org/login/oauth/authorize.
40 githubDefaultLoginURL = &url.URL{
43 Path: "/login/oauth/authorize",
46 // Default Redeem URL for GitHub.
47 // Pre-parsed URL of https://github.org/login/oauth/access_token.
48 githubDefaultRedeemURL = &url.URL{
51 Path: "/login/oauth/access_token",
54 // Default Validation URL for GitHub.
55 // ValidationURL is the API Base URL.
56 // Other API requests are based off of this (eg to fetch users/groups).
57 // Pre-parsed URL of https://api.github.com/.
58 githubDefaultValidateURL = &url.URL{
60 Host: "api.github.com",
65// NewGitHubProvider initiates a new GitHubProvider
66func NewGitHubProvider(p *ProviderData, opts options.GitHubOptions) *GitHubProvider {
67 p.setProviderDefaults(providerDefaults{
68 name: githubProviderName,
69 loginURL: githubDefaultLoginURL,
70 redeemURL: githubDefaultRedeemURL,
72 validateURL: githubDefaultValidateURL,
73 scope: githubDefaultScope,
76 provider := &GitHubProvider{ProviderData: p}
78 provider.setOrgTeam(opts.Org, opts.Team)
79 provider.setRepo(opts.Repo, opts.Token)
80 provider.setUsers(opts.Users)
84func makeGitHubHeader(accessToken string) http.Header {
85 // extra headers required by the GitHub API when making authenticated requests
86 extraHeaders := map[string]string{
87 acceptHeader: "application/vnd.github.v3+json",
89 return makeAuthorizationHeader(tokenTypeToken, accessToken, extraHeaders)
92func (p *GitHubProvider) makeGitHubAPIEndpoint(endpoint string, params *url.Values) *url.URL {
93 basePath := p.ValidateURL.Path
95 re := regexp.MustCompile(`^/api/v\d+`)
96 match := re.FindString(p.ValidateURL.Path)
102 params = &url.Values{}
106 Scheme: p.ValidateURL.Scheme,
107 Host: p.ValidateURL.Host,
108 Path: path.Join(basePath, endpoint),
109 RawQuery: params.Encode(),
113// setOrgTeam adds GitHub org reading parameters to the OAuth2 scope
114func (p *GitHubProvider) setOrgTeam(org, team string) {
117 if org != "" || team != "" {
118 p.Scope += " read:org"
122// setRepo configures the target repository and optional token to use
123func (p *GitHubProvider) setRepo(repo, token string) {
128// setUsers configures allowed usernames
129func (p *GitHubProvider) setUsers(users []string) {
133// EnrichSession updates the User & Email after the initial Redeem
134func (p *GitHubProvider) EnrichSession(ctx context.Context, s *sessions.SessionState) error {
135 err := p.getEmail(ctx, s)
139 return p.getUser(ctx, s)
142// ValidateSession validates the AccessToken
143func (p *GitHubProvider) ValidateSession(ctx context.Context, s *sessions.SessionState) bool {
144 return validateToken(ctx, p, s.AccessToken, makeGitHubHeader(s.AccessToken))
147func (p *GitHubProvider) hasOrg(ctx context.Context, accessToken string) (bool, error) {
148 // https://developer.github.com/v3/orgs/#list-your-organizations
151 Login string `json:"login"`
154 type orgsPage []struct {
155 Login string `json:"login"`
160 params := url.Values{
162 "page": {strconv.Itoa(pn)},
165 endpoint := p.makeGitHubAPIEndpoint("/user/orgs", ¶ms)
168 err := requests.New(endpoint.String()).
170 WithHeaders(makeGitHubHeader(accessToken)).
181 orgs = append(orgs, op...)
185 presentOrgs := make([]string, 0, len(orgs))
186 for _, org := range orgs {
187 if p.Org == org.Login {
188 logger.Printf("Found Github Organization: %q", org.Login)
191 presentOrgs = append(presentOrgs, org.Login)
194 logger.Printf("Missing Organization:%q in %v", p.Org, presentOrgs)
198func (p *GitHubProvider) hasOrgAndTeam(ctx context.Context, accessToken string) (bool, error) {
199 // https://developer.github.com/v3/orgs/teams/#list-user-teams
202 Name string `json:"name"`
203 Slug string `json:"slug"`
205 Login string `json:"login"`
206 } `json:"organization"`
209 type teamsPage []struct {
210 Name string `json:"name"`
211 Slug string `json:"slug"`
213 Login string `json:"login"`
214 } `json:"organization"`
220 params := url.Values{
222 "page": {strconv.Itoa(pn)},
225 endpoint := p.makeGitHubAPIEndpoint("/user/teams", ¶ms)
227 // bodyclose cannot detect that the body is being closed later in requests.Into,
228 // so have to skip the linting for the next line.
230 result := requests.New(endpoint.String()).
232 WithHeaders(makeGitHubHeader(accessToken)).
234 if result.Error() != nil {
235 return false, result.Error()
239 // link header may not be obtained
240 // When paging is not required and all data can be retrieved with a single call
242 // Conditions for obtaining the link header.
243 // 1. When paging is required (Example: When the data size is 100 and the page size is 99 or less)
244 // 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)
246 // link header at not last page
247 // <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"
248 // link header at last page (doesn't exist last info)
249 // <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"
251 link := result.Headers().Get("Link")
252 rep1 := regexp.MustCompile(`(?s).*\<https://api.github.com/user/teams\?page=(.)&per_page=[0-9]+\>; rel="last".*`)
253 i, converr := strconv.Atoi(rep1.ReplaceAllString(link, "$1"))
255 // If the last page cannot be taken from the link in the http header, the last variable remains zero
262 if err := result.UnmarshalInto(&tp); err != nil {
269 teams = append(teams, tp...)
282 presentOrgs := make(map[string]bool)
283 var presentTeams []string
284 for _, team := range teams {
285 presentOrgs[team.Org.Login] = true
286 if p.Org == team.Org.Login {
288 ts := strings.Split(p.Team, ",")
289 for _, t := range ts {
291 logger.Printf("Found Github Organization:%q Team:%q (Name:%q)", team.Org.Login, team.Slug, team.Name)
295 presentTeams = append(presentTeams, team.Slug)
299 logger.Printf("Missing Team:%q from Org:%q in teams: %v", p.Team, p.Org, presentTeams)
302 for org := range presentOrgs {
303 allOrgs = append(allOrgs, org)
305 logger.Printf("Missing Organization:%q in %#v", p.Org, allOrgs)
310func (p *GitHubProvider) hasRepo(ctx context.Context, accessToken string) (bool, error) {
311 // https://developer.github.com/v3/repos/#get-a-repository
313 type permissions struct {
314 Pull bool `json:"pull"`
315 Push bool `json:"push"`
318 type repository struct {
319 Permissions permissions `json:"permissions"`
320 Private bool `json:"private"`
323 endpoint := p.makeGitHubAPIEndpoint("/repos/"+p.Repo, nil)
326 err := requests.New(endpoint.String()).
328 WithHeaders(makeGitHubHeader(accessToken)).
335 // Every user can implicitly pull from a public repo, so only grant access
336 // if they have push access or the repo is private and they can pull
337 return repo.Permissions.Push || (repo.Private && repo.Permissions.Pull), nil
340func (p *GitHubProvider) hasUser(ctx context.Context, accessToken string) (bool, error) {
341 // https://developer.github.com/v3/users/#get-the-authenticated-user
344 Login string `json:"login"`
345 Email string `json:"email"`
348 endpoint := p.makeGitHubAPIEndpoint("/user", nil)
350 err := requests.New(endpoint.String()).
352 WithHeaders(makeGitHubHeader(accessToken)).
359 if p.isVerifiedUser(user.Login) {
365func (p *GitHubProvider) isCollaborator(ctx context.Context, username, accessToken string) (bool, error) {
366 //https://developer.github.com/v3/repos/collaborators/#check-if-a-user-is-a-collaborator
368 endpoint := p.makeGitHubAPIEndpoint("/repos/"+p.Repo+"/collaborators/"+username, nil)
369 result := requests.New(endpoint.String()).
371 WithHeaders(makeGitHubHeader(accessToken)).
373 if result.Error() != nil {
374 return false, result.Error()
377 if result.StatusCode() != 204 {
378 return false, fmt.Errorf("got %d from %q %s",
379 result.StatusCode(), endpoint.String(), result.Body())
382 logger.Printf("got %d from %q %s", result.StatusCode(), endpoint.String(), result.Body())
387// getEmail updates the SessionState Email
388func (p *GitHubProvider) getEmail(ctx context.Context, s *sessions.SessionState) error {
390 var emails []struct {
391 Email string `json:"email"`
392 Primary bool `json:"primary"`
393 Verified bool `json:"verified"`
396 // If usernames are set, check that first
397 verifiedUser := false
398 if len(p.Users) > 0 {
400 verifiedUser, err = p.hasUser(ctx, s.AccessToken)
404 // org and repository options are not configured
405 if !verifiedUser && p.Org == "" && p.Repo == "" {
406 return errors.New("missing github user")
409 // If a user is verified by username options, skip the following restrictions
413 if ok, err := p.hasOrgAndTeam(ctx, s.AccessToken); err != nil || !ok {
417 if ok, err := p.hasOrg(ctx, s.AccessToken); err != nil || !ok {
421 } else if p.Repo != "" && p.Token == "" { // If we have a token we'll do the collaborator check in GetUserName
422 if ok, err := p.hasRepo(ctx, s.AccessToken); err != nil || !ok {
428 endpoint := p.makeGitHubAPIEndpoint("/user/emails", nil)
429 err := requests.New(endpoint.String()).
431 WithHeaders(makeGitHubHeader(s.AccessToken)).
433 UnmarshalInto(&emails)
438 for _, email := range emails {
441 s.Email = email.Email
450// getUser updates the SessionState User
451func (p *GitHubProvider) getUser(ctx context.Context, s *sessions.SessionState) error {
453 Login string `json:"login"`
454 Email string `json:"email"`
457 endpoint := p.makeGitHubAPIEndpoint("/user", nil)
459 err := requests.New(endpoint.String()).
461 WithHeaders(makeGitHubHeader(s.AccessToken)).
468 // Now that we have the username we can check collaborator status
469 if !p.isVerifiedUser(user.Login) && p.Org == "" && p.Repo != "" && p.Token != "" {
470 if ok, err := p.isCollaborator(ctx, user.Login, p.Token); err != nil || !ok {
480func (p *GitHubProvider) isVerifiedUser(username string) bool {
481 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