• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mindersec / minder / 24718479667

21 Apr 2026 10:54AM UTC coverage: 60.126%. First build
24718479667

Pull #6382

github

web-flow
Merge 87fe9b564 into fef41377a
Pull Request #6382: test(engine): add unit tests for commit metadata extraction

26 of 81 new or added lines in 3 files covered. (32.1%)

20250 of 33679 relevant lines covered (60.13%)

35.96 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

60.59
/internal/providers/github/common.go
1
// SPDX-FileCopyrightText: Copyright 2023 The Minder Authors
2
// SPDX-License-Identifier: Apache-2.0
3

4
// Package github provides a client for interacting with the GitHub API
5
package github
6

7
import (
8
        "bytes"
9
        "context"
10
        "errors"
11
        "fmt"
12
        "io"
13
        "net/http"
14
        "net/url"
15
        "sort"
16
        "strings"
17
        "time"
18

19
        backoffv4 "github.com/cenkalti/backoff/v4"
20
        "github.com/go-git/go-git/v5"
21
        "github.com/google/go-github/v63/github"
22
        "github.com/rs/zerolog"
23
        "golang.org/x/oauth2"
24
        "google.golang.org/protobuf/types/known/timestamppb"
25

26
        "github.com/mindersec/minder/internal/db"
27
        gitclient "github.com/mindersec/minder/internal/providers/git"
28
        "github.com/mindersec/minder/internal/providers/github/ghcr"
29
        "github.com/mindersec/minder/internal/providers/github/properties"
30
        "github.com/mindersec/minder/internal/providers/ratecache"
31
        minderv1 "github.com/mindersec/minder/pkg/api/protobuf/go/minder/v1"
32
        config "github.com/mindersec/minder/pkg/config/server"
33
        engerrors "github.com/mindersec/minder/pkg/engine/errors"
34
        provifv1 "github.com/mindersec/minder/pkg/providers/v1"
35
)
36

37
//go:generate go run go.uber.org/mock/mockgen -package mock_$GOPACKAGE -destination=./mock/$GOFILE -source=./$GOFILE
38

39
const (
40
        // ExpensiveRestCallTimeout is the timeout for expensive REST calls
41
        ExpensiveRestCallTimeout = 15 * time.Second
42
        // MaxRateLimitWait is the maximum time to wait for a rate limit to reset
43
        MaxRateLimitWait = 5 * time.Minute
44
        // MaxRateLimitRetries is the maximum number of retries for rate limit errors after waiting
45
        MaxRateLimitRetries = 1
46
        // DefaultRateLimitWaitTime is the default time to wait for a rate limit to reset
47
        DefaultRateLimitWaitTime = 1 * time.Minute
48

49
        githubBranchNotFoundMsg = "Branch not found"
50
)
51

52
var (
53
        // ErrNotFound denotes if the call returned a 404
54
        ErrNotFound = errors.New("not found")
55
        // ErrBranchNotFound denotes if the branch was not found
56
        ErrBranchNotFound = errors.New("branch not found")
57
        // ErrNoPackageListingClient denotes if there is no package listing client available
58
        ErrNoPackageListingClient = errors.New("no package listing client available")
59
        // ErroNoCheckPermissions is a fixed error returned when the credentialed
60
        // identity has not been authorized to use the checks API
61
        ErroNoCheckPermissions = errors.New("missing permissions: check")
62
        // ErrBranchNameEmpty is a fixed error returned when the branch name is empty
63
        ErrBranchNameEmpty = errors.New("branch name cannot be empty")
64
)
65

66
// GitHub is the struct that contains the shared GitHub client operations
67
type GitHub struct {
68
        client               *github.Client
69
        packageListingClient *github.Client
70
        cache                ratecache.RestClientCache
71
        delegate             Delegate
72
        providerClass        db.ProviderClass
73
        ghcrwrap             *ghcr.ImageLister
74
        gitConfig            config.GitConfig
75
        webhookConfig        *config.WebhookConfig
76
        propertyFetchers     properties.GhPropertyFetcherFactory
77
}
78

79
// Ensure that the GitHub client implements the GitHub interface
80
var _ provifv1.GitHub = (*GitHub)(nil)
81

82
// ClientService is an interface for GitHub operations
83
// It is used to mock GitHub operations in tests, but in order to generate
84
// mocks, the interface must be exported
85
type ClientService interface {
86
        GetInstallation(ctx context.Context, id int64, jwt string) (*github.Installation, *github.Response, error)
87
        GetUserIdFromToken(ctx context.Context, token *oauth2.Token) (*int64, error)
88
        ListUserInstallations(ctx context.Context, token *oauth2.Token) ([]*github.Installation, error)
89
        DeleteInstallation(ctx context.Context, id int64, jwt string) (*github.Response, error)
90
        GetOrgMembership(ctx context.Context, token *oauth2.Token, org string) (*github.Membership, *github.Response, error)
91
}
92

93
var _ ClientService = (*ClientServiceImplementation)(nil)
94

95
// ClientServiceImplementation is the implementation of the ClientService interface
96
type ClientServiceImplementation struct{}
97

98
// GetInstallation is a wrapper for the GitHub API to get an installation
99
func (ClientServiceImplementation) GetInstallation(
100
        ctx context.Context,
101
        installationID int64,
102
        jwt string,
103
) (*github.Installation, *github.Response, error) {
×
104
        ghClient := github.NewClient(nil).WithAuthToken(jwt)
×
105
        return ghClient.Apps.GetInstallation(ctx, installationID)
×
106
}
×
107

108
// GetUserIdFromToken is a wrapper for the GitHub API to get the user id from a token
109
func (ClientServiceImplementation) GetUserIdFromToken(ctx context.Context, token *oauth2.Token) (*int64, error) {
×
110
        ghClient := github.NewClient(nil).WithAuthToken(token.AccessToken)
×
111

×
112
        user, _, err := ghClient.Users.Get(ctx, "")
×
113
        if err != nil {
×
114
                return nil, err
×
115
        }
×
116

117
        return user.ID, nil
×
118
}
119

120
// ListUserInstallations is a wrapper for the GitHub API to list user installations
121
func (ClientServiceImplementation) ListUserInstallations(
122
        ctx context.Context, token *oauth2.Token,
123
) ([]*github.Installation, error) {
×
124
        ghClient := github.NewClient(nil).WithAuthToken(token.AccessToken)
×
125

×
126
        installations, _, err := ghClient.Apps.ListUserInstallations(ctx, nil)
×
127
        return installations, err
×
128
}
×
129

