-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathnopr.go
494 lines (437 loc) · 13.5 KB
/
nopr.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
// TODO: allow users to configure behavior:
// - whether to close the PR or add a status (closing hides statuses)
// - whether to comment on the PR before closing
// - custom text to use when closing
// TODO: use appengine-value to store client secret
// TODO: use gorilla sessions instead of Google auth
// TODO: xsrf everywhere
package nopr
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"appengine"
"appengine/datastore"
"appengine/urlfetch"
"appengine/user"
"github.com/google/go-github/github"
)
const (
// TODO: store these more securely (and revoke these when you do!)
clientID = "350be49c3c1988aac719"
clientSecret = "f14c9383c4b8964781ea4acdd881946b1dfed488"
redirectURLPath = "/oauthcallback"
)
var scopes = strings.Join([]string{
"user:email", // permission to get basic information about the user
"public_repo", // permission to close PRs
"admin:repo_hook", // permission to add/delete webhooks
// TODO: ask for this when we're not just closing the PR
// "repo:status", // permission to add statuses to commits
}, ",")
func init() {
http.HandleFunc("/start", startHandler)
http.HandleFunc(redirectURLPath, oauthHandler)
http.HandleFunc("/user", userHandler)
http.HandleFunc("/enable/", enableHandler)
http.HandleFunc("/disable/", disableHandler)
http.HandleFunc("/revoke", revokeHandler)
http.HandleFunc("/hook", webhookHandler)
}
func startHandler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
u := user.Current(ctx)
if u == nil {
ctx.Infof("not logged in, redirecting...")
loginURL, _ := user.LoginURL(ctx, r.URL.Path)
http.Redirect(w, r, loginURL, http.StatusSeeOther)
return
}
ctx.Infof("starting oauth...")
redirectURL := fmt.Sprintf("https://%s.appspot.com", appengine.AppID(ctx)) + redirectURLPath
url := fmt.Sprintf("https://github.com/login/oauth/authorize?client_id=%s&redirect_uri=%s&scope=%s",
clientID, redirectURL, scopes)
http.Redirect(w, r, url, http.StatusSeeOther)
}
func renderError(w http.ResponseWriter, msg string) {
w.WriteHeader(http.StatusInternalServerError)
errorTmpl.Execute(w, msg)
}
func oauthHandler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
code := r.FormValue("code")
if code == "" {
ctx.Errorf("no code, going to start")
http.Redirect(w, r, "/start", http.StatusSeeOther)
return
}
u := user.Current(ctx)
if u == nil {
ctx.Infof("not logged in, redirecting...")
loginURL, _ := user.LoginURL(ctx, r.URL.Path)
http.Redirect(w, r, loginURL, http.StatusSeeOther)
return
}
tok, err := getAccessToken(ctx, code)
if err != nil {
ctx.Errorf("getting access token: %v", err)
renderError(w, "Error getting access token")
return
}
ghu, _, err := newClient(ctx, tok).Users.Get("")
if err != nil {
ctx.Errorf("getting user: %v", err)
renderError(w, "Error getting user")
return
}
if err := PutUser(ctx, User{
GoogleUserID: u.ID,
GitHubUserID: *ghu.ID,
GitHubToken: tok,
}); err != nil {
ctx.Errorf("put user: %v", err)
renderError(w, "Error writing user entry")
return
}
http.Redirect(w, r, "/user", http.StatusSeeOther)
}
func getAccessToken(ctx appengine.Context, code string) (string, error) {
client := urlfetch.Client(ctx)
url := fmt.Sprintf("https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s",
clientID, clientSecret, code)
req, err := http.NewRequest("POST", url, nil)
req.Header.Set("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
ctx.Errorf("exchanging code: %v", err)
return "", err
}
defer resp.Body.Close()
var b struct {
AccessToken string `json:"access_token"`
}
if err := json.NewDecoder(resp.Body).Decode(&b); err != nil {
ctx.Errorf("decoding json: %v", err)
return "", err
}
return b.AccessToken, nil
}
func newClient(ctx appengine.Context, tok string) *github.Client {
return github.NewClient(&http.Client{Transport: transport{ctx, tok}})
}
type transport struct {
ctx appengine.Context
tok string
}
func (t transport) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Set("Authorization", "token "+t.tok)
return urlfetch.Client(t.ctx).Do(req)
}
type User struct {
GoogleUserID string
GitHubUserID int
GitHubToken string
}
func PutUser(ctx appengine.Context, u User) error {
k := datastore.NewKey(ctx, "User", u.GoogleUserID, 0, nil)
_, err := datastore.Put(ctx, k, &u)
return err
}
func GetUser(ctx appengine.Context, id string) *User {
k := datastore.NewKey(ctx, "User", id, 0, nil)
var u User
if err := datastore.Get(ctx, k, &u); err == datastore.ErrNoSuchEntity {
return nil
} else if err != nil {
ctx.Errorf("getting user: %v", err)
return nil
}
return &u
}
func DeleteUser(ctx appengine.Context, userID string) error {
return datastore.Delete(ctx, datastore.NewKey(ctx, "User", userID, 0, nil))
}
func userHandler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
uu := user.Current(ctx)
if uu == nil {
ctx.Infof("not logged in, redirecting...")
loginURL, _ := user.LoginURL(ctx, r.URL.Path)
http.Redirect(w, r, loginURL, http.StatusSeeOther)
return
}
u := GetUser(ctx, uu.ID)
if u == nil {
ctx.Infof("unknown user, going to /start")
http.Redirect(w, r, "/start", http.StatusSeeOther)
return
}
repos, _, err := newClient(ctx, u.GitHubToken).Repositories.List("", &github.RepositoryListOptions{
Type: "admin",
})
if err != nil {
ctx.Errorf("listing repos: %v", err)
renderError(w, "Error listing repos")
return
}
type data struct {
Repo github.Repository
Disabled bool
}
d := []data{}
keys := []*datastore.Key{}
for _, r := range repos {
keys = append(keys, datastore.NewKey(ctx, "Repo", *r.FullName, 0, nil))
}
repoEntities := make([]Repo, len(keys))
if err := datastore.GetMulti(ctx, keys, repoEntities); err != nil {
if me, ok := err.(appengine.MultiError); ok {
for i, e := range me {
var disabled = e == nil
d = append(d, data{Repo: repos[i], Disabled: disabled})
}
} else {
ctx.Errorf("getmulti: %v", err)
renderError(w, "Error retrieving repos")
return
}
} else {
// all repos are disabled
for _, r := range repos {
d = append(d, data{Repo: r, Disabled: true})
}
}
if err := userTmpl.Execute(w, d); err != nil {
ctx.Errorf("executing template: %v", err)
}
}
type Repo struct {
FullName string // e.g., MyUser/foo-bar
UserID string // User key to use to close PRs
WebhookID int // Used to delete the hook
}
func (r Repo) Split() (string, string) {
parts := strings.Split(r.FullName, "/")
if len(parts) < 2 {
panic("invalid full name: " + r.FullName)
}
return parts[0], parts[1]
}
func PutRepo(ctx appengine.Context, r Repo) error {
k := datastore.NewKey(ctx, "Repo", r.FullName, 0, nil)
_, err := datastore.Put(ctx, k, &r)
return err
}
func GetRepo(ctx appengine.Context, fn string) *Repo {
k := datastore.NewKey(ctx, "Repo", fn, 0, nil)
var r Repo
if err := datastore.Get(ctx, k, &r); err == datastore.ErrNoSuchEntity {
return nil
} else if err != nil {
ctx.Errorf("getting repo: %v", err)
return nil
}
return &r
}
func DeleteRepo(ctx appengine.Context, fn string) error {
return datastore.Delete(ctx, datastore.NewKey(ctx, "Repo", fn, 0, nil))
}
func disableHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
return
}
ctx := appengine.NewContext(r)
uu := user.Current(ctx)
if uu == nil {
ctx.Infof("not logged in, redirecting...")
loginURL, _ := user.LoginURL(ctx, r.URL.Path)
http.Redirect(w, r, loginURL, http.StatusSeeOther)
return
}
u := GetUser(ctx, uu.ID)
if u == nil {
ctx.Infof("unknown user, going to /start")
http.Redirect(w, r, "/start", http.StatusSeeOther)
return
}
// TODO: check that the user is an admin on the repo
fullName := r.URL.Path[len("/disable/"):]
ghUser, ghRepo := Repo{FullName: fullName}.Split()
hook, _, err := newClient(ctx, u.GitHubToken).Repositories.CreateHook(ghUser, ghRepo, &github.Hook{
Name: github.String("web"),
Events: []string{"pull_request"},
Config: map[string]interface{}{
"content_type": "json",
"url": fmt.Sprintf("https://%s.appspot.com/hook", appengine.AppID(ctx)),
},
})
if err != nil {
ctx.Errorf("creating hook: %v", err)
renderError(w, "Error creating webhook")
return
}
if err := PutRepo(ctx, Repo{
FullName: fullName,
UserID: u.GoogleUserID,
WebhookID: *hook.ID,
}); err != nil {
ctx.Errorf("put repo: %v", err)
renderError(w, "Error writing repo entry")
return
}
http.Redirect(w, r, "/user", http.StatusSeeOther)
}
func enableHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
return
}
ctx := appengine.NewContext(r)
uu := user.Current(ctx)
if uu == nil {
ctx.Infof("not logged in, redirecting...")
loginURL, _ := user.LoginURL(ctx, r.URL.Path)
http.Redirect(w, r, loginURL, http.StatusSeeOther)
return
}
u := GetUser(ctx, uu.ID)
if u == nil {
ctx.Infof("unknown user, going to /start")
http.Redirect(w, r, "/start", http.StatusSeeOther)
return
}
// TODO: check that the user is an admin on the repo
fullName := r.URL.Path[len("/enable/"):]
repo := GetRepo(ctx, fullName)
if repo == nil {
http.Error(w, "repo not found", http.StatusNotFound)
return
}
ghUser, ghRepo := repo.Split()
if _, err := newClient(ctx, u.GitHubToken).Repositories.DeleteHook(ghUser, ghRepo, repo.WebhookID); err != nil {
ctx.Errorf("delete hook: %v", err)
renderError(w, "Error deleting webhook")
return
}
if err := DeleteRepo(ctx, repo.FullName); err != nil {
ctx.Errorf("delete repo: %v", err)
renderError(w, "Error deleting repo entry")
return
}
http.Redirect(w, r, "/user", http.StatusSeeOther)
}
func webhookHandler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
if r.Method != "POST" {
return
}
if r.Header.Get("X-Github-Event") != "pull_request" {
return
}
defer r.Body.Close()
var hook github.PullRequestEvent
if err := json.NewDecoder(r.Body).Decode(&hook); err != nil {
ctx.Errorf("decoding json: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if *hook.Action != "opened" && *hook.Action != "reopened" {
return
}
ctx.Infof("got webhook for pull request %d opened for %q (%s)", *hook.Number, *hook.Repo.FullName, *hook.PullRequest.Head.SHA)
repo := GetRepo(ctx, *hook.Repo.FullName)
if repo == nil {
ctx.Errorf("unknown repo")
// TODO: delete webhook?
return
}
user := GetUser(ctx, repo.UserID)
if user == nil {
ctx.Errorf("unknown user %q", repo.UserID)
// TODO: user who configured the hook has left?
return
}
ghUser, ghRepo := repo.Split()
client := newClient(ctx, user.GitHubToken)
// TODO: Commit statuses are hidden when the PR is closed, and stick around
// once they're reopened. Either the PR should stay open with a failed status,
// and the status should be removed when PRs are re-enabled (ugh), or we can
// just skip the status and comment and close.
/*
if _, _, err := client.Repositories.CreateStatus(ghUser, ghRepo, *hook.PullRequest.Head.SHA, &github.RepoStatus{
State: github.String("error"),
TargetURL: github.String("https://nopullrequests.appspot.com"),
Description: github.String("This repository has chosen not to enable pull requests."), // TODO: configurable
Context: github.String("no pull requests"),
}); err != nil {
ctx.Errorf("failed to create status on %q: %v", *hook.PullRequest.Head.SHA, err)
}
*/
if _, _, err := client.Issues.CreateComment(ghUser, ghRepo, *hook.Number, &github.IssueComment{
Body: github.String("This repository has chosen to disable pull requests."), // TODO: configurable
}); err != nil {
ctx.Errorf("failed to create comment: %v", err)
}
if _, _, err := client.PullRequests.Edit(ghUser, ghRepo, *hook.Number, &github.PullRequest{
State: github.String("closed"),
}); err != nil {
ctx.Errorf("failed to close pull request: %v", err)
}
}
func revokeHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
return
}
ctx := appengine.NewContext(r)
uu := user.Current(ctx)
if uu == nil {
ctx.Infof("not logged in, redirecting...")
loginURL, _ := user.LoginURL(ctx, r.URL.Path)
http.Redirect(w, r, loginURL, http.StatusSeeOther)
return
}
u := GetUser(ctx, uu.ID)
if u == nil {
ctx.Infof("unknown user, going to /start")
http.Redirect(w, r, "/start", http.StatusSeeOther)
return
}
client := newClient(ctx, u.GitHubToken)
q := datastore.NewQuery("Repo").Filter("UserID =", uu.ID)
for t := q.Run(ctx); ; {
var r Repo
if _, err := t.Next(&r); err == datastore.Done {
break
} else if err != nil {
ctx.Errorf("query: %v", err)
renderError(w, "Error listing repos")
return
}
ghUser, ghRepo := r.Split()
if _, err := client.Repositories.DeleteHook(ghUser, ghRepo, r.WebhookID); err != nil {
ctx.Errorf("delete hook: %v", err)
renderError(w, "Error deleting hook")
return
}
if err := DeleteRepo(ctx, r.FullName); err != nil {
ctx.Errorf("delete repo: %v", err)
renderError(w, "Error deleting repo entry")
return
}
}
url := fmt.Sprintf("https://api.github.com/applications/%s/tokens/%s", clientID, u.GitHubToken)
ctx.Debugf(url)
req, _ := http.NewRequest("DELETE", url, nil)
req.SetBasicAuth(clientID, clientSecret)
if resp, err := urlfetch.Client(ctx).Do(req); err != nil || resp.StatusCode != http.StatusNoContent {
ctx.Errorf("revoking token (%d): %v", resp.StatusCode, err)
renderError(w, "Error revoking access")
return
}
if err := DeleteUser(ctx, uu.ID); err != nil {
ctx.Errorf("delete user: %v", err)
renderError(w, "Error deleting user entry")
return
}
http.Redirect(w, r, "/", http.StatusSeeOther)
}