forked from leg100/otf
/
client.go
584 lines (523 loc) · 16.1 KB
/
client.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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
package github
import (
"context"
"sort"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"path"
"strconv"
"strings"
"time"
"github.com/bradleyfalzon/ghinstallation/v2"
"github.com/google/go-github/v55/github"
"github.com/tofutf/tofutf/internal"
"github.com/tofutf/tofutf/internal/authenticator"
otfhttp "github.com/tofutf/tofutf/internal/http"
"github.com/tofutf/tofutf/internal/vcs"
"golang.org/x/oauth2"
)
type (
// Client is a wrapper around the upstream go-github client
Client struct {
client *github.Client
// whether authenticated using an installation access token
iat bool
}
ClientOptions struct {
Hostname string
SkipTLSVerification bool
// Only specify one of the following
OAuthToken *oauth2.Token
PersonalToken *string
*AppCredentials
*InstallCredentials
}
// Credentials for authenticating as an app:
// https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/about-authentication-with-a-github-app#authentication-as-a-github-app
AppCredentials struct {
// Github app ID
ID int64
// Private key in PEM format
PrivateKey string
}
// Credentials for authenticating as an app installation:
// https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/about-authentication-with-a-github-app#authentication-as-an-app-installation
InstallCredentials struct {
// Github installation ID
ID int64
// Github username if installed in a user account; mutually exclusive
// with Organization
User *string
// Github organization if installed in an organization; mutually
// exclusive with User
Organization *string
AppCredentials
}
)
func NewClient(cfg ClientOptions) (*Client, error) {
if cfg.Hostname == "" {
cfg.Hostname = DefaultHostname
}
// build http roundtripper using provided credentials
var (
tripper = http.DefaultTransport
err error
iat bool
)
if cfg.SkipTLSVerification {
tripper = otfhttp.InsecureTransport
}
switch {
case cfg.AppCredentials != nil:
tripper, err = ghinstallation.NewAppsTransport(tripper, cfg.AppCredentials.ID, []byte(cfg.AppCredentials.PrivateKey))
if err != nil {
return nil, err
}
case cfg.InstallCredentials != nil:
iat = true
creds := cfg.InstallCredentials
installTransport, err := ghinstallation.New(tripper, creds.AppCredentials.ID, creds.ID, []byte(creds.AppCredentials.PrivateKey))
if err != nil {
return nil, err
}
// ghinstallation defaults to https://api.github.com
if cfg.Hostname != DefaultHostname {
installTransport.BaseURL = (&url.URL{Scheme: "https", Path: "/api/v3", Host: cfg.Hostname}).String()
}
tripper = installTransport
case cfg.PersonalToken != nil:
// personal token is actually an OAuth2 *access token, so wrap
// inside an OAuth2 token and handle it the same as an OAuth2 token
cfg.OAuthToken = &oauth2.Token{AccessToken: *cfg.PersonalToken}
fallthrough
case cfg.OAuthToken != nil:
tripper = &oauth2.Transport{
Base: tripper,
// Github's oauth access token never expires
Source: oauth2.ReuseTokenSource(nil, oauth2.StaticTokenSource(cfg.OAuthToken)),
}
}
// create upstream client with roundtripper
client := github.NewClient(&http.Client{Transport: tripper})
// Assume github enterprise if using non-default hostname
if cfg.Hostname != DefaultHostname {
client, err = client.WithEnterpriseURLs(
"https://"+cfg.Hostname,
"https://"+cfg.Hostname,
)
if err != nil {
return nil, err
}
}
return &Client{client: client, iat: iat}, nil
}
func NewTokenClient(opts vcs.NewTokenClientOptions) (vcs.Client, error) {
return NewClient(ClientOptions{
Hostname: opts.Hostname,
PersonalToken: &opts.Token,
SkipTLSVerification: opts.SkipTLSVerification,
})
}
func NewOAuthClient(cfg authenticator.OAuthConfig, token *oauth2.Token) (authenticator.IdentityProviderClient, error) {
return NewClient(ClientOptions{
Hostname: cfg.Hostname,
OAuthToken: token,
SkipTLSVerification: cfg.SkipTLSVerification,
})
}
func (g *Client) GetCurrentUser(ctx context.Context) (string, error) {
guser, _, err := g.client.Users.Get(ctx, "")
if err != nil {
return "", err
}
return guser.GetLogin(), nil
}
func (g *Client) GetRepository(ctx context.Context, identifier string) (vcs.Repository, error) {
owner, name, found := strings.Cut(identifier, "/")
if !found {
return vcs.Repository{}, fmt.Errorf("malformed identifier: %s", identifier)
}
repo, _, err := g.client.Repositories.Get(ctx, owner, name)
if err != nil {
return vcs.Repository{}, err
}
return vcs.Repository{
Path: identifier,
DefaultBranch: repo.GetDefaultBranch(),
}, nil
}
// ListRepositories lists repositories belonging to the authenticated entity: if
// authenticated using a user's oauth token or PAT then their repos are listed;
// if authenticated using a github installation then repos that the installation
// has access to are listed.
//
// ListRepositories has different behaviour depending on the authentication:
// (a) if authenticated as an app installation then repositories accessible to
// the installation are listed; *all* repos are listed, in order of last pushed
// to.
// (b) if authenticated using a personal access token then repositories
// belonging to the user are listed; only the first page of repos is listed,
// those that have most recently been pushed to.
func (g *Client) ListRepositories(ctx context.Context, opts vcs.ListRepositoriesOptions) ([]string, error) {
var (
repos []*github.Repository
)
if g.iat {
// Apps.ListRepos endpoint does not support ordering on the server-side,
// so instead we request *all* repos, page-by-page, and then sort
// client-side.
var page = 1
for {
result, resp, err := g.client.Apps.ListRepos(ctx, &github.ListOptions{
PerPage: opts.PageSize,
Page: page,
})
if err != nil {
return nil, err
}
repos = append(repos, result.Repositories...)
if resp.NextPage != 0 {
page = resp.NextPage
} else {
break
}
}
// sort repositories in order of most recently pushed to
sort.Slice(repos, func(i, j int) bool { return repos[i].GetPushedAt().After(repos[j].GetPushedAt().Time) })
} else {
var err error
repos, _, err = g.client.Repositories.List(ctx, "", &github.RepositoryListOptions{
ListOptions: github.ListOptions{PerPage: opts.PageSize},
// retrieve repositories in order of most recently pushed to
Sort: "pushed",
})
if err != nil {
return nil, err
}
}
names := make([]string, len(repos))
for i, repo := range repos {
names[i] = repo.GetFullName()
}
return names, nil
}
func (g *Client) ListTags(ctx context.Context, opts vcs.ListTagsOptions) ([]string, error) {
owner, name, found := strings.Cut(opts.Repo, "/")
if !found {
return nil, fmt.Errorf("malformed identifier: %s", opts.Repo)
}
results, _, err := g.client.Git.ListMatchingRefs(ctx, owner, name, &github.ReferenceListOptions{
Ref: "tags/" + opts.Prefix,
})
if err != nil {
return nil, err
}
// return tags with the format 'tags/<tag_value>'
tags := make([]string, len(results))
for i, ref := range results {
tags[i] = strings.TrimPrefix(ref.GetRef(), "refs/")
}
return tags, nil
}
func (g *Client) ExchangeCode(ctx context.Context, code string) (*github.AppConfig, error) {
cfg, _, err := g.client.Apps.CompleteAppManifest(ctx, code)
if err != nil {
return nil, err
}
return cfg, nil
}
func (g *Client) GetRepoTarball(ctx context.Context, opts vcs.GetRepoTarballOptions) ([]byte, string, error) {
owner, name, found := strings.Cut(opts.Repo, "/")
if !found {
return nil, "", fmt.Errorf("malformed identifier: %s", opts.Repo)
}
var gopts github.RepositoryContentGetOptions
if opts.Ref != nil {
gopts.Ref = *opts.Ref
}
link, _, err := g.client.Repositories.GetArchiveLink(ctx, owner, name, github.Tarball, &gopts, true)
if err != nil {
return nil, "", err
}
resp, err := g.client.Client().Get(link.String())
if err != nil {
return nil, "", err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
// parse out the query string which contains credential
u, _ := url.Parse(link.String())
return nil, "", fmt.Errorf("non-200 status code: %d: %s", resp.StatusCode, u.Path)
}
// github tarball contains a parent directory of the format
// <owner>-<repo>-<commit>. We need a tarball without this parent directory,
// so we untar it to a temp dir, then tar it up the contents of the parent
// directory.
untarpath, err := os.MkdirTemp("", fmt.Sprintf("github-%s-%s-*", owner, name))
if err != nil {
return nil, "", err
}
defer os.RemoveAll(untarpath)
if err := internal.Unpack(resp.Body, untarpath); err != nil {
return nil, "", err
}
contents, err := os.ReadDir(untarpath)
if err != nil {
return nil, "", err
}
if len(contents) != 1 {
return nil, "", fmt.Errorf("expected only one top-level directory; instead got %s", contents)
}
dir := contents[0].Name()
parts := strings.Split(dir, "-")
if len(parts) < 3 {
return nil, "", fmt.Errorf("malformed directory name found in tarball: %s", dir)
}
parentDir := path.Join(untarpath, dir)
tarball, err := internal.Pack(parentDir)
if err != nil {
return nil, "", err
}
return tarball, parts[len(parts)-1], nil
}
// CreateWebhook creates a webhook on a github repository.
func (g *Client) CreateWebhook(ctx context.Context, opts vcs.CreateWebhookOptions) (string, error) {
owner, name, found := strings.Cut(opts.Repo, "/")
if !found {
return "", fmt.Errorf("malformed identifier: %s", opts.Repo)
}
var events []string
for _, event := range opts.Events {
switch event {
case vcs.EventTypePush:
events = append(events, "push")
case vcs.EventTypePull:
events = append(events, "pull_request")
}
}
hook, _, err := g.client.Repositories.CreateHook(ctx, owner, name, &github.Hook{
Events: events,
Config: map[string]any{
"url": opts.Endpoint,
"secret": opts.Secret,
"content_type": "json",
},
Active: internal.Bool(true),
})
if err != nil {
return "", err
}
return strconv.FormatInt(hook.GetID(), 10), nil
}
func (g *Client) UpdateWebhook(ctx context.Context, id string, opts vcs.UpdateWebhookOptions) error {
owner, name, found := strings.Cut(opts.Repo, "/")
if !found {
return fmt.Errorf("malformed identifier: %s", opts.Repo)
}
intID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
return err
}
var events []string
for _, event := range opts.Events {
switch event {
case vcs.EventTypePush:
events = append(events, "push")
case vcs.EventTypePull:
events = append(events, "pull_request")
}
}
_, _, err = g.client.Repositories.EditHook(ctx, owner, name, intID, &github.Hook{
Events: events,
Config: map[string]any{
"url": opts.Endpoint,
"secret": opts.Secret,
"content_type": "json",
},
Active: internal.Bool(true),
})
if err != nil {
return err
}
return nil
}
func (g *Client) GetWebhook(ctx context.Context, opts vcs.GetWebhookOptions) (vcs.Webhook, error) {
owner, name, found := strings.Cut(opts.Repo, "/")
if !found {
return vcs.Webhook{}, fmt.Errorf("malformed identifier: %s", opts.Repo)
}
intID, err := strconv.ParseInt(opts.ID, 10, 64)
if err != nil {
return vcs.Webhook{}, err
}
hook, resp, err := g.client.Repositories.GetHook(ctx, owner, name, intID)
if err != nil {
if resp.StatusCode == http.StatusNotFound {
return vcs.Webhook{}, internal.ErrResourceNotFound
}
return vcs.Webhook{}, err
}
var events []vcs.EventType
for _, event := range hook.Events {
switch event {
case "push":
events = append(events, vcs.EventTypePush)
case "pull_request":
events = append(events, vcs.EventTypePull)
}
}
// extracting OTF endpoint from github's config map is a bit of work...
rawEndpoint, ok := hook.Config["url"]
if !ok {
return vcs.Webhook{}, errors.New("missing url")
}
endpoint, ok := rawEndpoint.(string)
if !ok {
return vcs.Webhook{}, errors.New("url is not a string")
}
return vcs.Webhook{
ID: strconv.FormatInt(hook.GetID(), 10),
Repo: opts.Repo,
Events: events,
Endpoint: endpoint,
}, nil
}
func (g *Client) DeleteWebhook(ctx context.Context, opts vcs.DeleteWebhookOptions) error {
owner, name, found := strings.Cut(opts.Repo, "/")
if !found {
return fmt.Errorf("malformed identifier: %s", opts.Repo)
}
intID, err := strconv.ParseInt(opts.ID, 10, 64)
if err != nil {
return err
}
_, err = g.client.Repositories.DeleteHook(ctx, owner, name, intID)
return err
}
func (g *Client) SetStatus(ctx context.Context, opts vcs.SetStatusOptions) error {
owner, name, found := strings.Cut(opts.Repo, "/")
if !found {
return fmt.Errorf("malformed identifier: %s", opts.Repo)
}
var status string
switch opts.Status {
case vcs.PendingStatus, vcs.RunningStatus:
status = "pending"
case vcs.SuccessStatus:
status = "success"
case vcs.ErrorStatus:
status = "error"
case vcs.FailureStatus:
status = "failure"
default:
return fmt.Errorf("invalid vcs status: %s", opts.Status)
}
_, _, err := g.client.Repositories.CreateStatus(ctx, owner, name, opts.Ref, &github.RepoStatus{
Context: internal.String(fmt.Sprintf("otf/%s", opts.Workspace)),
TargetURL: internal.String(opts.TargetURL),
Description: internal.String(opts.Description),
State: internal.String(status),
})
return err
}
func (g *Client) ListPullRequestFiles(ctx context.Context, repo string, pull int) ([]string, error) {
owner, name, found := strings.Cut(repo, "/")
if !found {
return nil, fmt.Errorf("malformed identifier: %s", repo)
}
var files []string
nextPage := 0
listloop:
for {
opts := github.ListOptions{
PerPage: 300,
}
if nextPage != 0 {
opts.Page = nextPage
}
// GitHub has started to return 404's sometimes. They've got some
// eventual consistency issues going on so we're just going to attempt
// up to 5 times for each page with exponential backoff.
maxAttempts := 5
attemptDelay := 0 * time.Second
for i := 0; i < maxAttempts; i++ {
// First don't sleep, then sleep 1, 3, 7, etc.
time.Sleep(attemptDelay)
attemptDelay = 2*attemptDelay + 1*time.Second
pageFiles, resp, err := g.client.PullRequests.ListFiles(ctx, owner, name, pull, &opts)
if err != nil {
ghErr, ok := err.(*github.ErrorResponse)
if ok && ghErr.Response.StatusCode == 404 {
// (hopefully) transient 404, retry after backoff
continue
}
// something else, give up
return files, err
}
for _, f := range pageFiles {
files = append(files, f.GetFilename())
// If the file was renamed, we'll want to run plan in the directory
// it was moved from as well.
if f.GetStatus() == "renamed" {
files = append(files, f.GetPreviousFilename())
}
}
if resp.NextPage == 0 {
break listloop
}
nextPage = resp.NextPage
break
}
}
return files, nil
}
func (g *Client) GetCommit(ctx context.Context, repo, ref string) (vcs.Commit, error) {
owner, name, found := strings.Cut(repo, "/")
if !found {
return vcs.Commit{}, fmt.Errorf("malformed identifier: %s", repo)
}
commit, resp, err := g.client.Repositories.GetCommit(ctx, owner, name, ref, nil)
if err != nil {
return vcs.Commit{}, err
}
defer resp.Body.Close()
return vcs.Commit{
SHA: commit.GetSHA(),
URL: commit.GetHTMLURL(),
Author: vcs.CommitAuthor{
Username: commit.GetAuthor().GetLogin(),
AvatarURL: commit.GetAuthor().GetAvatarURL(),
ProfileURL: commit.GetAuthor().GetHTMLURL(),
},
}, nil
}
// ListInstallations lists installations of the currently authenticated app.
func (g *Client) ListInstallations(ctx context.Context) ([]*github.Installation, error) {
installs, resp, err := g.client.Apps.ListInstallations(ctx, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return installs, err
}
func (g *Client) GetInstallation(ctx context.Context, installID int64) (*github.Installation, error) {
install, resp, err := g.client.Apps.GetInstallation(ctx, installID)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return install, err
}
// DeleteInstallation deletes an installation of a github app with the given
// installation ID.
func (g *Client) DeleteInstallation(ctx context.Context, installID int64) error {
resp, err := g.client.Apps.DeleteInstallation(ctx, installID)
if err != nil {
return err
}
defer resp.Body.Close()
return err
}