130
// DeleteInstallation is a wrapper for the GitHub API to delete an installation
131
func (ClientServiceImplementation) DeleteInstallation(ctx context.Context, id int64, jwt string) (*github.Response, error) {
×
132
        ghClient := github.NewClient(nil).WithAuthToken(jwt)
×
133
        return ghClient.Apps.DeleteInstallation(ctx, id)
×
134
}
×
135

136
// GetOrgMembership is a wrapper for the GitHub API to get users' organization membership
137
func (ClientServiceImplementation) GetOrgMembership(
138
        ctx context.Context, token *oauth2.Token, org string,
139
) (*github.Membership, *github.Response, error) {
×
140
        ghClient := github.NewClient(nil).WithAuthToken(token.AccessToken)
×
141
        return ghClient.Organizations.GetOrgMembership(ctx, "", org)
×
142
}
×
143

144
// Delegate is the interface that contains operations that differ between different GitHub actors (user vs app)
145
type Delegate interface {
146
        GetCredential() provifv1.GitHubCredential
147
        ListAllRepositories(context.Context) ([]*minderv1.Repository, error)
148
        GetUserId(ctx context.Context) (int64, error)
149
        GetName(ctx context.Context) (string, error)
150
        GetLogin(ctx context.Context) (string, error)
151
        GetPrimaryEmail(ctx context.Context) (string, error)
152
        GetOwner() string
153
        IsOrg() bool
154
}
155

156
// NewGitHub creates a new GitHub client
157
func NewGitHub(
158
        client *github.Client,
159
        packageListingClient *github.Client,
160
        cache ratecache.RestClientCache,
161
        delegate Delegate,
162
        providerClass db.ProviderClass,
163
        cfg *config.ProviderConfig,
164
        whcfg *config.WebhookConfig,
165
        propertyFetchers properties.GhPropertyFetcherFactory,
166
) *GitHub {
51✔
167
        var gitConfig config.GitConfig
51✔
168
        if cfg != nil {
60✔
169
                gitConfig = cfg.Git
9✔
170
        }
9✔
171
        return &GitHub{
51✔
172
                client:               client,
51✔
173
                packageListingClient: packageListingClient,
51✔
174
                cache:                cache,
51✔
175
                delegate:             delegate,
51✔
176
                providerClass:        providerClass,
51✔
177
                ghcrwrap:             ghcr.FromGitHubClient(client, delegate.GetOwner()),
51✔
178
                gitConfig:            gitConfig,
51✔
179
                webhookConfig:        whcfg,
51✔
180
                propertyFetchers:     propertyFetchers,
51✔
181
        }
51✔
182
}
183

184
// CanImplement returns true/false depending on whether the Provider
185
// can implement the specified trait
186
func (*GitHub) CanImplement(trait minderv1.ProviderType) bool {
×
187
        return trait == minderv1.ProviderType_PROVIDER_TYPE_GITHUB ||
×
188
                trait == minderv1.ProviderType_PROVIDER_TYPE_GIT ||
×
189
                trait == minderv1.ProviderType_PROVIDER_TYPE_REST ||
×
190
                trait == minderv1.ProviderType_PROVIDER_TYPE_REPO_LISTER
×
191
}
×
192

193
// ListPackagesByRepository returns a list of all packages for a specific repository
194
func (c *GitHub) ListPackagesByRepository(
195
        ctx context.Context,
196
        owner string,
197
        artifactType string,
198
        repositoryId int64,
199
        pageNumber int,
200
        itemsPerPage int,
201
) ([]*github.Package, error) {
4✔
202
        opt := &github.PackageListOptions{
4✔
203
                PackageType: &artifactType,
4✔
204
                ListOptions: github.ListOptions{
4✔
205
                        Page:    pageNumber,
4✔
206
                        PerPage: itemsPerPage,
4✔
207
                },
4✔
208
        }
4✔
209
        // create a slice to hold the containers
4✔
210
        var allContainers []*github.Package
4✔
211

4✔
212
        if c.packageListingClient == nil {
5✔
213
                zerolog.Ctx(ctx).Error().Msg("No client available for listing packages")
1✔
214
                return allContainers, ErrNoPackageListingClient
1✔
215
        }
1✔
216

217
        type listPackagesRespWrapper struct {
3✔
218
                artifacts []*github.Package
3✔
219
                resp      *github.Response
3✔
220
        }
3✔
221
        op := func() (listPackagesRespWrapper, error) {
6✔
222
                var artifacts []*github.Package
3✔
223
                var resp *github.Response
3✔
224
                var err error
3✔
225

3✔
226
                if c.IsOrg() {
6✔
227
                        artifacts, resp, err = c.packageListingClient.Organizations.ListPackages(ctx, owner, opt)
3✔
228
                } else {
3✔
229
                        artifacts, resp, err = c.packageListingClient.Users.ListPackages(ctx, owner, opt)
×
230
                }
×
231

232
                listPackagesResp := listPackagesRespWrapper{
3✔
233
                        artifacts: artifacts,
3✔
234
                        resp:      resp,
3✔
235
                }
3✔
236

3✔
237
                if isRateLimitError(err) {
3✔
238
                        waitErr := c.waitForRateLimitReset(ctx, err)
×
239
                        if waitErr == nil {
×
240
                                return listPackagesResp, err
×
241
                        }
×
242
                        return listPackagesResp, backoffv4.Permanent(err)
×
243
                }
244

245
                return listPackagesResp, backoffv4.Permanent(err)
3✔
246
        }
247

248
        for {
6✔
249
                result, err := performWithRetry(ctx, op)
3✔
250
                if err != nil {
3✔
251
                        if result.resp != nil && result.resp.StatusCode == http.StatusNotFound {
×
252
                                return allContainers, fmt.Errorf("packages not found for repository %d: %w", repositoryId, ErrNotFound)
×
253
                        }
×
254

255
                        return allContainers, err
×
256
                }
257

258
                // now just append the ones belonging to the repository
259
                for _, artifact := range result.artifacts {
7✔
260
                        if artifact.Repository.GetID() == repositoryId {
7✔
261
                                allContainers = append(allContainers, artifact)
3✔
262
                        }
3✔
263
                }
264

265
                if result.resp.NextPage == 0 {
6✔
266
                        break
3✔
267
                }
268
                opt.Page = result.resp.NextPage
×
269
        }
270

271
        return allContainers, nil
3✔
272
}
273

