/
scorecard.go
272 lines (247 loc) · 7.11 KB
/
scorecard.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
// Copyright 2020 OpenSSF Scorecard Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package pkg defines fns for running Scorecard checks on a Repo.
package pkg
import (
"context"
"errors"
"fmt"
"os"
"strings"
"sync"
"time"
"sigs.k8s.io/release-utils/version"
"github.com/ossf/scorecard/v5/checker"
"github.com/ossf/scorecard/v5/clients"
"github.com/ossf/scorecard/v5/config"
sce "github.com/ossf/scorecard/v5/errors"
"github.com/ossf/scorecard/v5/finding"
proberegistration "github.com/ossf/scorecard/v5/internal/probes"
sclog "github.com/ossf/scorecard/v5/log"
"github.com/ossf/scorecard/v5/options"
)
// errEmptyRepository indicates the repository is empty.
var errEmptyRepository = errors.New("repository empty")
func runEnabledChecks(ctx context.Context,
repo clients.Repo,
request *checker.CheckRequest,
checksToRun checker.CheckNameToFnMap,
resultsCh chan<- checker.CheckResult,
) {
wg := sync.WaitGroup{}
for checkName, checkFn := range checksToRun {
checkName := checkName
checkFn := checkFn
wg.Add(1)
go func() {
defer wg.Done()
runner := checker.NewRunner(
checkName,
repo.URI(),
request,
)
resultsCh <- runner.Run(ctx, checkFn)
}()
}
wg.Wait()
close(resultsCh)
}
func getRepoCommitHash(r clients.RepoClient) (string, error) {
commits, err := r.ListCommits()
if err != nil {
// allow --local repos to still process
if errors.Is(err, clients.ErrUnsupportedFeature) {
return "unknown", nil
}
return "", sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("ListCommits:%v", err.Error()))
}
if len(commits) == 0 {
return "", errEmptyRepository
}
return commits[0].SHA, nil
}
func runScorecard(ctx context.Context,
repo clients.Repo,
commitSHA string,
commitDepth int,
checksToRun checker.CheckNameToFnMap,
probesToRun []string,
repoClient clients.RepoClient,
ossFuzzRepoClient clients.RepoClient,
ciiClient clients.CIIBestPracticesClient,
vulnsClient clients.VulnerabilitiesClient,
) (ScorecardResult, error) {
if err := repoClient.InitRepo(repo, commitSHA, commitDepth); err != nil {
// No need to call sce.WithMessage() since InitRepo will do that for us.
//nolint:wrapcheck
return ScorecardResult{}, err
}
defer repoClient.Close()
versionInfo := version.GetVersionInfo()
ret := ScorecardResult{
Repo: RepoInfo{
Name: repo.URI(),
CommitSHA: commitSHA,
},
Scorecard: ScorecardInfo{
Version: versionInfo.GitVersion,
CommitSHA: versionInfo.GitCommit,
},
Date: time.Now(),
}
commitSHA, err := getRepoCommitHash(repoClient)
if errors.Is(err, errEmptyRepository) {
return ret, nil
} else if err != nil {
return ScorecardResult{}, err
}
ret.Repo.CommitSHA = commitSHA
defaultBranch, err := repoClient.GetDefaultBranchName()
if err != nil {
if !errors.Is(err, clients.ErrUnsupportedFeature) {
return ScorecardResult{},
sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("GetDefaultBranchName:%v", err.Error()))
}
defaultBranch = "unknown"
}
resultsCh := make(chan checker.CheckResult)
// Set metadata for all checks to use. This is necessary
// to create remediations from the probe yaml files.
ret.RawResults.Metadata.Metadata = map[string]string{
"repository.host": repo.Host(),
"repository.name": strings.TrimPrefix(repo.URI(), repo.Host()+"/"),
"repository.uri": repo.URI(),
"repository.sha1": commitSHA,
"repository.defaultBranch": defaultBranch,
}
request := &checker.CheckRequest{
Ctx: ctx,
RepoClient: repoClient,
OssFuzzRepo: ossFuzzRepoClient,
CIIClient: ciiClient,
VulnerabilitiesClient: vulnsClient,
Repo: repo,
RawResults: &ret.RawResults,
}
// If the user runs probes
if len(probesToRun) > 0 {
err = runEnabledProbes(request, probesToRun, &ret)
if err != nil {
return ScorecardResult{}, err
}
return ret, nil
}
// If the user runs checks
go runEnabledChecks(ctx, repo, request, checksToRun, resultsCh)
if os.Getenv(options.EnvVarScorecardExperimental) == "1" {
// Get configuration
rc, err := repoClient.GetFileReader("scorecard.yml")
// If configuration file exists, continue. Otherwise, ignore
if err == nil {
defer rc.Close()
checks := []string{}
for check := range checksToRun {
checks = append(checks, check)
}
c, err := config.Parse(rc, checks)
if err != nil {
logger := sclog.NewLogger(sclog.DefaultLevel)
logger.Error(err, "parsing configuration file")
}
ret.Config = c
}
}
for result := range resultsCh {
ret.Checks = append(ret.Checks, result)
ret.Findings = append(ret.Findings, result.Findings...)
}
return ret, nil
}
func runEnabledProbes(request *checker.CheckRequest,
probesToRun []string,
ret *ScorecardResult,
) error {
// Add RawResults to request
err := populateRawResults(request, probesToRun, ret)
if err != nil {
return err
}
probeFindings := make([]finding.Finding, 0)
for _, probeName := range probesToRun {
probe, err := proberegistration.Get(probeName)
if err != nil {
return fmt.Errorf("getting probe %q: %w", probeName, err)
}
// Run probe
var findings []finding.Finding
if probe.IndependentImplementation != nil {
findings, _, err = probe.IndependentImplementation(request)
} else {
findings, _, err = probe.Implementation(&ret.RawResults)
}
if err != nil {
return sce.WithMessage(sce.ErrScorecardInternal, "ending run")
}
probeFindings = append(probeFindings, findings...)
}
ret.Findings = probeFindings
return nil
}
// RunScorecard runs enabled Scorecard checks on a Repo.
func RunScorecard(ctx context.Context,
repo clients.Repo,
commitSHA string,
commitDepth int,
checksToRun checker.CheckNameToFnMap,
repoClient clients.RepoClient,
ossFuzzRepoClient clients.RepoClient,
ciiClient clients.CIIBestPracticesClient,
vulnsClient clients.VulnerabilitiesClient,
) (ScorecardResult, error) {
return runScorecard(ctx,
repo,
commitSHA,
commitDepth,
checksToRun,
[]string{},
repoClient,
ossFuzzRepoClient,
ciiClient,
vulnsClient,
)
}
// ExperimentalRunProbes is experimental. Do not depend on it, it may be removed at any point.
func ExperimentalRunProbes(ctx context.Context,
repo clients.Repo,
commitSHA string,
commitDepth int,
checksToRun checker.CheckNameToFnMap,
probesToRun []string,
repoClient clients.RepoClient,
ossFuzzRepoClient clients.RepoClient,
ciiClient clients.CIIBestPracticesClient,
vulnsClient clients.VulnerabilitiesClient,
) (ScorecardResult, error) {
return runScorecard(ctx,
repo,
commitSHA,
commitDepth,
checksToRun,
probesToRun,
repoClient,
ossFuzzRepoClient,
ciiClient,
vulnsClient,
)
}