-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscan.go
290 lines (252 loc) · 9.2 KB
/
scan.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/*
* © 2024 Snyk Limited All rights reserved.
*
* 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.
*/
//nolint:lll // Some of the lines in this file are going to be long for now.
package codeclient
import (
"context"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/snyk/code-client-go/config"
codeClientHTTP "github.com/snyk/code-client-go/http"
"github.com/snyk/code-client-go/internal/analysis"
testModels "github.com/snyk/code-client-go/internal/api/test/2024-12-21/models"
"github.com/snyk/code-client-go/internal/bundle"
"github.com/snyk/code-client-go/internal/deepcode"
"github.com/snyk/code-client-go/observability"
"github.com/snyk/code-client-go/sarif"
"github.com/snyk/code-client-go/scan"
)
type codeScanner struct {
httpClient codeClientHTTP.HTTPClient
bundleManager bundle.BundleManager
analysisOrchestrator analysis.AnalysisOrchestrator
instrumentor observability.Instrumentor
errorReporter observability.ErrorReporter
trackerFactory scan.TrackerFactory
logger *zerolog.Logger
config config.Config
resultTypes testModels.Scan
}
type CodeScanner interface {
UploadAndAnalyze(
ctx context.Context,
requestId string,
target scan.Target,
files <-chan string,
changedFiles map[string]bool,
) (*sarif.SarifResponse, string, error)
}
var _ CodeScanner = (*codeScanner)(nil)
type OptionFunc func(*codeScanner)
func WithInstrumentor(instrumentor observability.Instrumentor) OptionFunc {
return func(c *codeScanner) {
c.instrumentor = instrumentor
}
}
func WithFlow(flow string) OptionFunc {
return func(c *codeScanner) {
switch flow {
case "ide_test":
c.resultTypes = testModels.CodeSecurityCodeQuality
default:
c.resultTypes = testModels.CodeSecurity
}
}
}
func WithErrorReporter(errorReporter observability.ErrorReporter) OptionFunc {
return func(c *codeScanner) {
c.errorReporter = errorReporter
}
}
func WithLogger(logger *zerolog.Logger) OptionFunc {
return func(c *codeScanner) {
c.logger = logger
}
}
func WithTrackerFactory(trackerFactory scan.TrackerFactory) OptionFunc {
return func(c *codeScanner) {
c.trackerFactory = trackerFactory
}
}
type AnalysisOption func(*analysis.AnalysisConfig)
func ReportLocalTest(projectName string, targetName string, targetReference string) AnalysisOption {
return func(c *analysis.AnalysisConfig) {
c.Report = true
c.ProjectName = &projectName
c.TargetName = &targetName
c.TargetReference = &targetReference
}
}
func ReportRemoteTest(projectId uuid.UUID, commitId string) AnalysisOption {
return func(c *analysis.AnalysisConfig) {
c.Report = true
c.ProjectId = &projectId
c.CommitId = &commitId
}
}
// NewCodeScanner creates a Code Scanner which can be used to trigger Snyk Code on a folder.
func NewCodeScanner(
config config.Config,
httpClient codeClientHTTP.HTTPClient,
options ...OptionFunc,
) *codeScanner {
nopLogger := zerolog.Nop()
instrumentor := observability.NewInstrumentor()
errorReporter := observability.NewErrorReporter(&nopLogger)
trackerFactory := scan.NewNoopTrackerFactory()
scanner := &codeScanner{
config: config,
httpClient: httpClient,
errorReporter: errorReporter,
logger: &nopLogger,
instrumentor: instrumentor,
trackerFactory: trackerFactory,
resultTypes: testModels.CodeSecurityCodeQuality,
}
for _, option := range options {
option(scanner)
}
// initialize other dependencies
deepcodeClient := deepcode.NewDeepcodeClient(scanner.config, httpClient, scanner.logger, scanner.instrumentor, scanner.errorReporter)
bundleManager := bundle.NewBundleManager(deepcodeClient, scanner.logger, scanner.instrumentor, scanner.errorReporter, scanner.trackerFactory)
scanner.bundleManager = bundleManager
analysisOrchestrator := analysis.NewAnalysisOrchestrator(
scanner.config,
httpClient,
analysis.WithInstrumentor(scanner.instrumentor),
analysis.WithErrorReporter(scanner.errorReporter),
analysis.WithTrackerFactory(scanner.trackerFactory),
analysis.WithLogger(scanner.logger),
analysis.WithResultType(scanner.resultTypes),
)
scanner.analysisOrchestrator = analysisOrchestrator
return scanner
}
// WithBundleManager creates a new Code Scanner from the current one and replaces the bundle manager.
// It can be used to replace the bundle manager in tests.
func (c *codeScanner) WithBundleManager(bundleManager bundle.BundleManager) *codeScanner {
return &codeScanner{
bundleManager: bundleManager,
analysisOrchestrator: c.analysisOrchestrator,
errorReporter: c.errorReporter,
logger: c.logger,
config: c.config,
}
}
// WithAnalysisOrchestrator creates a new Code Scanner from the current one and replaces the analysis orchestrator.
// It can be used to replace the analysis orchestrator in tests.
func (c *codeScanner) WithAnalysisOrchestrator(analysisOrchestrator analysis.AnalysisOrchestrator) *codeScanner {
return &codeScanner{
bundleManager: c.bundleManager,
analysisOrchestrator: analysisOrchestrator,
errorReporter: c.errorReporter,
logger: c.logger,
config: c.config,
}
}
// Upload creates a bundle from changed files and uploads it, returning the uploaded Bundle.
func (c *codeScanner) Upload(
ctx context.Context,
requestId string,
target scan.Target,
files <-chan string,
changedFiles map[string]bool,
) (bundle.Bundle, error) {
err := c.checkCancellationOrLogError(ctx, target.GetPath(), nil, "")
if err != nil {
return nil, err
}
originalBundle, err := c.bundleManager.Create(ctx, requestId, target.GetPath(), files, changedFiles)
err = c.checkCancellationOrLogError(ctx, target.GetPath(), err, "error creating bundle...")
if err != nil {
return nil, err
}
filesToUpload := originalBundle.GetFiles()
uploadedBundle, err := c.bundleManager.Upload(ctx, requestId, originalBundle, filesToUpload)
err = c.checkCancellationOrLogError(ctx, target.GetPath(), err, "error uploading bundle...")
if err != nil {
return uploadedBundle, err
}
return uploadedBundle, nil
}
// Utility function to check for cancellations before optionally logging an error (if one is provided). Cancellations
// always take precedence. Returns any error or cancellation that was handled, nil otherwise.
func (c *codeScanner) checkCancellationOrLogError(ctx context.Context, targetPath string, err error, message string) error {
returnError := ctx.Err()
if returnError != nil {
c.logger.Info().Msg("Canceling Code scan - Code scanner received cancellation signal")
} else if err != nil {
if message != "" {
err = errors.Wrap(err, message)
}
c.errorReporter.CaptureError(err, observability.ErrorReporterOptions{ErrorDiagnosticPath: targetPath})
returnError = err
}
return returnError
}
// UploadAndAnalyze returns a fake SARIF response for testing. Use target-service to run analysis on.
func (c *codeScanner) UploadAndAnalyze(
ctx context.Context,
requestId string,
target scan.Target,
files <-chan string,
changedFiles map[string]bool,
) (*sarif.SarifResponse, string, error) {
response, bundleHash, _, err := c.UploadAndAnalyzeWithOptions(ctx, requestId, target, files, changedFiles)
return response, bundleHash, err
}
// UploadAndAnalyzeWithOptions returns a fake SARIF response for testing. Use target-service to run analysis on.
func (c *codeScanner) UploadAndAnalyzeWithOptions(
ctx context.Context,
requestId string,
target scan.Target,
files <-chan string,
changedFiles map[string]bool,
options ...AnalysisOption,
) (*sarif.SarifResponse, string, *scan.ResultMetaData, error) {
uploadedBundle, err := c.Upload(ctx, requestId, target, files, changedFiles)
if err != nil || uploadedBundle == nil || uploadedBundle.GetBundleHash() == "" {
c.logger.Debug().Msg("empty bundle, no Snyk Code analysis")
return nil, "", nil, err
}
cfg := analysis.AnalysisConfig{}
for _, opt := range options {
opt(&cfg)
}
response, metadata, err := c.analysisOrchestrator.RunTest(ctx, c.config.Organization(), uploadedBundle, target, cfg)
err = c.checkCancellationOrLogError(ctx, target.GetPath(), err, "error running analysis...")
if err != nil {
return nil, "", nil, err
}
return response, uploadedBundle.GetBundleHash(), metadata, err
}
func (c *codeScanner) AnalyzeRemote(ctx context.Context, options ...AnalysisOption) (*sarif.SarifResponse, *scan.ResultMetaData, error) {
cfg := analysis.AnalysisConfig{}
for _, opt := range options {
opt(&cfg)
}
err := c.checkCancellationOrLogError(ctx, "", nil, "")
if err != nil {
return nil, nil, err
}
response, metadata, err := c.analysisOrchestrator.RunTestRemote(ctx, c.config.Organization(), cfg)
err = c.checkCancellationOrLogError(ctx, "", err, "")
if err != nil {
return nil, nil, err
}
return response, metadata, err
}