274
// getPackageVersions returns a list of all package versions for the authenticated user or org
275
func (c *GitHub) getPackageVersions(ctx context.Context, owner string, package_type string, package_name string,
276
) ([]*github.PackageVersion, error) {
4✔
277
        state := "active"
4✔
278

4✔
279
        // since the GH API sometimes returns container and sometimes CONTAINER as the type, let's just lowercase it
4✔
280
        package_type = strings.ToLower(package_type)
4✔
281

4✔
282
        opt := &github.PackageListOptions{
4✔
283
                PackageType: &package_type,
4✔
284
                State:       &state,
4✔
285
                ListOptions: github.ListOptions{
4✔
286
                        Page:    1,
4✔
287
                        PerPage: 100,
4✔
288
                },
4✔
289
        }
4✔
290

4✔
291
        // create a slice to hold the versions
4✔
292
        var allVersions []*github.PackageVersion
4✔
293

4✔
294
        // loop until we get all package versions
4✔
295
        for {
8✔
296
                var v []*github.PackageVersion
4✔
297
                var resp *github.Response
4✔
298
                var err error
4✔
299
                if c.IsOrg() {
8✔
300
                        v, resp, err = c.client.Organizations.PackageGetAllVersions(ctx, owner, package_type, package_name, opt)
4✔
301
                } else {
4✔
302
                        package_name = url.PathEscape(package_name)
×
303
                        v, resp, err = c.client.Users.PackageGetAllVersions(ctx, owner, package_type, package_name, opt)
×
304
                }
×
305
                if err != nil {
5✔
306
                        return nil, err
1✔
307
                }
1✔
308

309
                // append to the slice
310
                allVersions = append(allVersions, v...)
3✔
311

3✔
312
                // if there is no next page, break
3✔
313
                if resp.NextPage == 0 {
6✔
314
                        break
3✔
315
                }
316

317
                // update the page
318
                opt.Page = resp.NextPage
×
319
        }
320

321
        // return the slice
322
        return allVersions, nil
3✔
323
}
324

325
// GetPackageByName returns a single package for the authenticated user or for the org
326
func (c *GitHub) GetPackageByName(ctx context.Context, owner string, package_type string, package_name string,
327
) (*github.Package, error) {
2✔
328
        var pkg *github.Package
2✔
329
        var err error
2✔
330

2✔
331
        // since the GH API sometimes returns container and sometimes CONTAINER as the type, let's just lowercase it
2✔
332
        package_type = strings.ToLower(package_type)
2✔
333

2✔
334
        if c.IsOrg() {
4✔
335
                pkg, _, err = c.client.Organizations.GetPackage(ctx, owner, package_type, package_name)
2✔
336
                if err != nil {
2✔
337
                        return nil, err
×
338
                }
×
339
        } else {
×
340
                pkg, _, err = c.client.Users.GetPackage(ctx, "", package_type, package_name)
×
341
                if err != nil {
×
342
                        return nil, err
×
343
                }
×
344
        }
345
        return pkg, nil
2✔
346
}
347

348
// GetPackageVersionById returns a single package version for the specific id
349
func (c *GitHub) GetPackageVersionById(ctx context.Context, owner string, packageType string, packageName string,
350
        version int64) (*github.PackageVersion, error) {
2✔
351
        var pkgVersion *github.PackageVersion
2✔
352
        var err error
2✔
353

2✔
354
        if c.IsOrg() {
4✔
355
                pkgVersion, _, err = c.client.Organizations.PackageGetVersion(ctx, owner, packageType, packageName, version)
2✔
356
                if err != nil {
2✔
357
                        return nil, err
×
358
                }
×
359
        } else {
×
360
                packageName = url.PathEscape(packageName)
×
361
                pkgVersion, _, err = c.client.Users.PackageGetVersion(ctx, owner, packageType, packageName, version)
×
362
                if err != nil {
×
363
                        return nil, err
×
364
                }
×
365
        }
366

367
        return pkgVersion, nil
2✔
368
}
369

370
// GetPullRequest is a wrapper for the GitHub API to get a pull request
371
func (c *GitHub) GetPullRequest(
372
        ctx context.Context,
373
        owner string,
374
        repo string,
375
        number int,
376
) (*github.PullRequest, error) {
×
377
        pr, _, err := c.client.PullRequests.Get(ctx, owner, repo, number)
×
378
        if err != nil {
×
379
                return nil, err
×
380
        }
×
381
        return pr, nil
×
382
}
383

384
// ListFiles is a wrapper for the GitHub API to list files in a pull request
385
func (c *GitHub) ListFiles(
386
        ctx context.Context,
387
        owner string,
388
        repo string,
389
        prNumber int,
390
        perPage int,
391
        pageNumber int,
392
) ([]*github.CommitFile, *github.Response, error) {
3✔
393
        type listFilesRespWrapper struct {
3✔
394
                files []*github.CommitFile
3✔
395
                resp  *github.Response
3✔
396
        }
3✔
397

3✔
398
        op := func() (listFilesRespWrapper, error) {
7✔
399
                opt := &github.ListOptions{
4✔
400
                        Page:    pageNumber,
4✔
401
                        PerPage: perPage,
4✔
402
                }
4✔
403
                files, resp, err := c.client.PullRequests.ListFiles(ctx, owner, repo, prNumber, opt)
4✔
404

4✔
405
                listFileResp := listFilesRespWrapper{
4✔
406
                        files: files,
4✔
407
                        resp:  resp,
4✔
408
                }
4✔
409

4✔
410
                if isRateLimitError(err) {
5✔
411
                        waitErr := c.waitForRateLimitReset(ctx, err)
1✔
412
                        if waitErr == nil {
2✔
413
                                return listFileResp, err
1✔
414
                        }
1✔
415
                        return listFileResp, backoffv4.Permanent(err)
×
416
                }
417

418
                return listFileResp, backoffv4.Permanent(err)
3✔
419
        }
420

421
        resp, err := performWithRetry(ctx, op)
3✔
422
        return resp.files, resp.resp, err
3✔
423
}
424

