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

mindersec / minder / 24718498200

21 Apr 2026 10:54AM UTC coverage: 60.096%. First build
24718498200

Pull #6372

github

web-flow
Merge f94afb8fc into fef41377a
Pull Request #6372: feat(engine): add commit iteration support for pull request evaluation

9 of 70 new or added lines in 2 files covered. (12.86%)

20233 of 33668 relevant lines covered (60.1%)

35.92 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
// It is currently intended for internal engine experimentation, such as iterating over all
427
// commits in a PR during evaluation.
428
func (c *GitHub) ListPullRequestCommits(
429
        ctx context.Context,
430
        owner string,
431
        repo string,
432
        prNumber int,
433
        perPage int,
434
        pageNumber int,
NEW
435
) ([]*github.RepositoryCommit, *github.Response, error) {
×
NEW
436
        type listCommitsRespWrapper struct {
×
NEW
437
                commits []*github.RepositoryCommit
×
NEW
438
                resp    *github.Response
×
NEW
439
        }
×
NEW
440

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

×
NEW
448
                wrapped := listCommitsRespWrapper{
×
NEW
449
                        commits: commits,
×
NEW
450
                        resp:    resp,
×
NEW
451
                }
×
NEW
452

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

NEW
461
                return wrapped, backoffv4.Permanent(err)
×
462
        }
463

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

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

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

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

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

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

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

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

549
        return repo, nil
×
550
}
551

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

748
        return pr, nil
×
749
}
750

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

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

773
        return prs, nil
×
774
}
775

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

886
                sort.Strings(tags)
1✔
887

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

898
        return out, nil
1✔
899
}
900

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

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

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

929
        return nil
1✔
930
}
931

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

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

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

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

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

961
        return nil
×
962
}
963

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

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

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

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

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

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

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

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

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

1011
        event.Msg("rate limit exceeded")
19✔
1012
}
1013

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

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

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

1044
        return false, nil
1✔
1045
}
1046

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

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

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

1✔
1081
        packageListingClient = github.NewClient(fallbackTokenTC)
1✔
1082
        return packageListingClient
1✔
1083
}
1084

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

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

1108
// UpdateCheckRun updates an existing check run in GitHub. The check run is referenced
1109
// using its run ID. This function returns the updated CheckRun srtuct.
1110
func (c *GitHub) UpdateCheckRun(
1111
        ctx context.Context, owner, repo string, checkRunID int64, opts *github.UpdateCheckRunOptions,
1112
) (*github.CheckRun, error) {
3✔
1113
        run, resp, err := c.client.Checks.UpdateCheckRun(ctx, owner, repo, checkRunID, *opts)
3✔
1114
        if err != nil {
5✔
1115
                if isRateLimitError(err) {
2✔
1116
                        return nil, c.waitForRateLimitReset(ctx, err)
×
1117
                }
×
1118
                // If error is 403 then it means we are missing permissions
1119
                if resp != nil && resp.StatusCode == 403 {
3✔
1120
                        return nil, ErroNoCheckPermissions
1✔
1121
                }
1✔
1122
                return nil, fmt.Errorf("updating check: %w", err)
1✔
1123
        }
1124
        return run, nil
1✔
1125
}
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