-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathupload_sbom.go
More file actions
299 lines (252 loc) · 8.64 KB
/
upload_sbom.go
File metadata and controls
299 lines (252 loc) · 8.64 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
package cmd
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"codacy/cli-v2/utils/logger"
"github.com/fatih/color"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
var (
sbomAPIToken string
sbomProvider string
sbomOrg string
sbomImageName string
sbomTag string
sbomRepoName string
sbomEnv string
sbomFormat string
sbomBaseURL string
sbomHTTPClient httpDoer = &http.Client{Timeout: 5 * time.Minute}
)
// httpDoer abstracts the Do method of http.Client for testing.
type httpDoer interface {
Do(req *http.Request) (*http.Response, error)
}
func init() {
uploadSBOMCmd.Flags().StringVarP(&sbomAPIToken, "api-token", "a", "", "API token for Codacy API (required)")
uploadSBOMCmd.Flags().StringVarP(&sbomProvider, "provider", "p", "", "Git provider (gh, gl, bb) (required)")
uploadSBOMCmd.Flags().StringVarP(&sbomOrg, "organization", "o", "", "Organization name on the Git provider (required)")
uploadSBOMCmd.Flags().StringVarP(&sbomTag, "tag", "t", "", "Docker image tag (defaults to image tag or 'latest')")
uploadSBOMCmd.Flags().StringVarP(&sbomRepoName, "repository", "r", "", "Repository name (optional)")
uploadSBOMCmd.Flags().StringVarP(&sbomEnv, "environment", "e", "", "Environment where the image is deployed (optional)")
uploadSBOMCmd.Flags().StringVar(&sbomFormat, "format", "cyclonedx", "SBOM format: cyclonedx or spdx-json (default cyclonedx, smaller output)")
uploadSBOMCmd.MarkFlagRequired("api-token")
uploadSBOMCmd.MarkFlagRequired("provider")
uploadSBOMCmd.MarkFlagRequired("organization")
rootCmd.AddCommand(uploadSBOMCmd)
}
var uploadSBOMCmd = &cobra.Command{
Use: "upload-sbom <IMAGE_NAME>",
Short: "Generate and upload an SBOM for a Docker image to Codacy",
Long: `Generate an SBOM (Software Bill of Materials) for a Docker image using Trivy
and upload it to Codacy for vulnerability tracking.
By default, Trivy generates a CycloneDX SBOM (smaller output). Use --format
to switch to spdx-json if needed. Both formats are accepted by the Codacy API.`,
Example: ` # Generate and upload SBOM
codacy-cli upload-sbom -a <api-token> -p gh -o my-org -r my-repo myapp:latest
# Use SPDX format instead
codacy-cli upload-sbom -a <api-token> -p gh -o my-org -r my-repo --format spdx-json myapp:v1.0.0`,
Args: cobra.ExactArgs(1),
Run: runUploadSBOM,
}
func runUploadSBOM(_ *cobra.Command, args []string) {
exitCode := executeUploadSBOM(args[0])
exitFunc(exitCode)
}
// executeUploadSBOM generates (or reads) an SBOM and uploads it to Codacy. Returns exit code.
func executeUploadSBOM(imageRef string) int {
if err := validateImageName(imageRef); err != nil {
logger.Error("Invalid image name", logrus.Fields{"image": imageRef, "error": err.Error()})
color.Red("Error: %v", err)
return 2
}
if sbomFormat != "cyclonedx" && sbomFormat != "spdx-json" {
color.Red("Error: --format must be 'cyclonedx' or 'spdx-json'")
return 2
}
imageName, tag := parseImageRef(imageRef)
isDigest := strings.Contains(imageRef, "@")
if sbomTag != "" {
if isDigest {
color.Red("Error: --tag cannot be used with digest references (image@sha256:...)")
return 2
}
tag = sbomTag
}
sbomImageName = imageName
var effectiveImageRef string
if isDigest {
effectiveImageRef = fmt.Sprintf("%s@%s", imageName, tag)
} else {
effectiveImageRef = fmt.Sprintf("%s:%s", imageName, tag)
}
logger.Info("Starting SBOM upload", logrus.Fields{
"image": effectiveImageRef,
"provider": sbomProvider,
"org": sbomOrg,
})
sbomPath, err := generateSBOM(effectiveImageRef)
if err != nil {
return 2
}
defer os.Remove(sbomPath)
fmt.Printf("Uploading SBOM to Codacy (org: %s/%s)...\n", sbomProvider, sbomOrg)
params := sbomUploadParams{
provider: sbomProvider,
org: sbomOrg,
apiToken: sbomAPIToken,
repoName: sbomRepoName,
env: sbomEnv,
baseURL: sbomBaseURL,
}
if err := uploadSBOMToCodacy(sbomPath, sbomImageName, tag, params); err != nil {
logger.Error("Failed to upload SBOM", logrus.Fields{"error": err.Error()})
color.Red("Error: Failed to upload SBOM: %v", err)
return 1
}
color.Green("Successfully uploaded SBOM for %s", effectiveImageRef)
return 0
}
// generateSBOM runs Trivy to generate an SBOM file and returns the path to it.
func generateSBOM(imageRef string) (string, error) {
trivyPath, err := getTrivyPath()
if err != nil {
handleTrivyNotFound(err)
return "", err
}
tmpFile, err := os.CreateTemp("", "codacy-sbom-*")
if err != nil {
logger.Error("Failed to create temp file", logrus.Fields{"error": err.Error()})
color.Red("Error: Failed to create temporary file: %v", err)
return "", err
}
tmpFile.Close()
sbomPath := tmpFile.Name()
fmt.Printf("Generating SBOM for image: %s\n", imageRef)
args := []string{"image", "--format", sbomFormat, "-o", sbomPath, imageRef}
logger.Info("Running Trivy SBOM generation", logrus.Fields{"command": fmt.Sprintf("%s %v", trivyPath, args)})
var stderrBuf bytes.Buffer
if err := commandRunner.RunWithStderr(trivyPath, args, &stderrBuf); err != nil {
if isScanFailure(stderrBuf.Bytes()) {
color.Red("Error: Failed to generate SBOM (image not found or no container runtime)")
} else {
color.Red("Error: Failed to generate SBOM: %v", err)
}
logger.Error("Trivy SBOM generation failed", logrus.Fields{"error": err.Error()})
os.Remove(sbomPath)
return "", err
}
fmt.Println("SBOM generated successfully")
return sbomPath, nil
}
// parseImageRef splits an image reference into name and tag.
// e.g. "myapp:v1.0.0" -> ("myapp", "v1.0.0"), "myapp" -> ("myapp", "latest")
func parseImageRef(imageRef string) (string, string) {
// Handle digest references (image@sha256:...)
if idx := strings.Index(imageRef, "@"); idx != -1 {
return imageRef[:idx], imageRef[idx+1:]
}
// Find the last colon that is part of the tag (not the registry port)
lastSlash := strings.LastIndex(imageRef, "/")
tagPart := imageRef
if lastSlash != -1 {
tagPart = imageRef[lastSlash:]
}
if idx := strings.LastIndex(tagPart, ":"); idx != -1 {
absIdx := idx
if lastSlash != -1 {
absIdx = lastSlash + idx
}
return imageRef[:absIdx], imageRef[absIdx+1:]
}
return imageRef, "latest"
}
type sbomUploadParams struct {
provider string
org string
apiToken string
repoName string
env string
baseURL string
}
func (p sbomUploadParams) uploadURL() string {
base := p.baseURL
if base == "" {
base = "https://app.codacy.com"
}
return fmt.Sprintf("%s/api/v3/organizations/%s/%s/image-sboms", base, p.provider, p.org)
}
func uploadSBOMToCodacy(sbomPath, imageName, tag string, params sbomUploadParams) error {
url := params.uploadURL()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
if err := buildSBOMMultipartForm(writer, sbomPath, imageName, tag, params); err != nil {
return err
}
if err := writer.Close(); err != nil {
return fmt.Errorf("failed to close multipart writer: %w", err)
}
req, err := http.NewRequest("POST", url, body)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("Accept", "application/json")
req.Header.Set("api-token", params.apiToken)
resp, err := sbomHTTPClient.Do(req)
if err != nil {
return fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
respBody, _ := io.ReadAll(resp.Body)
return fmt.Errorf("API returned status %d: %s", resp.StatusCode, string(respBody))
}
return nil
}
// buildSBOMMultipartForm populates the multipart form with the SBOM file and metadata fields.
func buildSBOMMultipartForm(writer *multipart.Writer, sbomPath, imageName, tag string, params sbomUploadParams) error {
if err := addSBOMFile(writer, sbomPath); err != nil {
return err
}
fields := map[string]string{
"imageName": imageName,
"tag": tag,
}
if params.repoName != "" {
fields["repositoryName"] = params.repoName
}
if params.env != "" {
fields["environment"] = params.env
}
for name, value := range fields {
if err := writer.WriteField(name, value); err != nil {
return fmt.Errorf("failed to write %s field: %w", name, err)
}
}
return nil
}
// addSBOMFile adds the SBOM file to the multipart form.
func addSBOMFile(writer *multipart.Writer, sbomPath string) error {
sbomFile, err := os.Open(sbomPath)
if err != nil {
return fmt.Errorf("failed to open SBOM file: %w", err)
}
defer sbomFile.Close()
part, err := writer.CreateFormFile("sbom", filepath.Base(sbomPath))
if err != nil {
return fmt.Errorf("failed to create form file: %w", err)
}
if _, err := io.Copy(part, sbomFile); err != nil {
return fmt.Errorf("failed to write SBOM to form: %w", err)
}
return nil
}