425
// ListPullRequestCommits is a wrapper for the GitHub API to list commits in a pull request.
426
func (c *GitHub) ListPullRequestCommits(
427
        ctx context.Context,
428
        owner string,
429
        repo string,
430
        prNumber int,
431
        perPage int,
432
        pageNumber int,
NEW
433
) ([]*github.RepositoryCommit, *github.Response, error) {
×
NEW
434
        type listPullRequestCommitsRespWrapper struct {
×
NEW
435
                commits []*github.RepositoryCommit
×
NEW
436
                resp    *github.Response
×
NEW
437
        }
×
NEW
438

×
NEW
439
        op := func() (listPullRequestCommitsRespWrapper, error) {
×
NEW
440
                opt := &github.ListOptions{
×
NEW
441
                        Page:    pageNumber,
×
NEW
442
                        PerPage: perPage,
×
NEW
443
                }
×
NEW
444
                commits, resp, err := c.client.PullRequests.ListCommits(ctx, owner, repo, prNumber, opt)
×
NEW
445

×
NEW
446
                listCommitsResp := listPullRequestCommitsRespWrapper{
×
NEW
447
                        commits: commits,
×
NEW
448
                        resp:    resp,
×
NEW
449
                }
×
NEW
450

×
NEW
451
                if isRateLimitError(err) {
×
NEW
452
                        waitErr := c.waitForRateLimitReset(ctx, err)
×
NEW
453
                        if waitErr == nil {
×
NEW
454
                                return listCommitsResp, err
×
NEW
455
                        }
×
NEW
456
                        return listCommitsResp, backoffv4.Permanent(err)
×
457
                }
458

NEW
459
                return listCommitsResp, backoffv4.Permanent(err)
×
460
        }
461

NEW
462
        resp, err := performWithRetry(ctx, op)
×
NEW
463
        return resp.commits, resp.resp, err
×
464
}
465

466
// CreateReview is a wrapper for the GitHub API to create a review
467
func (c *GitHub) CreateReview(
468
        ctx context.Context, owner, repo string, number int, reviewRequest *github.PullRequestReviewRequest,
469
) (*github.PullRequestReview, error) {
×
470
        review, _, err := c.client.PullRequests.CreateReview(ctx, owner, repo, number, reviewRequest)
×
471
        if err != nil {
×
472
                return nil, fmt.Errorf("error creating review: %w", err)
×
473
        }
×
474
        return review, nil
×
475
}
476

477
// UpdateReview is a wrapper for the GitHub API to update a review
478
func (c *GitHub) UpdateReview(
479
        ctx context.Context, owner, repo string, number int, reviewId int64, body string,
480
) (*github.PullRequestReview, error) {
×
481
        review, _, err := c.client.PullRequests.UpdateReview(ctx, owner, repo, number, reviewId, body)
×
482
        if err != nil {
×
483
                return nil, fmt.Errorf("error updating review: %w", err)
×
484
        }
×
485
        return review, nil
×
486
}
487

488
// ListIssueComments is a wrapper for the GitHub API to get all comments in a review
489
func (c *GitHub) ListIssueComments(
490
        ctx context.Context, owner, repo string, number int, opts *github.IssueListCommentsOptions,
491
) ([]*github.IssueComment, error) {
×
492
        comments, _, err := c.client.Issues.ListComments(ctx, owner, repo, number, opts)
×
493
        if err != nil {
×
494
                return nil, fmt.Errorf("error getting list of comments: %w", err)
×
495
        }
×
496
        return comments, nil
×
497
}
498

499
// ListReviews is a wrapper for the GitHub API to list reviews
500
func (c *GitHub) ListReviews(
501
        ctx context.Context,
502
        owner, repo string,
503
        number int,
504
        opt *github.ListOptions,
505
) ([]*github.PullRequestReview, error) {
×
506
        reviews, _, err := c.client.PullRequests.ListReviews(ctx, owner, repo, number, opt)
×
507
        if err != nil {
×
508
                return nil, fmt.Errorf("error listing reviews for PR %s/%s/%d: %w", owner, repo, number, err)
×
509
        }
×
510
        return reviews, nil
×
511
}
512

513
// DismissReview is a wrapper for the GitHub API to dismiss a review
514
func (c *GitHub) DismissReview(
515
        ctx context.Context,
516
        owner, repo string,
517
        prId int,
518
        reviewId int64,
519
        dismissalRequest *github.PullRequestReviewDismissalRequest,
520
) (*github.PullRequestReview, error) {
×
521
        review, _, err := c.client.PullRequests.DismissReview(ctx, owner, repo, prId, reviewId, dismissalRequest)
×
522
        if err != nil {
×
523
                return nil, fmt.Errorf("error dismissing review %d for PR %s/%s/%d: %w", reviewId, owner, repo, prId, err)
×
524
        }
×
525
        return review, nil
×
526
}
527

528
// SetCommitStatus is a wrapper for the GitHub API to set a commit status
529
func (c *GitHub) SetCommitStatus(
530
        ctx context.Context, owner, repo, ref string, status *github.RepoStatus,
531
) (*github.RepoStatus, error) {
×
532
        status, _, err := c.client.Repositories.CreateStatus(ctx, owner, repo, ref, status)
×
533
        if err != nil {
×
534
                return nil, fmt.Errorf("error creating commit status: %w", err)
×
535
        }
×
536
        return status, nil
×
537
}
538

539
// GetRepository returns a single repository for the authenticated user
540
func (c *GitHub) GetRepository(ctx context.Context, owner string, name string) (*github.Repository, error) {
×
541
        // create a slice to hold the repositories
×
542
        repo, _, err := c.client.Repositories.Get(ctx, owner, name)
×
543
        if err != nil {
×
544
                return nil, fmt.Errorf("error getting repository: %w", err)
×
545
        }
×
546

547
        return repo, nil
×
548
}
549

550
// GetBranchProtection returns the branch protection for a given branch
551
func (c *GitHub) GetBranchProtection(ctx context.Context, owner string,
552
        repo_name string, branch_name string) (*github.Protection, error) {
×
553
        var respErr *github.ErrorResponse
×
554
        if branch_name == "" {
×
555
                return nil, ErrBranchNameEmpty
×
556
        }
×
557

558
        protection, _, err := c.client.Repositories.GetBranchProtection(ctx, owner, repo_name, branch_name)
×
559
        if errors.As(err, &respErr) {
×
560
                if respErr.Message == githubBranchNotFoundMsg {
×
561
                        return nil, ErrBranchNotFound
×
562
                }
×
563

564
                return nil, fmt.Errorf("error getting branch protection: %w", err)
×
565
        } else if err != nil {
×
566
                return nil, err
×
567
        }
×
568
        return protection, nil
×
569
}
570

571
// UpdateBranchProtection updates the branch protection for a given branch
572
func (c *GitHub) UpdateBranchProtection(
573
        ctx context.Context, owner, repo, branch string, preq *github.ProtectionRequest,
574
) error {
×
575
        if branch == "" {
×
576
                return ErrBranchNameEmpty
×
577
        }
×
578
        _, _, err := c.client.Repositories.UpdateBranchProtection(ctx, owner, repo, branch, preq)
×
579
        return err
×
580
}
581

