Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
299 changes: 299 additions & 0 deletions cmd/upload_sbom.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,299 @@
package cmd

Check notice on line 1 in cmd/upload_sbom.go

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

cmd/upload_sbom.go#L1

should have a package comment

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

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

cmd/upload_sbom.go#L79

Method executeUploadSBOM has 53 lines of code (limit is 50)

Check warning on line 79 in cmd/upload_sbom.go

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

cmd/upload_sbom.go#L79

Method executeUploadSBOM has a cyclomatic complexity of 9 (limit is 7)
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
}
Loading
Loading