forked from jenkins-x/test-infra
/
prstatus.go
350 lines (317 loc) · 9.79 KB
/
prstatus.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
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package prstatus
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
gogithub "github.com/google/go-github/github"
"github.com/shurcooL/githubv4"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"k8s.io/test-infra/ghclient"
"k8s.io/test-infra/prow/config"
"k8s.io/test-infra/prow/github"
)
const (
loginSession = "github_login"
githubEndpoint = "https://api.github.com"
tokenSession = "access-token-session"
tokenKey = "access-token"
loginKey = "login"
)
type githubClient interface {
Query(context.Context, interface{}, map[string]interface{}) error
GetCombinedStatus(org, repo, ref string) (*github.CombinedStatus, error)
}
// PullRequestQueryHandler defines an interface that query handlers should implement.
type PullRequestQueryHandler interface {
HeadContexts(ghc githubClient, pr PullRequest) ([]Context, error)
QueryPullRequests(context.Context, githubClient, string) ([]PullRequest, error)
GetUser(*ghclient.Client) (*gogithub.User, error)
}
// UserData represents data returned to client request to the endpoint. It has a flag that indicates
// whether the user has logged in his github or not and list of open pull requests owned by the
// user.
type UserData struct {
Login bool
PullRequestsWithContexts []PullRequestWithContext
}
// PullRequestWithContext contains a pull request with its latest context.
type PullRequestWithContext struct {
Contexts []Context
PullRequest PullRequest
}
// Dashboard Agent is responsible for handling request to /pr-status endpoint. It will serve
// list of open pull requests owned by the user.
type DashboardAgent struct {
repos []string
goac *config.GithubOAuthConfig
log *logrus.Entry
}
type Label struct {
ID githubv4.ID
Name githubv4.String
}
// Context represent github contexts.
type Context struct {
Context string
Description string
State string
}
// PullRequest holds graphql response data for github pull request.
type PullRequest struct {
Number githubv4.Int
Merged githubv4.Boolean
Title githubv4.String
Author struct {
Login githubv4.String
}
BaseRef struct {
Name githubv4.String
Prefix githubv4.String
}
HeadRefOID githubv4.String `graphql:"headRefOid"`
Repository struct {
Name githubv4.String
NameWithOwner githubv4.String
Owner struct {
Login githubv4.String
}
}
Labels struct {
Nodes []struct {
Label Label `graphql:"... on Label"`
}
} `graphql:"labels(first: 100)"`
Milestone struct {
ID githubv4.ID
Closed githubv4.Boolean
}
}
type UserLoginQuery struct {
Viewer struct {
Login githubv4.String
}
}
type searchQuery struct {
RateLimit struct {
Cost githubv4.Int
Remaining githubv4.Int
}
Search struct {
PageInfo struct {
HasNextPage githubv4.Boolean
EndCursor githubv4.String
}
Nodes []struct {
PullRequest PullRequest `graphql:"... on PullRequest"`
}
} `graphql:"search(type: ISSUE, first: 100, after: $searchCursor, query: $query)"`
}
// Returns new user dashboard agent.
func NewDashboardAgent(repos []string, config *config.GithubOAuthConfig, log *logrus.Entry) *DashboardAgent {
return &DashboardAgent{
repos: repos,
goac: config,
log: log,
}
}
// HandlePrStatus returns a http handler function that handles request to /pr-status
// endpoint. The handler takes user access token stored in the cookie to query to Github on behalf
// of the user and serve the data in return. The Query handler is passed to the method so as it
// can be mocked in the unit test..
func (da *DashboardAgent) HandlePrStatus(queryHandler PullRequestQueryHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
serverError := func(action string, err error) {
da.log.WithError(err).Errorf("Error %s.", action)
msg := fmt.Sprintf("500 Internal server error %s: %v", action, err)
http.Error(w, msg, http.StatusInternalServerError)
}
session, err := da.goac.CookieStore.Get(r, tokenSession)
if err != nil {
serverError("Error with getting git token session.", err)
return
}
token, ok := session.Values[tokenKey].(*oauth2.Token)
data := UserData{
Login: false,
}
var user *gogithub.User
if ok && token.Valid() {
// If access token exist, get user login using the access token. This is a chance
// to validate whether the access token is consumable or not. If not, invalidate the
// session.
goGithubClient := ghclient.NewClient(token.AccessToken, false)
var err error
user, err = queryHandler.GetUser(goGithubClient)
if err != nil {
if strings.Contains(err.Error(), "401") {
// Invalidate access token session
session.Options.MaxAge = -1
if err := session.Save(r, w); err != nil {
serverError("Error with saving invalidated session", err)
return
}
// Invalidate github login session
http.SetCookie(w, &http.Cookie{
Name: loginSession,
Path: "/",
Expires: time.Now().Add(-time.Hour * 24),
MaxAge: -1,
Secure: true,
})
} else {
serverError("Error with getting user login", err)
return
}
}
}
if user != nil {
login := *user.Login
data.Login = true
// Saves login. We save the login under 2 cookies. One for the use of client to render the
// data and one encoded for server to verify the identity of the authenticated user.
http.SetCookie(w, &http.Cookie{
Name: loginSession,
Value: login,
Path: "/",
Expires: time.Now().Add(time.Hour * 24 * 30),
Secure: true,
})
session.Values[loginKey] = login
if err := session.Save(r, w); err != nil {
serverError("Save oauth session", err)
return
}
getSecret := func() []byte {
return []byte(token.AccessToken)
}
// Construct query
ghc := github.NewClient(getSecret, githubEndpoint)
query := da.ConstructSearchQuery(login)
if err := r.ParseForm(); err == nil {
if q := r.Form.Get("query"); q != "" {
query = q
}
}
// If neither repo nor org is specified in the search query. We limit the search to repos that
// are configured with either Prow or Tide.
if !queryConstrainsRepos(query) {
for _, v := range da.repos {
query += fmt.Sprintf(" repo:\"%s\"", v)
}
}
pullRequests, err := queryHandler.QueryPullRequests(context.Background(), ghc, query)
if err != nil {
serverError("Error with querying user data.", err)
return
}
var pullRequestWithContexts []PullRequestWithContext
for _, pr := range pullRequests {
prcontext, err := queryHandler.HeadContexts(ghc, pr)
if err != nil {
serverError("Error with getting head context of pr", err)
continue
}
pullRequestWithContexts = append(pullRequestWithContexts, PullRequestWithContext{
Contexts: prcontext,
PullRequest: pr,
})
}
data.PullRequestsWithContexts = pullRequestWithContexts
}
marshaledData, err := json.Marshal(data)
if err != nil {
da.log.WithError(err).Error("Error with marshalling user data.")
}
if v := r.URL.Query().Get("var"); v != "" {
fmt.Fprintf(w, "var %s = ", v)
w.Write(marshaledData)
io.WriteString(w, ";")
} else {
w.Write(marshaledData)
}
}
}
// Query function that returns a list of open pull requests owned by the user whose access token
// is consumed by the github client.
func (da *DashboardAgent) QueryPullRequests(ctx context.Context, ghc githubClient, query string) ([]PullRequest, error) {
var prs []PullRequest
vars := map[string]interface{}{
"query": (githubv4.String)(query),
"searchCursor": (*githubv4.String)(nil),
}
var totalCost int
var remaining int
for {
sq := searchQuery{}
if err := ghc.Query(ctx, &sq, vars); err != nil {
return nil, err
}
totalCost += int(sq.RateLimit.Cost)
remaining = int(sq.RateLimit.Remaining)
for _, n := range sq.Search.Nodes {
prs = append(prs, n.PullRequest)
}
if !sq.Search.PageInfo.HasNextPage {
break
}
vars["searchCursor"] = githubv4.NewString(sq.Search.PageInfo.EndCursor)
}
da.log.Infof("Search for query \"%s\" cost %d point(s). %d remaining.", query, totalCost, remaining)
return prs, nil
}
func (da *DashboardAgent) HeadContexts(ghc githubClient, pr PullRequest) ([]Context, error) {
org := string(pr.Repository.Owner.Login)
repo := string(pr.Repository.Name)
combined, err := ghc.GetCombinedStatus(org, repo, string(pr.HeadRefOID))
if err != nil {
return nil, fmt.Errorf("failed to get the combined status: %v", err)
}
contexts := make([]Context, 0, len(combined.Statuses))
for _, status := range combined.Statuses {
contexts = append(
contexts,
Context{
Context: status.Context,
Description: status.Description,
State: strings.ToUpper(status.State),
},
)
}
return contexts, nil
}
func (da *DashboardAgent) GetUser(client *ghclient.Client) (*gogithub.User, error) {
return client.GetUser("")
}
func (da *DashboardAgent) ConstructSearchQuery(login string) string {
tokens := []string{"is:pr", "state:open", "author:" + login}
for i := range da.repos {
tokens = append(tokens, fmt.Sprintf("repo:\"%s\"", da.repos[i]))
}
return strings.Join(tokens, " ")
}
func queryConstrainsRepos(q string) bool {
tkns := strings.Split(q, " ")
for _, tkn := range tkns {
if strings.HasPrefix(tkn, "org:") || strings.HasPrefix(tkn, "repo:") {
return true
}
}
return false
}