582
// GetBaseURL returns the base URL for the REST API.
583
func (c *GitHub) GetBaseURL() string {
1✔
584
        return c.client.BaseURL.String()
1✔
585
}
1✔
586

587
// NewRequest creates an API request. A relative URL can be provided in urlStr,
588
// which will be resolved to the BaseURL of the Client. Relative URLS should
589
// always be specified without a preceding slash. If specified, the value
590
// pointed to by body is JSON encoded and included as the request body.
591
func (c *GitHub) NewRequest(method, requestUrl string, body any) (*http.Request, error) {
9✔
592
        return c.client.NewRequest(method, requestUrl, body)
9✔
593
}
9✔
594

595
// Do sends an API request and returns the API response.
596
func (c *GitHub) Do(ctx context.Context, req *http.Request) (*http.Response, error) {
9✔
597
        var buf bytes.Buffer
9✔
598

9✔
599
        // The GitHub client closes the response body, so we need to capture it
9✔
600
        // in a buffer so that we can return it to the caller
9✔
601
        resp, err := c.client.Do(ctx, req, &buf)
9✔
602
        if err != nil && resp == nil {
9✔
603
                return nil, err
×
604
        }
×
605

606
        if resp.Response != nil {
18✔
607
                resp.Body = io.NopCloser(&buf)
9✔
608
        }
9✔
609
        return resp.Response, err
9✔
610
}
611

612
// GetCredential returns the credential used to authenticate with the GitHub API
613
func (c *GitHub) GetCredential() provifv1.GitHubCredential {
×
614
        return c.delegate.GetCredential()
×
615
}
×
616

617
// IsOrg returns true if the owner is an organization
618
func (c *GitHub) IsOrg() bool {
11✔
619
        return c.delegate.IsOrg()
11✔
620
}
11✔
621

622
// ListHooks lists all Hooks for the specified repository.
623
func (c *GitHub) ListHooks(ctx context.Context, owner, repo string) ([]*github.Hook, error) {
×
624
        list, resp, err := c.client.Repositories.ListHooks(ctx, owner, repo, nil)
×
625
        if err != nil && resp != nil && resp.StatusCode == http.StatusNotFound {
×
626
                // return empty list so that the caller can ignore the error and iterate over the empty list
×
627
                return []*github.Hook{}, fmt.Errorf("hooks not found for repository %s/%s: %w", owner, repo, ErrNotFound)
×
628
        }
×
629
        return list, err
×
630
}
631

632
// DeleteHook deletes a specified Hook.
633
func (c *GitHub) DeleteHook(ctx context.Context, owner, repo string, id int64) error {
×
634
        resp, err := c.client.Repositories.DeleteHook(ctx, owner, repo, id)
×
635
        if isRateLimitError(err) {
×
636
                return c.waitForRateLimitReset(ctx, err)
×
637
        }
×
638
        if resp != nil && (resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden) {
×
639
                // If the hook is not found, we can ignore the
×
640
                // error, user might have deleted it manually.
×
641
                // We also ignore deleting webhooks that we're not
×
642
                // allowed to touch. This is usually the case
×
643
                // with repository transfer.
×
644
                return nil
×
645
        }
×
646
        return err
×
647
}
648

649
// CreateHook creates a new Hook.
650
func (c *GitHub) CreateHook(ctx context.Context, owner, repo string, hook *github.Hook) (*github.Hook, error) {
4✔
651
        h, _, err := c.client.Repositories.CreateHook(ctx, owner, repo, hook)
4✔
652
        if isRateLimitError(err) {
5✔
653
                if waitErr := c.waitForRateLimitReset(ctx, err); waitErr != nil {
2✔
654
                        return nil, waitErr
1✔
655
                }
1✔
656
        }
657
        return h, err
3✔
658
}
659

660
// EditHook edits an existing Hook.
661
func (c *GitHub) EditHook(ctx context.Context, owner, repo string, id int64, hook *github.Hook) (*github.Hook, error) {
×
662
        h, _, err := c.client.Repositories.EditHook(ctx, owner, repo, id, hook)
×
663
        if isRateLimitError(err) {
×
664
                if waitErr := c.waitForRateLimitReset(ctx, err); waitErr != nil {
×
665
                        return nil, waitErr
×
666
                }
×
667
        }
668
        return h, err
×
669
}
670

671
// CreateSecurityAdvisory creates a new security advisory
672
func (c *GitHub) CreateSecurityAdvisory(ctx context.Context, owner, repo, severity, summary, description string,
673
        v []*github.AdvisoryVulnerability) (string, error) {
3✔
674
        u := fmt.Sprintf("repos/%v/%v/security-advisories", owner, repo)
3✔
675

3✔
676
        payload := &struct {
3✔
677
                Summary         string                          `json:"summary"`
3✔
678
                Description     string                          `json:"description"`
3✔
679
                Severity        string                          `json:"severity"`
3✔
680
                Vulnerabilities []*github.AdvisoryVulnerability `json:"vulnerabilities"`
3✔
681
        }{
3✔
682
                Summary:         summary,
3✔
683
                Description:     description,
3✔
684
                Severity:        severity,
3✔
685
                Vulnerabilities: v,
3✔
686
        }
3✔
687
        req, err := c.client.NewRequest("POST", u, payload)
3✔
688
        if err != nil {
3✔
689
                return "", err
×
690
        }
×
691

692
        res := &struct {
3✔
693
                ID string `json:"ghsa_id"`
3✔
694
        }{}
3✔
695

3✔
696
        resp, err := c.client.Do(ctx, req, res)
3✔
697
        if err != nil {
5✔
698
                return "", err
2✔
699
        }
2✔
700

701
        if resp.StatusCode != http.StatusCreated {
1✔
702
                return "", fmt.Errorf("error creating security advisory: %v", resp.Status)
×
703
        }
×
704
        return res.ID, nil
1✔
705
}
706

707
// CloseSecurityAdvisory closes a security advisory
708
func (c *GitHub) CloseSecurityAdvisory(ctx context.Context, owner, repo, id string) error {
4✔
709
        u := fmt.Sprintf("repos/%v/%v/security-advisories/%v", owner, repo, id)
4✔
710

4✔
711
        payload := &struct {
4✔
712
                State string `json:"state"`
4✔
713
        }{
4✔
714
                State: "closed",
4✔
715
        }
4✔
716

4✔
717
        req, err := c.client.NewRequest("PATCH", u, payload)
4✔
718
        if err != nil {
4✔
719
                return err
×
720
        }
×
721

722
        resp, err := c.client.Do(ctx, req, nil)
4✔
723
        if err != nil {
7✔
724
                return err
3✔
725
        }
3✔
726
        // Translate the HTTP status code to an error, nil if between 200 and 299
727
        return engerrors.HTTPErrorCodeToErr(resp.StatusCode)
1✔
728
}
729

