git.iko.soy/typeable/oauth2-proxy
on bee7879 help sign in
487 lines 13 kB history raw
1package providers
3import (
4 "context"
5 "errors"
6 "fmt"
7 "net/http"
8 "net/url"
9 "path"
10 "regexp"
11 "strconv"
12 "strings"
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 {
22 *ProviderData
23 Org string
24 Team string
25 Repo string
26 Token string
27 Users []string
30var _ Provider = (*GitHubProvider)(nil)
32const (
33 githubProviderName = "GitHub"
34 githubDefaultScope = "user:email"
37var (
38 // Default Login URL for GitHub.
39 // Pre-parsed URL of https://github.org/login/oauth/authorize.
40 githubDefaultLoginURL = &url.URL{
41 Scheme: "https",
42 Host: "github.com",
43 Path: "/login/oauth/authorize",
44 }
46 // Default Redeem URL for GitHub.
47 // Pre-parsed URL of https://github.org/login/oauth/access_token.
48 githubDefaultRedeemURL = &url.URL{
49 Scheme: "https",
50 Host: "github.com",
51 Path: "/login/oauth/access_token",
52 }
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{
59 Scheme: "https",
60 Host: "api.github.com",
61 Path: "/",
62 }
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,
71 profileURL: nil,
72 validateURL: githubDefaultValidateURL,
73 scope: githubDefaultScope,
74 })
76 provider := &GitHubProvider{ProviderData: p}
78 provider.setOrgTeam(opts.Org, opts.Team)
79 provider.setRepo(opts.Repo, opts.Token)
80 provider.setUsers(opts.Users)
81 return provider
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",
88 }
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)
97 if match != "" {
98 basePath = match
99 }
101 if params == nil {
102 params = &url.Values{}
103 }
105 return &url.URL{
106 Scheme: p.ValidateURL.Scheme,
107 Host: p.ValidateURL.Host,
108 Path: path.Join(basePath, endpoint),
109 RawQuery: params.Encode(),
110 }
113// setOrgTeam adds GitHub org reading parameters to the OAuth2 scope
114func (p *GitHubProvider) setOrgTeam(org, team string) {
115 p.Org = org
116 p.Team = team
117 if org != "" || team != "" {
118 p.Scope += " read:org"
119 }
122// setRepo configures the target repository and optional token to use
123func (p *GitHubProvider) setRepo(repo, token string) {
124 p.Repo = repo
125 p.Token = token
128// setUsers configures allowed usernames
129func (p *GitHubProvider) setUsers(users []string) {
130 p.Users = users
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)
136 if err != nil {
137 return err
138 }
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
150 var orgs []struct {
151 Login string `json:"login"`
152 }
154 type orgsPage []struct {
155 Login string `json:"login"`
156 }
158 pn := 1
159 for {
160 params := url.Values{
161 "per_page": {"100"},
162 "page": {strconv.Itoa(pn)},
163 }
165 endpoint := p.makeGitHubAPIEndpoint("/user/orgs", &params)
167 var op orgsPage
168 err := requests.New(endpoint.String()).
169 WithContext(ctx).
170 WithHeaders(makeGitHubHeader(accessToken)).
171 Do().
172 UnmarshalInto(&op)
173 if err != nil {
174 return false, err
175 }
177 if len(op) == 0 {
178 break
179 }
181 orgs = append(orgs, op...)
182 pn++
183 }
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)
189 return true, nil
190 }
191 presentOrgs = append(presentOrgs, org.Login)
192 }
194 logger.Printf("Missing Organization:%q in %v", p.Org, presentOrgs)
195 return false, nil
198func (p *GitHubProvider) hasOrgAndTeam(ctx context.Context, accessToken string) (bool, error) {
199 // https://developer.github.com/v3/orgs/teams/#list-user-teams
201 var teams []struct {
202 Name string `json:"name"`
203 Slug string `json:"slug"`
204 Org struct {
205 Login string `json:"login"`
206 } `json:"organization"`
207 }
209 type teamsPage []struct {
210 Name string `json:"name"`
211 Slug string `json:"slug"`
212 Org struct {
213 Login string `json:"login"`
214 } `json:"organization"`
215 }
217 pn := 1
218 last := 0
219 for {
220 params := url.Values{
221 "per_page": {"100"},
222 "page": {strconv.Itoa(pn)},
223 }
225 endpoint := p.makeGitHubAPIEndpoint("/user/teams", &params)
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.
229 // nolint:bodyclose
230 result := requests.New(endpoint.String()).
231 WithContext(ctx).
232 WithHeaders(makeGitHubHeader(accessToken)).
233 Do()
234 if result.Error() != nil {
235 return false, result.Error()
236 }
238 if last == 0 {
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
256 if converr == nil {
257 last = i
258 }
259 }
261 var tp teamsPage
262 if err := result.UnmarshalInto(&tp); err != nil {
263 return false, err
264 }
265 if len(tp) == 0 {
266 break
267 }
269 teams = append(teams, tp...)
271 if pn == last {
272 break
273 }
274 if last == 0 {
275 break
276 }
278 pn++
279 }
281 var hasOrg bool
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 {
287 hasOrg = true
288 ts := strings.Split(p.Team, ",")
289 for _, t := range ts {
290 if t == team.Slug {
291 logger.Printf("Found Github Organization:%q Team:%q (Name:%q)", team.Org.Login, team.Slug, team.Name)
292 return true, nil
293 }
294 }
295 presentTeams = append(presentTeams, team.Slug)
296 }
297 }
298 if hasOrg {
299 logger.Printf("Missing Team:%q from Org:%q in teams: %v", p.Team, p.Org, presentTeams)
300 } else {
301 var allOrgs []string
302 for org := range presentOrgs {
303 allOrgs = append(allOrgs, org)
304 }
305 logger.Printf("Missing Organization:%q in %#v", p.Org, allOrgs)
306 }
307 return false, nil
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"`
316 }
318 type repository struct {
319 Permissions permissions `json:"permissions"`
320 Private bool `json:"private"`
321 }
323 endpoint := p.makeGitHubAPIEndpoint("/repos/"+p.Repo, nil)
325 var repo repository
326 err := requests.New(endpoint.String()).
327 WithContext(ctx).
328 WithHeaders(makeGitHubHeader(accessToken)).
329 Do().
330 UnmarshalInto(&repo)
331 if err != nil {
332 return false, err
333 }
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
343 var user struct {
344 Login string `json:"login"`
345 Email string `json:"email"`
346 }
348 endpoint := p.makeGitHubAPIEndpoint("/user", nil)
350 err := requests.New(endpoint.String()).
351 WithContext(ctx).
352 WithHeaders(makeGitHubHeader(accessToken)).
353 Do().
354 UnmarshalInto(&user)
355 if err != nil {
356 return false, err
357 }
359 if p.isVerifiedUser(user.Login) {
360 return true, nil
361 }
362 return false, nil
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()).
370 WithContext(ctx).
371 WithHeaders(makeGitHubHeader(accessToken)).
372 Do()
373 if result.Error() != nil {
374 return false, result.Error()
375 }
377 if result.StatusCode() != 204 {
378 return false, fmt.Errorf("got %d from %q %s",
379 result.StatusCode(), endpoint.String(), result.Body())
380 }
382 logger.Printf("got %d from %q %s", result.StatusCode(), endpoint.String(), result.Body())
384 return true, nil
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"`
394 }
396 // If usernames are set, check that first
397 verifiedUser := false
398 if len(p.Users) > 0 {
399 var err error
400 verifiedUser, err = p.hasUser(ctx, s.AccessToken)
401 if err != nil {
402 return err
403 }
404 // org and repository options are not configured
405 if !verifiedUser && p.Org == "" && p.Repo == "" {
406 return errors.New("missing github user")
407 }
408 }
409 // If a user is verified by username options, skip the following restrictions
410 if !verifiedUser {
411 if p.Org != "" {
412 if p.Team != "" {
413 if ok, err := p.hasOrgAndTeam(ctx, s.AccessToken); err != nil || !ok {
414 return err
415 }
416 } else {
417 if ok, err := p.hasOrg(ctx, s.AccessToken); err != nil || !ok {
418 return err
419 }
420 }
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 {
423 return err
424 }
425 }
426 }
428 endpoint := p.makeGitHubAPIEndpoint("/user/emails", nil)
429 err := requests.New(endpoint.String()).
430 WithContext(ctx).
431 WithHeaders(makeGitHubHeader(s.AccessToken)).
432 Do().
433 UnmarshalInto(&emails)
434 if err != nil {
435 return err
436 }
438 for _, email := range emails {
439 if email.Verified {
440 if email.Primary {
441 s.Email = email.Email
442 return nil
443 }
444 }
445 }
447 return nil
450// getUser updates the SessionState User
451func (p *GitHubProvider) getUser(ctx context.Context, s *sessions.SessionState) error {
452 var user struct {
453 Login string `json:"login"`
454 Email string `json:"email"`
455 }
457 endpoint := p.makeGitHubAPIEndpoint("/user", nil)
459 err := requests.New(endpoint.String()).
460 WithContext(ctx).
461 WithHeaders(makeGitHubHeader(s.AccessToken)).
462 Do().
463 UnmarshalInto(&user)
464 if err != nil {
465 return err
466 }
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 {
471 return err
472 }
473 }
475 s.User = user.Login
476 return nil
479// isVerifiedUser
480func (p *GitHubProvider) isVerifiedUser(username string) bool {
481 for _, u := range p.Users {
482 if username == u {
483 return true
484 }
485 }
486 return false