-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathgithub.go
More file actions
488 lines (429 loc) · 15.6 KB
/
Copy pathgithub.go
File metadata and controls
488 lines (429 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
// SPDX-FileCopyrightText: Copyright 2025 The SLSA Authors
// SPDX-License-Identifier: Apache-2.0
package github
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"time"
"github.com/google/go-github/v69/github"
"github.com/slsa-framework/source-tool/pkg/attest"
"github.com/slsa-framework/source-tool/pkg/auth"
"github.com/slsa-framework/source-tool/pkg/ghcontrol"
"github.com/slsa-framework/source-tool/pkg/slsa"
"github.com/slsa-framework/source-tool/pkg/sourcetool/models"
)
// asUnsupportedPlanError inspects an error returned from the GitHub API and,
// when it is a 403 raised because the repository's plan does not include the
// requested feature (for example reading branch rulesets on a private repo on a
// free plan), returns models.ErrUnsupportedRepoPlan wrapping the original
// error. It returns nil if err is not that case so callers can fall through to
// their normal handling. The check is done on the typed *github.ErrorResponse
// rather than on the error string so it does not break if GitHub rewords the
// message.
func asUnsupportedPlanError(err error) error {
if err == nil {
return nil
}
var ghErr *github.ErrorResponse
if !errors.As(err, &ghErr) {
return nil
}
if ghErr.Response == nil || ghErr.Response.StatusCode != http.StatusForbidden {
return nil
}
return fmt.Errorf("%w: %w", models.ErrUnsupportedRepoPlan, err)
}
// InherentControls are the controls that are always true because we are
// in git and/org GitHub.
var InherentControls = slsa.ControlNameSet{
// GitHub uses git
slsa.SLSA_SOURCE_ORG_SCS,
// GitHub enforces access control
slsa.SLSA_SOURCE_ORG_ACCESS_CONTROL,
// There is no safe expunge in Git or GitHub but as long as users
// cannot force push, then things cannot be expunged. So I think
// it passes.
// slsa.SLSA_SOURCE_ORG_SAFE_EXPUNGE,
// All the org controls are default expect for expunge, so we tie
// org continuity to the branch continuity
// slsa.SLSA_SOURCE_ORG_CONTINUITY,
// GitHub gives you a repo id/uri
slsa.SLSA_SOURCE_SCS_REPO_ID,
// Git commit
slsa.SLSA_SOURCE_SCS_REVISION_ID,
// git diff
slsa.SLSA_SOURCE_SCS_DIFF_DISPLAY,
// We disable VSA until checking we have one
// slsa.SLSA_SOURCE_SCS_VSA,
// Git is change history
slsa.SLSA_SOURCE_SCS_HISTORY,
// We will compute continuity from the GH api
// slsa.SLSA_SOURCE_SCS_CONTINUITY,
// Both git and GitHub have user identities
slsa.SLSA_SOURCE_SCS_IDENTITY,
// We disable provenance until we check we have an attestation
// slsa.SLSA_SOURCE_SCS_PROVENANCE,
// This depends on branch protection
// slsa.SLSA_SOURCE_SCS_PROTECTED_REFS,
// We will check for two party review in the API
// slsa.SLSA_SOURCE_SCS_TWO_PARTY_REVIEW,
}
func New(options *models.BackendOptions) *Backend {
return &Backend{
authenticator: auth.New(),
Options: options,
}
}
type Options struct {
UseFork bool
}
// Backend implemets the GitHub sourcetool backend
type Backend struct {
authenticator *auth.Authenticator
Options *models.BackendOptions
}
// getGitHubConnection builds a github connector to a repository
func (b *Backend) getGitHubConnection(repository *models.Repository, ref string) (*ghcontrol.GitHubConnection, error) {
if repository == nil {
return nil, fmt.Errorf("unable to build GitHub connection, repository is nil")
}
if repository.Path == "" {
return nil, errors.New("repository path not set")
}
owner, name, err := repository.PathAsGitHubOwnerName()
if err != nil {
return nil, err
}
client, err := b.authenticator.GetGitHubClient()
if err != nil {
return nil, err
}
ghc := ghcontrol.NewGhConnectionWithClient(owner, name, ref, client)
ghc.Options.AllowMergeCommits = b.Options.AllowMergeCommits
return ghc, nil
}
func (b *Backend) GetBranchControls(ctx context.Context, branch *models.Branch) (*slsa.ControlSet, error) {
if branch.Repository == nil {
return nil, fmt.Errorf("branch has no repository")
}
// get latest commit
ghc, err := b.getGitHubConnection(branch.Repository, branch.FullRef())
if err != nil {
return nil, fmt.Errorf("getting github connection: %w", err)
}
// Get the latest commit from the branch
commit, err := ghc.GetLatestCommit(ctx, branch.FullRef())
if err != nil {
return nil, fmt.Errorf("fetching latest commit from %q: %w", branch.FullRef(), err)
}
return b.GetBranchControlsAtCommit(ctx, branch, &models.Commit{SHA: commit})
}
// GetBranchControlsAtCommit
func (b *Backend) GetBranchControlsAtCommit(ctx context.Context, branch *models.Branch, commit *models.Commit) (*slsa.ControlSet, error) {
if branch.Repository == nil {
return nil, fmt.Errorf("branch has no repository")
}
if commit == nil {
return nil, errors.New("commit is not set")
}
ghc, err := b.getGitHubConnection(branch.Repository, branch.FullRef())
if err != nil {
return nil, fmt.Errorf("getting github connection: %w", err)
}
// The branch controls returned from ghcontrol only include the 4
// legacy checks sourcetool did (continuity, review, RequiredChecks, tag hygiene)
activeControls, err := ghc.GetBranchControls(ctx, branch.FullRef())
if err != nil {
// Reading branch rules 403s on private repos that are on a free plan.
// Surface a typed, actionable error before anything else happens so the
// caller can warn the user instead of leaking the raw API message.
if planErr := asUnsupportedPlanError(err); planErr != nil {
return nil, planErr
}
return nil, fmt.Errorf("checking status: %w", err)
}
// We need to manually check for PROVENANCE_AVAILABLE which is not
// handled by ghcontrol
attester, err := attest.NewAttester(
attest.WithBackend(b), attest.WithVerifier(attest.GetDefaultVerifier()),
attest.WithAuthenticator(b.authenticator),
)
if err != nil {
return nil, err
}
// Fetch the attestation. If found, then add the control:
attestation, err := attester.GetRevisionProvenance(ctx, branch, commit)
if err != nil {
return nil, fmt.Errorf("attempting to read provenance from commit %q: %w", commit.SHA, err)
}
if attestation != nil {
// We carry over the since date from the previous attestation, only if
// it > 0 (unix origin)
var t *time.Time
if ctrl := attestation.GetControl(slsa.SLSA_SOURCE_SCS_PROVENANCE.String()); ctrl != nil {
if ctrl.GetSince() != nil && ctrl.GetSince().AsTime().Unix() != 0 {
rt := ctrl.GetSince().AsTime()
t = &rt
}
} else if ctrl := attestation.GetControl(slsa.DEPRECATED_ProvenanceAvailable.String()); ctrl != nil {
if ctrl.GetSince() != nil && ctrl.GetSince().AsTime().Unix() != 0 {
rt := ctrl.GetSince().AsTime()
t = &rt
}
}
if tc := activeControls.GetControl(slsa.SLSA_SOURCE_SCS_PROVENANCE); tc != nil {
if t != nil {
tc.Since = t
}
} else {
activeControls.AddControl(&slsa.Control{
Name: slsa.SLSA_SOURCE_SCS_PROVENANCE,
Since: t,
})
}
} else {
log.Printf("No provenance attestation found on %s", commit.SHA)
}
_, vsaPred, err := attester.GetRevisionVSA(ctx, branch, commit)
if err != nil {
return nil, fmt.Errorf("reading VSA: %w", err)
}
if vsaPred != nil {
if tc := activeControls.GetControl(slsa.SLSA_SOURCE_SCS_VSA); tc == nil {
activeControls.AddControl(&slsa.Control{
Name: slsa.SLSA_SOURCE_SCS_VSA,
})
}
} else {
log.Printf("No VSA found for commit")
}
// NewControlSet returns all the controls for the framework in
// StateNotEnabled.
status := slsa.NewControlSet()
sinceForever := time.Unix(1207836000, 0) // April 10, 2008 (when github came online)
for i, ctrl := range status.Controls {
// Check if it's an inherent control, turn it on and don't look back
if c := InherentControls.GetControl(slsa.ControlName(ctrl.Name.String())); c != "" {
status.Controls[i].Since = &sinceForever
status.Controls[i].State = slsa.StateActive
status.Controls[i].Message = "Inherent"
continue
}
// Check if it's one of the active controls and enable it and copy the since date
if c := activeControls.GetControl(ctrl.Name); c != nil {
status.Controls[i].Since = c.Since
status.Controls[i].State = slsa.StateActive
status.Controls[i].Message = b.controlImplementationMessage(c.GetName())
}
// Enable ORG_SAFE_EXPUNGE when branch protection (protected refs) is active.
// Without force push, content cannot be expunged.
if ctrl.Name == slsa.SLSA_SOURCE_ORG_SAFE_EXPUNGE {
if c := activeControls.GetControl(slsa.SLSA_SOURCE_SCS_PROTECTED_REFS); c != nil {
status.Controls[i].Since = c.Since
status.Controls[i].State = slsa.StateActive
status.Controls[i].Message = b.controlImplementationMessage(ctrl.Name)
}
}
// Enable ORG_CONTINUITY when SCS branch continuity is active.
if ctrl.Name == slsa.SLSA_SOURCE_ORG_CONTINUITY {
if c := activeControls.GetControl(slsa.SLSA_SOURCE_SCS_CONTINUITY); c != nil {
status.Controls[i].Since = c.Since
status.Controls[i].State = slsa.StateActive
status.Controls[i].Message = b.controlImplementationMessage(ctrl.Name)
}
}
}
// The only control which can be in in_progress state in GitHub is
// provenance generation when the PR is open but not merged. We check
// here and report back the status.
switchProvCtlToInProgress := false
var provenanceMessage string
if c := activeControls.GetControl(slsa.SLSA_SOURCE_SCS_PROVENANCE); c == nil {
pr, err := b.FindWorkflowPR(ctx, branch.Repository)
if err != nil {
return nil, fmt.Errorf("looking for provenance workflow pull request: %w", err)
}
// PR found, check is in progress
if pr != nil {
// ... but do it below to save finding the control
switchProvCtlToInProgress = true
provenanceMessage = fmt.Sprintf("(PR %s#%d waiting to merge)", pr.Repo.Path, pr.Number)
}
}
// Populate the recommended actions
for i := range status.Controls {
// Piggyback on this loop to switch the provenance status for efficiency
if switchProvCtlToInProgress && status.Controls[i].Name == slsa.SLSA_SOURCE_SCS_PROVENANCE {
status.Controls[i].State = slsa.StateInProgress
status.Controls[i].Message = provenanceMessage
}
action := b.getRecommendedAction(branch.Repository, branch, status.Controls[i].Name, status.Controls[i].State)
status.Controls[i].RecommendedAction = action
}
return status, nil
}
// controlImplementationMessage returns an implementation message to populate the
// status message when controls are active.
func (b *Backend) controlImplementationMessage(ctrlName slsa.ControlName) string {
//nolint:exhaustive
switch ctrlName {
case slsa.SLSA_SOURCE_SCS_PROVENANCE, slsa.DEPRECATED_ProvenanceAvailable:
return "Signed provenance metadata is being published on every commit"
case slsa.SLSA_SOURCE_SCS_PROTECTED_REFS, slsa.DEPRECATED_TagHygiene:
return "Tag protections are configured in the repository"
case slsa.DEPRECATED_ReviewEnforced:
return "Code review is enforced in the repository"
case slsa.SLSA_SOURCE_ORG_CONTINUITY, slsa.DEPRECATED_ContinuityEnforced:
return "Push and delete protection is enabled on the branch"
case slsa.PolicyAvailable:
return "The repository has published a policy"
default:
return ""
}
}
func (b *Backend) GetTagControls(ctx context.Context, branch *models.Branch, tag *models.Tag) (*slsa.ControlSet, error) {
if tag.Commit == nil || tag.Commit.SHA == "" {
return nil, errors.New("tag commit is empty")
}
return b.GetBranchControlsAtCommit(ctx, branch, tag.Commit)
}
func (b *Backend) ControlConfigurationDescr(branch *models.Branch, config models.ControlConfiguration) string {
repo := branch.Repository
if repo == nil {
repo = &models.Repository{
// this is an invalid path but it is just a default used to
// construct English sentences below:
Path: "your repository",
}
}
switch config {
case models.CONFIG_BRANCH_RULES:
return fmt.Sprintf(
"Enable push and delete protection on %s for branch %s",
repo.Path, branch.Name,
)
case models.CONFIG_GEN_PROVENANCE:
return fmt.Sprintf(
"Open a pull request on %s to add the provenance generation workflow",
repo.Path,
)
case models.CONFIG_POLICY:
return fmt.Sprintf(
"Open a pull request on the SLSA policy repo to check-in %s SLSA source policy",
repo.Path,
)
case models.CONFIG_TAG_RULES:
return fmt.Sprintf(
"Enable force push/update/delete protection for all tags in %s",
repo.Path,
)
default:
return ""
}
}
// GetLatestCommit returns the latest commit from a branch
func (b *Backend) GetLatestCommit(ctx context.Context, r *models.Repository, branch *models.Branch) (*models.Commit, error) {
gcx, err := b.getGitHubConnection(r, branch.FullRef())
if err != nil {
return nil, fmt.Errorf("building GitHub connector: %w", err)
}
sha, err := gcx.GetLatestCommit(ctx, branch.FullRef())
if err != nil {
return nil, fmt.Errorf("reading latest commit: %w", err)
}
return &models.Commit{SHA: sha}, nil
}
// GetRecommendedAction returns the recommended action based on the
// status of a SLSA control
func (b *Backend) getRecommendedAction(r *models.Repository, _ *models.Branch, control slsa.ControlName, state slsa.ControlState) *slsa.ControlRecommendedAction {
//nolint:exhaustive // Not all drivers handle all controls
switch control {
case slsa.DEPRECATED_ProvenanceAvailable:
switch state {
case slsa.StateInProgress:
return &slsa.ControlRecommendedAction{
Message: "Wait for provenance generator pull request to merge",
}
case slsa.StateNotEnabled:
return &slsa.ControlRecommendedAction{
Message: "Start generating provenance",
Command: fmt.Sprintf("sourcetool setup controls --config=%s %s", models.CONFIG_GEN_PROVENANCE, r.Path),
}
default:
return nil
}
case slsa.SLSA_SOURCE_ORG_CONTINUITY, slsa.DEPRECATED_ContinuityEnforced:
if state == slsa.StateNotEnabled {
return &slsa.ControlRecommendedAction{
Message: "Enable branch push/delete protection",
Command: fmt.Sprintf("sourcetool setup controls --config=%s %s", models.CONFIG_BRANCH_RULES, r.Path),
}
}
return nil
case slsa.SLSA_SOURCE_SCS_PROTECTED_REFS, slsa.DEPRECATED_TagHygiene:
if state == slsa.StateNotEnabled {
return &slsa.ControlRecommendedAction{
Message: "Enable tag push/update/delete protection",
Command: fmt.Sprintf("sourcetool setup controls --config=%s %s", models.CONFIG_TAG_RULES, r.Path),
}
}
return nil
default:
return nil
}
}
// GetPreviousCommit takes a commit in
func (b *Backend) GetPreviousCommit(ctx context.Context, branch *models.Branch, commit *models.Commit) (*models.Commit, error) {
ghx, err := b.getGitHubConnection(branch.Repository, branch.FullRef())
if err != nil {
return nil, err
}
// TODO:IMPLEMENT
rawCommit, err := ghx.GetPriorCommit(ctx, commit.SHA)
if err != nil {
return nil, fmt.Errorf("fetching previous commit: %w", err)
}
return &models.Commit{
SHA: rawCommit,
}, nil
}
// GetDefaultBranch returns the default branch
func (b *Backend) GetDefaultBranch(ctx context.Context, repo *models.Repository) (*models.Branch, error) {
ghx, err := b.getGitHubConnection(repo, "")
if err != nil {
return nil, err
}
branchName, err := ghx.GetDefaultBranch(ctx)
if err != nil {
return nil, fmt.Errorf("fetching default branch: %w", err)
}
return &models.Branch{
Name: branchName,
Repository: repo,
}, nil
}
// GetRevisionCommit returns the commit of a revision (or error)
func (b *Backend) GetRevisionCommit(ctx context.Context, repo *models.Repository, rev models.Revision) (*models.Commit, error) {
switch inst := rev.(type) {
case *models.Commit:
return inst, nil
case *models.Tag:
if inst.Commit == nil {
ghx, err := b.getGitHubConnection(repo, "")
if err != nil {
return nil, err
}
tagCommit, err := ghx.GetTagCommit(ctx, inst.GetName())
if err != nil {
return nil, err
}
inst.Commit = tagCommit
}
return inst.Commit, nil
default:
return nil, errors.New("not implemented yet or invalid revision")
}
}