730
// CreatePullRequest creates a pull request in a repository.
731
func (c *GitHub) CreatePullRequest(
732
        ctx context.Context,
733
        owner, repo, title, body, head, base string,
734
) (*github.PullRequest, error) {
×
735
        pr, _, err := c.client.PullRequests.Create(ctx, owner, repo, &github.NewPullRequest{
×
736
                Title:               github.String(title),
×
737
                Body:                github.String(body),
×
738
                Head:                github.String(head),
×
739
                Base:                github.String(base),
×
740
                MaintainerCanModify: github.Bool(true),
×
741
        })
×
742
        if err != nil {
×
743
                return nil, err
×
744
        }
×
745

746
        return pr, nil
×
747
}
748

749
// ClosePullRequest closes a pull request in a repository.
750
func (c *GitHub) ClosePullRequest(ctx context.Context, owner, repo string, number int) (*github.PullRequest, error) {
×
751
        pr, _, err := c.client.PullRequests.Edit(ctx, owner, repo, number, &github.PullRequest{
×
752
                State: github.String("closed"),
×
753
        })
×
754
        if err != nil {
×
755
                return nil, err
×
756
        }
×
757
        return pr, nil
×
758
}
759

760
// ListPullRequests lists all pull requests in a repository.
761
func (c *GitHub) ListPullRequests(
762
        ctx context.Context,
763
        owner, repo string,
764
        opt *github.PullRequestListOptions,
765
) ([]*github.PullRequest, error) {
×
766
        prs, _, err := c.client.PullRequests.List(ctx, owner, repo, opt)
×
767
        if err != nil {
×
768
                return nil, err
×
769
        }
×
770

771
        return prs, nil
×
772
}
773

774
// CreateIssueComment creates a comment on a pull request or an issue
775
func (c *GitHub) CreateIssueComment(
776
        ctx context.Context, owner, repo string, number int, comment string,
777
) (*github.IssueComment, error) {
14✔
778
        var issueComment *github.IssueComment
14✔
779

14✔
780
        op := func() (any, error) {
30✔
781
                var err error
16✔
782

16✔
783
                issueComment, _, err = c.client.Issues.CreateComment(ctx, owner, repo, number, &github.IssueComment{
16✔
784
                        Body: &comment,
16✔
785
                })
16✔
786

16✔
787
                if isRateLimitError(err) {
30✔
788
                        waitWrr := c.waitForRateLimitReset(ctx, err)
14✔
789
                        if waitWrr == nil {
16✔
790
                                return nil, err
2✔
791
                        }
2✔
792
                        return nil, backoffv4.Permanent(err)
12✔
793
                }
794

795
                return nil, backoffv4.Permanent(err)
2✔
796
        }
797
        _, retryErr := performWithRetry(ctx, op)
14✔
798
        return issueComment, retryErr
14✔
799
}
800

801
// UpdateIssueComment updates a comment on a pull request or an issue
802
func (c *GitHub) UpdateIssueComment(ctx context.Context, owner, repo string, number int64, comment string) error {
×
803
        _, _, err := c.client.Issues.EditComment(ctx, owner, repo, number, &github.IssueComment{
×
804
                Body: &comment,
×
805
        })
×
806
        return err
×
807
}
×
808

809
// Clone clones a GitHub repository
810
func (c *GitHub) Clone(ctx context.Context, cloneUrl string, branch string) (*git.Repository, error) {
×
811
        delegator := gitclient.NewGit(c.delegate.GetCredential(), gitclient.WithConfig(c.gitConfig))
×
812
        return delegator.Clone(ctx, cloneUrl, branch)
×
813
}
×
814

815
// AddAuthToPushOptions adds authorization to the push options
816
func (c *GitHub) AddAuthToPushOptions(ctx context.Context, pushOptions *git.PushOptions) error {
×
817
        login, err := c.delegate.GetLogin(ctx)
×
818
        if err != nil {
×
819
                return fmt.Errorf("cannot get login: %w", err)
×
820
        }
×
821
        c.delegate.GetCredential().AddToPushOptions(pushOptions, login)
×
822
        return nil
×
823
}
824

825
// ListAllRepositories lists all repositories the credential has access to
826
func (c *GitHub) ListAllRepositories(ctx context.Context) ([]*minderv1.Repository, error) {
3✔
827
        return c.delegate.ListAllRepositories(ctx)
3✔
828
}
3✔
829

830
// GetUserId returns the user id for the acting user
831
func (c *GitHub) GetUserId(ctx context.Context) (int64, error) {
1✔
832
        return c.delegate.GetUserId(ctx)
1✔
833
}
1✔
834

835
// GetName returns the username for the acting user
836
func (c *GitHub) GetName(ctx context.Context) (string, error) {
1✔
837
        return c.delegate.GetName(ctx)
1✔
838
}
1✔
839

840
// GetLogin returns the login for the acting user
841
func (c *GitHub) GetLogin(ctx context.Context) (string, error) {
1✔
842
        return c.delegate.GetLogin(ctx)
1✔
843
}
1✔
844

845
// GetPrimaryEmail returns the primary email for the acting user
846
func (c *GitHub) GetPrimaryEmail(ctx context.Context) (string, error) {
1✔
847
        return c.delegate.GetPrimaryEmail(ctx)
1✔
848
}
1✔
849

850
// ListImages lists all containers in the GitHub Container Registry
851
func (c *GitHub) ListImages(ctx context.Context) ([]string, error) {
×
852
        return c.ghcrwrap.ListImages(ctx)
×
853
}
×
854

855
// GetNamespaceURL returns the URL for the repository
856
func (c *GitHub) GetNamespaceURL() string {
×
857
        return c.ghcrwrap.GetNamespaceURL()
×
858
}
×
859

