git.iko.soy/typeable/oauth2-proxy
on 8cbf921 help sign in
480 lines 12 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/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 {
21 *ProviderData
22 Org string
23 Team string
24 Repo string
25 Token string
26 Users []string
29var _ Provider = (*GitHubProvider)(nil)
31const (
32 githubProviderName = "GitHub"
33 githubDefaultScope = "user:email"
36var (
37 // Default Login URL for GitHub.
38 // Pre-parsed URL of https://github.org/login/oauth/authorize.
39 githubDefaultLoginURL = &url.URL{
40 Scheme: "https",
41 Host: "github.com",
42 Path: "/login/oauth/authorize",
43 }
45 // Default Redeem URL for GitHub.
46 // Pre-parsed URL of https://github.org/login/oauth/access_token.
47 githubDefaultRedeemURL = &url.URL{
48 Scheme: "https",
49 Host: "github.com",
50 Path: "/login/oauth/access_token",
51 }
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{
58 Scheme: "https",
59 Host: "api.github.com",
60 Path: "/",
61 }
64// NewGitHubProvider initiates a new GitHubProvider
65func NewGitHubProvider(p *ProviderData) *GitHubProvider {
66 p.setProviderDefaults(providerDefaults{
67 name: githubProviderName,
68 loginURL: githubDefaultLoginURL,
69 redeemURL: githubDefaultRedeemURL,
70 profileURL: nil,
71 validateURL: githubDefaultValidateURL,
72 scope: githubDefaultScope,
73 })
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",
81 }
82 return makeAuthorizationHeader(tokenTypeToken, accessToken, extraHeaders)
85// SetOrgTeam adds GitHub org reading parameters to the OAuth2 scope
86func (p *GitHubProvider) SetOrgTeam(org, team string) {
87 p.Org = org
88 p.Team = team
89 if org != "" || team != "" {
90 p.Scope += " read:org"
91 }
94// SetRepo configures the target repository and optional token to use
95func (p *GitHubProvider) SetRepo(repo, token string) {
96 p.Repo = repo
97 p.Token = token
100// SetUsers configures allowed usernames
101func (p *GitHubProvider) SetUsers(users []string) {
102 p.Users = users
105func (p *GitHubProvider) hasOrg(ctx context.Context, accessToken string) (bool, error) {
106 // https://developer.github.com/v3/orgs/#list-your-organizations
108 var orgs []struct {
109 Login string `json:"login"`
110 }
112 type orgsPage []struct {
113 Login string `json:"login"`
114 }
116 pn := 1
117 for {
118 params := url.Values{
119 "per_page": {"100"},
120 "page": {strconv.Itoa(pn)},
121 }
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(),
128 }
130 var op orgsPage
131 err := requests.New(endpoint.String()).
132 WithContext(ctx).
133 WithHeaders(makeGitHubHeader(accessToken)).
134 Do().
135 UnmarshalInto(&op)
136 if err != nil {
137 return false, err
138 }
140 if len(op) == 0 {
141 break
142 }
144 orgs = append(orgs, op...)
145 pn++
146 }
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)
152 return true, nil
153 }
154 presentOrgs = append(presentOrgs, org.Login)
155 }
157 logger.Printf("Missing Organization:%q in %v", p.Org, presentOrgs)
158 return false, nil
161func (p *GitHubProvider) hasOrgAndTeam(ctx context.Context, accessToken string) (bool, error) {
162 // https://developer.github.com/v3/orgs/teams/#list-user-teams
164 var teams []struct {
165 Name string `json:"name"`
166 Slug string `json:"slug"`
167 Org struct {
168 Login string `json:"login"`
169 } `json:"organization"`
170 }
172 type teamsPage []struct {
173 Name string `json:"name"`
174 Slug string `json:"slug"`
175 Org struct {
176 Login string `json:"login"`
177 } `json:"organization"`
178 }
180 pn := 1
181 last := 0
182 for {
183 params := url.Values{
184 "per_page": {"100"},
185 "page": {strconv.Itoa(pn)},
186 }
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(),
193 }
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.
197 // nolint:bodyclose
198 result := requests.New(endpoint.String()).
199 WithContext(ctx).
200 WithHeaders(makeGitHubHeader(accessToken)).
201 Do()
202 if result.Error() != nil {
203 return false, result.Error()
204 }
206 if last == 0 {
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
224 if converr == nil {
225 last = i
226 }
227 }
229 var tp teamsPage
230 if err := result.UnmarshalInto(&tp); err != nil {
231 return false, err
232 }
233 if len(tp) == 0 {
234 break
235 }
237 teams = append(teams, tp...)
239 if pn == last {
240 break
241 }
242 if last == 0 {
243 break
244 }
246 pn++
247 }
249 var hasOrg bool
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 {
255 hasOrg = true
256 ts := strings.Split(p.Team, ",")
257 for _, t := range ts {
258 if t == team.Slug {
259 logger.Printf("Found Github Organization:%q Team:%q (Name:%q)", team.Org.Login, team.Slug, team.Name)
260 return true, nil
261 }
262 }
263 presentTeams = append(presentTeams, team.Slug)
264 }
265 }
266 if hasOrg {
267 logger.Printf("Missing Team:%q from Org:%q in teams: %v", p.Team, p.Org, presentTeams)
268 } else {
269 var allOrgs []string
270 for org := range presentOrgs {
271 allOrgs = append(allOrgs, org)
272 }
273 logger.Printf("Missing Organization:%q in %#v", p.Org, allOrgs)
274 }
275 return false, nil
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"`
284 }
286 type repository struct {
287 Permissions permissions `json:"permissions"`
288 Private bool `json:"private"`
289 }
291 endpoint := &url.URL{
292 Scheme: p.ValidateURL.Scheme,
293 Host: p.ValidateURL.Host,
294 Path: path.Join(p.ValidateURL.Path, "/repo/", p.Repo),
295 }
297 var repo repository
298 err := requests.New(endpoint.String()).
299 WithContext(ctx).
300 WithHeaders(makeGitHubHeader(accessToken)).
301 Do().
302 UnmarshalInto(&repo)
303 if err != nil {
304 return false, err
305 }
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
315 var user struct {
316 Login string `json:"login"`
317 Email string `json:"email"`
318 }
320 endpoint := &url.URL{
321 Scheme: p.ValidateURL.Scheme,
322 Host: p.ValidateURL.Host,
323 Path: path.Join(p.ValidateURL.Path, "/user"),
324 }
326 err := requests.New(endpoint.String()).
327 WithContext(ctx).
328 WithHeaders(makeGitHubHeader(accessToken)).
329 Do().
330 UnmarshalInto(&user)
331 if err != nil {
332 return false, err
333 }
335 if p.isVerifiedUser(user.Login) {
336 return true, nil
337 }
338 return false, nil
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),
348 }
349 result := requests.New(endpoint.String()).
350 WithContext(ctx).
351 WithHeaders(makeGitHubHeader(accessToken)).
352 Do()
353 if result.Error() != nil {
354 return false, result.Error()
355 }
357 if result.StatusCode() != 204 {
358 return false, fmt.Errorf("got %d from %q %s",
359 result.StatusCode(), endpoint.String(), result.Body())
360 }
362 logger.Printf("got %d from %q %s", result.StatusCode(), endpoint.String(), result.Body())
364 return true, nil
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"`
374 }
376 // If usernames are set, check that first
377 verifiedUser := false
378 if len(p.Users) > 0 {
379 var err error
380 verifiedUser, err = p.hasUser(ctx, s.AccessToken)
381 if err != nil {
382 return "", err
383 }
384 // org and repository options are not configured
385 if !verifiedUser && p.Org == "" && p.Repo == "" {
386 return "", errors.New("missing github user")
387 }
388 }
389 // If a user is verified by username options, skip the following restrictions
390 if !verifiedUser {
391 if p.Org != "" {
392 if p.Team != "" {
393 if ok, err := p.hasOrgAndTeam(ctx, s.AccessToken); err != nil || !ok {
394 return "", err
395 }
396 } else {
397 if ok, err := p.hasOrg(ctx, s.AccessToken); err != nil || !ok {
398 return "", err
399 }
400 }
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 {
403 return "", err
404 }
405 }
406 }
408 endpoint := &url.URL{
409 Scheme: p.ValidateURL.Scheme,
410 Host: p.ValidateURL.Host,
411 Path: path.Join(p.ValidateURL.Path, "/user/emails"),
412 }
413 err := requests.New(endpoint.String()).
414 WithContext(ctx).
415 WithHeaders(makeGitHubHeader(s.AccessToken)).
416 Do().
417 UnmarshalInto(&emails)
418 if err != nil {
419 return "", err
420 }
422 returnEmail := ""
423 for _, email := range emails {
424 if email.Verified {
425 returnEmail = email.Email
426 if email.Primary {
427 return returnEmail, nil
428 }
429 }
430 }
432 return returnEmail, nil
435// GetUserName returns the Account user name
436func (p *GitHubProvider) GetUserName(ctx context.Context, s *sessions.SessionState) (string, error) {
437 var user struct {
438 Login string `json:"login"`
439 Email string `json:"email"`
440 }
442 endpoint := &url.URL{
443 Scheme: p.ValidateURL.Scheme,
444 Host: p.ValidateURL.Host,
445 Path: path.Join(p.ValidateURL.Path, "/user"),
446 }
448 err := requests.New(endpoint.String()).
449 WithContext(ctx).
450 WithHeaders(makeGitHubHeader(s.AccessToken)).
451 Do().
452 UnmarshalInto(&user)
453 if err != nil {
454 return "", err
455 }
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 {
460 return "", err
461 }
462 }
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))
472// isVerifiedUser
473func (p *GitHubProvider) isVerifiedUser(username string) bool {
474 for _, u := range p.Users {
475 if username == u {
476 return true
477 }
478 }
479 return false