-
Notifications
You must be signed in to change notification settings - Fork 10
feat: generate and upload trivy SBOM into codacy #200
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,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 { | ||
|
Check warning on line 79 in cmd/upload_sbom.go
|
||
| 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 | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.