860
// GetArtifactVersions returns a list of all versions for a specific artifact
861
func (gv *GitHub) GetArtifactVersions(
862
        ctx context.Context, artifact *minderv1.Artifact,
863
        filter provifv1.GetArtifactVersionsFilter,
864
) ([]*minderv1.ArtifactVersion, error) {
2✔
865
        // We don't need to URL-encode the artifact name
2✔
866
        // since this already happens in go-github
2✔
867
        upstreamVersions, err := gv.getPackageVersions(
2✔
868
                ctx, artifact.GetOwner(), artifact.GetTypeLower(), artifact.GetName(),
2✔
869
        )
2✔
870
        if err != nil {
3✔
871
                return nil, fmt.Errorf("error retrieving artifact versions: %w", err)
1✔
872
        }
1✔
873

874
        out := make([]*minderv1.ArtifactVersion, 0, len(upstreamVersions))
1✔
875
        for _, uv := range upstreamVersions {
2✔
876
                tags := uv.Metadata.Container.Tags
1✔
877

1✔
878
                if err := filter.IsSkippable(uv.CreatedAt.Time, tags); err != nil {
1✔
879
                        zerolog.Ctx(ctx).Debug().Str("name", artifact.GetName()).Strs("tags", tags).
×
880
                                Str("reason", err.Error()).Msg("skipping artifact version")
×
881
                        continue
×
882
                }
883

884
                sort.Strings(tags)
1✔
885

1✔
886
                // only the tags and creation time is relevant to us.
1✔
887
                out = append(out, &minderv1.ArtifactVersion{
1✔
888
                        Tags: tags,
1✔
889
                        // NOTE: GitHub's name is actually a SHA. This is misleading...
1✔
890
                        // but it is what it is. We'll use it as the SHA for now.
1✔
891
                        Sha:       *uv.Name,
1✔
892
                        CreatedAt: timestamppb.New(uv.CreatedAt.Time),
1✔
893
                })
1✔
894
        }
895

896
        return out, nil
1✔
897
}
898

899
// setAsRateLimited adds the GitHub to the cache as rate limited.
900
// An optimistic concurrency control mechanism is used to ensure that every request doesn't need
901
// synchronization. GitHub only adds itself to the cache if it's not already there. It doesn't
902
// remove itself from the cache when the rate limit is reset. This approach leverages the high
903
// likelihood of the client or token being rate-limited again. By keeping the client in the cache,
904
// we can reuse client's rateLimits map, which holds rate limits for different endpoints.
905
// This reuse of cached rate limits helps avoid unnecessary GitHub API requests when the client
906
// is rate-limited. Every cache entry has an expiration time, so the cache will eventually evict
907
// the rate-limited client.
908
func (c *GitHub) setAsRateLimited() {
19✔
909
        if c.cache != nil {
38✔
910
                c.cache.Set(c.delegate.GetOwner(), c.delegate.GetCredential().GetCacheKey(), db.ProviderTypeGithub, c)
19✔
911
        }
19✔
912
}
913

914
// waitForRateLimitReset waits for token wait limit to reset. Returns error if wait time is more
915
// than MaxRateLimitWait or requests' context is cancelled.
916
func (c *GitHub) waitForRateLimitReset(ctx context.Context, err error) error {
20✔
917
        var rateLimitError *github.RateLimitError
20✔
918
        if errors.As(err, &rateLimitError) {
38✔
919
                return c.processPrimaryRateLimitErr(ctx, rateLimitError)
18✔
920
        }
18✔
921

922
        var abuseRateLimitError *github.AbuseRateLimitError
2✔
923
        if errors.As(err, &abuseRateLimitError) {
3✔
924
                return c.processAbuseRateLimitErr(ctx, abuseRateLimitError)
1✔
925
        }
1✔
926

927
        return nil
1✔
928
}
929

930
func (c *GitHub) processPrimaryRateLimitErr(ctx context.Context, err *github.RateLimitError) error {
18✔
931
        logger := zerolog.Ctx(ctx)
18✔
932
        rate := err.Rate
18✔
933
        if rate.Remaining == 0 {
36✔
934
                c.setAsRateLimited()
18✔
935

18✔
936
                waitTime := DefaultRateLimitWaitTime
18✔
937
                resetTime := rate.Reset.Time
18✔
938
                if !resetTime.IsZero() {
36✔
939
                        waitTime = time.Until(resetTime)
18✔
940
                }
18✔
941

942
                logRateLimitError(logger, "RateLimitError", waitTime, c.delegate.GetOwner(), err.Response)
18✔
943

18✔
944
                if waitTime > MaxRateLimitWait {
32✔
945
                        logger.Debug().Msgf("rate limit reset time: %v exceeds maximum wait time: %v", waitTime, MaxRateLimitWait)
14✔
946
                        return engerrors.NewRateLimitError(err, int64(rate.Limit), int64(rate.Remaining), resetTime)
14✔
947
                }
14✔
948

949
                // Wait for the rate limit to reset
950
                select {
4✔
951
                case <-time.After(waitTime):
4✔
952
                        return nil
4✔
953
                case <-ctx.Done():
×
954
                        logger.Debug().Err(ctx.Err()).Msg("context done while waiting for rate limit to reset")
×
955
                        return engerrors.NewRateLimitError(err, int64(rate.Limit), int64(rate.Remaining), resetTime)
×
956
                }
957
        }
958

959
        return nil
×
960
}
961

962
func (c *GitHub) processAbuseRateLimitErr(ctx context.Context, err *github.AbuseRateLimitError) error {
1✔
963
        logger := zerolog.Ctx(ctx)
1✔
964
        c.setAsRateLimited()
1✔
965

1✔
966
        retryAfter := err.RetryAfter
1✔
967
        waitTime := DefaultRateLimitWaitTime
1✔
968
        if retryAfter != nil && *retryAfter > 0 {
2✔
969
                waitTime = *retryAfter
1✔
970
        }
1✔
971

972
        logRateLimitError(logger, "AbuseRateLimitError", waitTime, c.delegate.GetOwner(), err.Response)
1✔
973

1✔
974
        if waitTime > MaxRateLimitWait {
1✔
975
                logger.Debug().Msgf("abuse rate limit wait time: %v exceeds maximum wait time: %v", waitTime, MaxRateLimitWait)
×
976
                return engerrors.NewRateLimitError(err, 0, 0, time.Now().Add(waitTime))
×
977
        }
×
978

979
        // Wait for the rate limit to reset
980
        select {
1✔
981
        case <-time.After(waitTime):
1✔
982
                return nil
1✔
983
        case <-ctx.Done():
×
984
                logger.Debug().Err(ctx.Err()).Msg("context done while waiting for rate limit to reset")
×
985
                return engerrors.NewRateLimitError(err, 0, 0, time.Now().Add(waitTime))
×
986
        }
987
}
988

