git.iko.soy/typeable/oauth2-proxy
on c0fb7e8 help sign in
373 lines 9.3 kB history raw
1package providers
3import (
4 "encoding/json"
5 "fmt"
6 "io/ioutil"
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"
18// GitHubProvider represents an GitHub based Identity Provider
19type GitHubProvider struct {
20 *ProviderData
21 Org string
22 Team string
25// NewGitHubProvider initiates a new GitHubProvider
26func NewGitHubProvider(p *ProviderData) *GitHubProvider {
27 p.ProviderName = "GitHub"
28 if p.LoginURL == nil || p.LoginURL.String() == "" {
29 p.LoginURL = &url.URL{
30 Scheme: "https",
31 Host: "github.com",
32 Path: "/login/oauth/authorize",
33 }
34 }
35 if p.RedeemURL == nil || p.RedeemURL.String() == "" {
36 p.RedeemURL = &url.URL{
37 Scheme: "https",
38 Host: "github.com",
39 Path: "/login/oauth/access_token",
40 }
41 }
42 // ValidationURL is the API Base URL
43 if p.ValidateURL == nil || p.ValidateURL.String() == "" {
44 p.ValidateURL = &url.URL{
45 Scheme: "https",
46 Host: "api.github.com",
47 Path: "/",
48 }
49 }
50 if p.Scope == "" {
51 p.Scope = "user:email"
52 }
53 return &GitHubProvider{ProviderData: p}
56func getGitHubHeader(accessToken string) http.Header {
57 header := make(http.Header)
58 header.Set("Accept", "application/vnd.github.v3+json")
59 header.Set("Authorization", fmt.Sprintf("token %s", accessToken))
60 return header
63// SetOrgTeam adds GitHub org reading parameters to the OAuth2 scope
64func (p *GitHubProvider) SetOrgTeam(org, team string) {
65 p.Org = org
66 p.Team = team
67 if org != "" || team != "" {
68 p.Scope += " read:org"
69 }
72func (p *GitHubProvider) hasOrg(accessToken string) (bool, error) {
73 // https://developer.github.com/v3/orgs/#list-your-organizations
75 var orgs []struct {
76 Login string `json:"login"`
77 }
79 type orgsPage []struct {
80 Login string `json:"login"`
81 }
83 pn := 1
84 for {
85 params := url.Values{
86 "per_page": {"100"},
87 "page": {strconv.Itoa(pn)},
88 }
90 endpoint := &url.URL{
91 Scheme: p.ValidateURL.Scheme,
92 Host: p.ValidateURL.Host,
93 Path: path.Join(p.ValidateURL.Path, "/user/orgs"),
94 RawQuery: params.Encode(),
95 }
96 req, _ := http.NewRequest("GET", endpoint.String(), nil)
97 req.Header = getGitHubHeader(accessToken)
98 resp, err := http.DefaultClient.Do(req)
99 if err != nil {
100 return false, err
101 }
103 body, err := ioutil.ReadAll(resp.Body)
104 resp.Body.Close()
105 if err != nil {
106 return false, err
107 }
108 if resp.StatusCode != 200 {
109 return false, fmt.Errorf(
110 "got %d from %q %s", resp.StatusCode, endpoint.String(), body)
111 }
113 var op orgsPage
114 if err := json.Unmarshal(body, &op); err != nil {
115 return false, err
116 }
117 if len(op) == 0 {
118 break
119 }
121 orgs = append(orgs, op...)
122 pn++
123 }
125 var presentOrgs []string
126 for _, org := range orgs {
127 if p.Org == org.Login {
128 logger.Printf("Found Github Organization: %q", org.Login)
129 return true, nil
130 }
131 presentOrgs = append(presentOrgs, org.Login)
132 }
134 logger.Printf("Missing Organization:%q in %v", p.Org, presentOrgs)
135 return false, nil
138func (p *GitHubProvider) hasOrgAndTeam(accessToken string) (bool, error) {
139 // https://developer.github.com/v3/orgs/teams/#list-user-teams
141 var teams []struct {
142 Name string `json:"name"`
143 Slug string `json:"slug"`
144 Org struct {
145 Login string `json:"login"`
146 } `json:"organization"`
147 }
149 type teamsPage []struct {
150 Name string `json:"name"`
151 Slug string `json:"slug"`
152 Org struct {
153 Login string `json:"login"`
154 } `json:"organization"`
155 }
157 pn := 1
158 last := 0
159 for {
160 params := url.Values{
161 "per_page": {"100"},
162 "page": {strconv.Itoa(pn)},
163 }
165 endpoint := &url.URL{
166 Scheme: p.ValidateURL.Scheme,
167 Host: p.ValidateURL.Host,
168 Path: path.Join(p.ValidateURL.Path, "/user/teams"),
169 RawQuery: params.Encode(),
170 }
172 req, _ := http.NewRequest("GET", endpoint.String(), nil)
173 req.Header = getGitHubHeader(accessToken)
174 resp, err := http.DefaultClient.Do(req)
175 if err != nil {
176 return false, err
177 }
179 if last == 0 {
180 // link header may not be obtained
181 // When paging is not required and all data can be retrieved with a single call
183 // Conditions for obtaining the link header.
184 // 1. When paging is required (Example: When the data size is 100 and the page size is 99 or less)
185 // 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)
187 // link header at not last page
188 // <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"
189 // link header at last page (doesn't exist last info)
190 // <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"
192 link := resp.Header.Get("Link")
193 rep1 := regexp.MustCompile(`(?s).*\<https://api.github.com/user/teams\?page=(.)&per_page=[0-9]+\>; rel="last".*`)
194 i, converr := strconv.Atoi(rep1.ReplaceAllString(link, "$1"))
196 // If the last page cannot be taken from the link in the http header, the last variable remains zero
197 if converr == nil {
198 last = i
199 }
200 }
202 body, err := ioutil.ReadAll(resp.Body)
203 if err != nil {
204 resp.Body.Close()
205 return false, err
206 }
207 resp.Body.Close()
209 if resp.StatusCode != 200 {
210 return false, fmt.Errorf(
211 "got %d from %q %s", resp.StatusCode, endpoint.String(), body)
212 }
214 var tp teamsPage
215 if err := json.Unmarshal(body, &tp); err != nil {
216 return false, fmt.Errorf("%s unmarshaling %s", err, body)
217 }
218 if len(tp) == 0 {
219 break
220 }
222 teams = append(teams, tp...)
224 if pn == last {
225 break
226 }
227 if last == 0 {
228 break
229 }
231 pn++
232 }
234 var hasOrg bool
235 presentOrgs := make(map[string]bool)
236 var presentTeams []string
237 for _, team := range teams {
238 presentOrgs[team.Org.Login] = true
239 if p.Org == team.Org.Login {
240 hasOrg = true
241 ts := strings.Split(p.Team, ",")
242 for _, t := range ts {
243 if t == team.Slug {
244 logger.Printf("Found Github Organization:%q Team:%q (Name:%q)", team.Org.Login, team.Slug, team.Name)
245 return true, nil
246 }
247 }
248 presentTeams = append(presentTeams, team.Slug)
249 }
250 }
251 if hasOrg {
252 logger.Printf("Missing Team:%q from Org:%q in teams: %v", p.Team, p.Org, presentTeams)
253 } else {
254 var allOrgs []string
255 for org := range presentOrgs {
256 allOrgs = append(allOrgs, org)
257 }
258 logger.Printf("Missing Organization:%q in %#v", p.Org, allOrgs)
259 }
260 return false, nil
263// GetEmailAddress returns the Account email address
264func (p *GitHubProvider) GetEmailAddress(s *sessions.SessionState) (string, error) {
266 var emails []struct {
267 Email string `json:"email"`
268 Primary bool `json:"primary"`
269 Verified bool `json:"verified"`
270 }
272 // if we require an Org or Team, check that first
273 if p.Org != "" {
274 if p.Team != "" {
275 if ok, err := p.hasOrgAndTeam(s.AccessToken); err != nil || !ok {
276 return "", err
277 }
278 } else {
279 if ok, err := p.hasOrg(s.AccessToken); err != nil || !ok {
280 return "", err
281 }
282 }
283 }
285 endpoint := &url.URL{
286 Scheme: p.ValidateURL.Scheme,
287 Host: p.ValidateURL.Host,
288 Path: path.Join(p.ValidateURL.Path, "/user/emails"),
289 }
290 req, _ := http.NewRequest("GET", endpoint.String(), nil)
291 req.Header = getGitHubHeader(s.AccessToken)
292 resp, err := http.DefaultClient.Do(req)
293 if err != nil {
294 return "", err
295 }
296 body, err := ioutil.ReadAll(resp.Body)
297 resp.Body.Close()
298 if err != nil {
299 return "", err
300 }
302 if resp.StatusCode != 200 {
303 return "", fmt.Errorf("got %d from %q %s",
304 resp.StatusCode, endpoint.String(), body)
305 }
307 logger.Printf("got %d from %q %s", resp.StatusCode, endpoint.String(), body)
309 if err := json.Unmarshal(body, &emails); err != nil {
310 return "", fmt.Errorf("%s unmarshaling %s", err, body)
311 }
313 returnEmail := ""
314 for _, email := range emails {
315 if email.Verified {
316 returnEmail = email.Email
317 if email.Primary {
318 return returnEmail, nil
319 }
320 }
321 }
323 return returnEmail, nil
326// GetUserName returns the Account user name
327func (p *GitHubProvider) GetUserName(s *sessions.SessionState) (string, error) {
328 var user struct {
329 Login string `json:"login"`
330 Email string `json:"email"`
331 }
333 endpoint := &url.URL{
334 Scheme: p.ValidateURL.Scheme,
335 Host: p.ValidateURL.Host,
336 Path: path.Join(p.ValidateURL.Path, "/user"),
337 }
339 req, err := http.NewRequest("GET", endpoint.String(), nil)
340 if err != nil {
341 return "", fmt.Errorf("could not create new GET request: %v", err)
342 }
344 req.Header = getGitHubHeader(s.AccessToken)
345 resp, err := http.DefaultClient.Do(req)
346 if err != nil {
347 return "", err
348 }
350 body, err := ioutil.ReadAll(resp.Body)
351 defer resp.Body.Close()
352 if err != nil {
353 return "", err
354 }
356 if resp.StatusCode != 200 {
357 return "", fmt.Errorf("got %d from %q %s",
358 resp.StatusCode, endpoint.String(), body)
359 }
361 logger.Printf("got %d from %q %s", resp.StatusCode, endpoint.String(), body)
363 if err := json.Unmarshal(body, &user); err != nil {
364 return "", fmt.Errorf("%s unmarshaling %s", err, body)
365 }
367 return user.Login, nil
370// ValidateSessionState validates the AccessToken
371func (p *GitHubProvider) ValidateSessionState(s *sessions.SessionState) bool {
372 return validateToken(p, s.AccessToken, getGitHubHeader(s.AccessToken))