forked from kubernetes/test-infra
/
prstatus.go
303 lines (274 loc) · 8.28 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
/*
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/githubql"
"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
}
type githubRestfulClient interface {
GetUser(login string) (*gogithub.User, error)
}
type pullRequestRestfulClient struct {
*ghclient.Client
}
func (grc pullRequestRestfulClient) GetUser(login string) (*gogithub.User, error) {
return grc.Client.GetUser(login)
}
// PullRequestQueryHandler defines an interface that query handlers should implement.
type PullRequestQueryHandler interface {
QueryPullRequests(context.Context, githubClient, string) ([]PullRequest, 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
PullRequests []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 githubql.ID
Name githubql.String
}
type PullRequest struct {
Number githubql.Int
Merged githubql.Boolean
Title githubql.String
Author struct {
Login githubql.String
}
BaseRef struct {
Name githubql.String
Prefix githubql.String
}
HeadRefOID githubql.String `graphql:"headRefOid"`
Repository struct {
Name githubql.String
NameWithOwner githubql.String
Owner struct {
Login githubql.String
}
}
Labels struct {
Nodes []struct {
Label Label `graphql:"... on Label"`
}
} `graphql:"labels(first: 100)"`
Milestone struct {
ID githubql.ID
Closed githubql.Boolean
}
}
type UserLoginQuery struct {
Viewer struct {
Login githubql.String
}
}
type searchQuery struct {
RateLimit struct {
Cost githubql.Int
Remaining githubql.Int
}
Search struct {
PageInfo struct {
HasNextPage githubql.Boolean
EndCursor githubql.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.
grc := pullRequestRestfulClient{ghclient.NewClient(token.AccessToken, false)}
var err error
user, err = grc.GetUser("")
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
}
// Construct query
ghc := github.NewClient(token.AccessToken, 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
} else {
data.PullRequests = pullRequests
}
}
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": (githubql.String)(query),
"searchCursor": (*githubql.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"] = githubql.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) 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
}