989
func logRateLimitError(logger *zerolog.Logger, errType string, waitTime time.Duration, owner string, resp *http.Response) {
19✔
990
        var method, path string
19✔
991
        if resp != nil && resp.Request != nil {
38✔
992
                method = resp.Request.Method
19✔
993
                path = resp.Request.URL.Path
19✔
994
        }
19✔
995

996
        event := logger.Debug().
19✔
997
                Str("owner", owner).
19✔
998
                Str("wait_time", waitTime.String()).
19✔
999
                Str("error_type", errType)
19✔
1000

19✔
1001
        if method != "" {
38✔
1002
                event = event.Str("method", method)
19✔
1003
        }
19✔
1004

1005
        if path != "" {
38✔
1006
                event = event.Str("path", path)
19✔
1007
        }
19✔
1008

1009
        event.Msg("rate limit exceeded")
19✔
1010
}
1011

1012
func performWithRetry[T any](ctx context.Context, op backoffv4.OperationWithData[T]) (T, error) {
23✔
1013
        exponentialBackOff := backoffv4.NewExponentialBackOff()
23✔
1014
        maxRetriesBackoff := backoffv4.WithMaxRetries(exponentialBackOff, MaxRateLimitRetries)
23✔
1015
        return backoffv4.RetryWithData(op, backoffv4.WithContext(maxRetriesBackoff, ctx))
23✔
1016
}
23✔
1017

1018
func isRateLimitError(err error) bool {
32✔
1019
        if _, ok := errors.AsType[*github.RateLimitError](err); ok {
48✔
1020
                return true
16✔
1021
        }
16✔
1022
        if _, ok := errors.AsType[*github.AbuseRateLimitError](err); ok {
16✔
1023
                return true
×
1024
        }
×
1025
        return false
16✔
1026
}
1027

1028
// IsMinderHook checks if a GitHub hook is a Minder hook
1029
func IsMinderHook(hook *github.Hook, hostURL string) (bool, error) {
4✔
1030
        configURL := hook.GetConfig().GetURL()
4✔
1031
        if configURL == "" {
5✔
1032
                return false, fmt.Errorf("unexpected hook config structure: %v", hook.Config)
1✔
1033
        }
1✔
1034
        parsedURL, err := url.Parse(configURL)
3✔
1035
        if err != nil {
4✔
1036
                return false, err
1✔
1037
        }
1✔
1038
        if parsedURL.Host == hostURL {
3✔
1039
                return true, nil
1✔
1040
        }
1✔
1041

1042
        return false, nil
1✔
1043
}
1044

1045
// CanHandleOwner checks if the GitHub provider has the right credentials to handle the owner
1046
func CanHandleOwner(_ context.Context, prov db.Provider, owner string) bool {
4✔
1047
        // TODO: this is fragile and does not handle organization renames, in the future we can make sure the credential
4✔
1048
        // has admin permissions on the owner
4✔
1049
        if prov.Name == fmt.Sprintf("%s-%s", db.ProviderClassGithubApp, owner) {
5✔
1050
                return true
1✔
1051
        }
1✔
1052
        if prov.Class == db.ProviderClassGithub {
4✔
1053
                return true
1✔
1054
        }
1✔
1055
        return false
2✔
1056
}
1057

1058
// NewFallbackTokenClient creates a new GitHub client that uses the GitHub App's fallback token
1059
func NewFallbackTokenClient(appConfig config.ProviderConfig) *github.Client {
3✔
1060
        if appConfig.GitHubApp == nil {
4✔
1061
                return nil
1✔
1062
        }
1✔
1063
        fallbackToken, err := appConfig.GitHubApp.GetFallbackToken()
2✔
1064
        if err != nil || fallbackToken == "" {
3✔
1065
                return nil
1✔
1066
        }
1✔
1067
        var packageListingClient *github.Client
1✔
1068

1✔
1069
        fallbackTokenSource := oauth2.StaticTokenSource(
1✔
1070
                &oauth2.Token{AccessToken: fallbackToken},
1✔
1071
        )
1✔
1072
        fallbackTokenTC := &http.Client{
1✔
1073
                Transport: &oauth2.Transport{
1✔
1074
                        Base:   http.DefaultClient.Transport,
1✔
1075
                        Source: fallbackTokenSource,
1✔
1076
                },
1✔
1077
        }
1✔
1078

1✔
1079
        packageListingClient = github.NewClient(fallbackTokenTC)
1✔
1080
        return packageListingClient
1✔
1081
}
1082

1083
// StartCheckRun calls the GitHub API to initialize a new check using the
1084
// supplied options.
1085
func (c *GitHub) StartCheckRun(
1086
        ctx context.Context, owner, repo string, opts *github.CreateCheckRunOptions,
1087
) (*github.CheckRun, error) {
4✔
1088
        if opts.StartedAt == nil {
7✔
1089
                opts.StartedAt = &github.Timestamp{Time: time.Now()}
3✔
1090
        }
3✔
1091

1092
        run, resp, err := c.client.Checks.CreateCheckRun(ctx, owner, repo, *opts)
4✔
1093
        if err != nil {
7✔
1094
                if isRateLimitError(err) {
3✔
1095
                        return nil, c.waitForRateLimitReset(ctx, err)
×
1096
                }
×
1097
                // If error is 403 then it means we are missing permissions
1098
                if resp != nil && resp.StatusCode == 403 {
4✔
1099
                        return nil, ErroNoCheckPermissions
1✔
1100
                }
1✔
1101
                return nil, fmt.Errorf("creating check: %w", err)
2✔
1102
        }
1103
        return run, nil
1✔
1104
}
1105

1106
// UpdateCheckRun updates an existing check run in GitHub. The check run is referenced
1107
// using its run ID. This function returns the updated CheckRun srtuct.
1108
func (c *GitHub) UpdateCheckRun(
1109
        ctx context.Context, owner, repo string, checkRunID int64, opts *github.UpdateCheckRunOptions,
1110
) (*github.CheckRun, error) {
3✔
1111
        run, resp, err := c.client.Checks.UpdateCheckRun(ctx, owner, repo, checkRunID, *opts)
3✔
1112
        if err != nil {
5✔
1113
                if isRateLimitError(err) {
2✔
1114
                        return nil, c.waitForRateLimitReset(ctx, err)
×
1115
                }
×
1116
                // If error is 403 then it means we are missing permissions
1117
                if resp != nil && resp.StatusCode == 403 {
3✔
1118
                        return nil, ErroNoCheckPermissions
1✔
1119
                }
1✔
1120
                return nil, fmt.Errorf("updating check: %w", err)
1✔
1121
        }
1122
        return run, nil
1✔
1123
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc