|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "io" |
| 6 | + "os" |
| 7 | + "path/filepath" |
| 8 | + "strings" |
| 9 | + |
| 10 | + "github.com/gitpod-io/leeway/pkg/leeway" |
| 11 | + "github.com/gitpod-io/leeway/pkg/leeway/cache" |
| 12 | + log "github.com/sirupsen/logrus" |
| 13 | + "github.com/spf13/cobra" |
| 14 | +) |
| 15 | + |
| 16 | +// sbomExportCmd represents the sbom export command |
| 17 | +var sbomExportCmd = &cobra.Command{ |
| 18 | + Use: "export [package]", |
| 19 | + Short: "Exports the SBOM of a (previously built) package", |
| 20 | + Long: `Exports the SBOM of a (previously built) package. |
| 21 | + |
| 22 | +When used with --with-dependencies, it exports SBOMs for the package and all its dependencies |
| 23 | +to the specified output directory. |
| 24 | +
|
| 25 | +If no package is specified, the workspace's default target is used.`, |
| 26 | + Args: cobra.MaximumNArgs(1), |
| 27 | + Run: func(cmd *cobra.Command, args []string) { |
| 28 | + // Get the package |
| 29 | + _, pkg, _, _ := getTarget(args, false) |
| 30 | + if pkg == nil { |
| 31 | + log.Fatal("sbom export requires a package or a default target in the workspace") |
| 32 | + } |
| 33 | + |
| 34 | + // Get build options and cache |
| 35 | + _, localCache := getBuildOpts(cmd) |
| 36 | + |
| 37 | + // Get output format and file |
| 38 | + format, _ := cmd.Flags().GetString("format") |
| 39 | + outputFile, _ := cmd.Flags().GetString("output") |
| 40 | + withDependencies, _ := cmd.Flags().GetBool("with-dependencies") |
| 41 | + outputDir, _ := cmd.Flags().GetString("output-dir") |
| 42 | + |
| 43 | + // Validate format using the utility function |
| 44 | + formatValid, validFormats := leeway.ValidateSBOMFormat(format) |
| 45 | + if !formatValid { |
| 46 | + log.Fatalf("Unsupported format: %s. Supported formats are: %s", format, strings.Join(validFormats, ", ")) |
| 47 | + } |
| 48 | + |
| 49 | + // Validate flags for dependency export |
| 50 | + if withDependencies { |
| 51 | + if outputDir == "" { |
| 52 | + log.Fatal("--output-dir is required when using --with-dependencies") |
| 53 | + } |
| 54 | + if outputFile != "" { |
| 55 | + log.Fatal("--output and --output-dir cannot be used together") |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + var allpkg []*leeway.Package |
| 60 | + allpkg = append(allpkg, pkg) |
| 61 | + |
| 62 | + if withDependencies { |
| 63 | + // Get all dependencies |
| 64 | + deps := pkg.GetTransitiveDependencies() |
| 65 | + log.Infof("Exporting SBOMs for %s and %d dependencies to %s", pkg.FullName(), len(deps), outputDir) |
| 66 | + |
| 67 | + allpkg = append(allpkg, deps...) |
| 68 | + } |
| 69 | + |
| 70 | + for _, p := range allpkg { |
| 71 | + var outputPath string |
| 72 | + if outputFile == "" { |
| 73 | + safeFilename := p.FilesystemSafeName() |
| 74 | + outputPath = filepath.Join(outputDir, safeFilename+leeway.GetSBOMFileExtension(format)) |
| 75 | + } else { |
| 76 | + outputPath = outputFile |
| 77 | + } |
| 78 | + exportSBOM(p, localCache, outputPath, format) |
| 79 | + } |
| 80 | + }, |
| 81 | +} |
| 82 | + |
| 83 | +func init() { |
| 84 | + sbomExportCmd.Flags().String("format", "cyclonedx", "SBOM format to export (cyclonedx, spdx, syft)") |
| 85 | + sbomExportCmd.Flags().StringP("output", "o", "", "Output file (defaults to stdout)") |
| 86 | + sbomExportCmd.Flags().Bool("with-dependencies", false, "Export SBOMs for the package and all its dependencies") |
| 87 | + sbomExportCmd.Flags().String("output-dir", "", "Output directory for exporting multiple SBOMs (required with --with-dependencies)") |
| 88 | + |
| 89 | + sbomCmd.AddCommand(sbomExportCmd) |
| 90 | + addBuildFlags(sbomExportCmd) |
| 91 | +} |
| 92 | + |
| 93 | +// exportSBOM extracts and writes an SBOM from a package's cached archive. |
| 94 | +// It retrieves the package from the cache, creates the output file if needed, |
| 95 | +// and extracts the SBOM in the specified format. If outputFile is empty, |
| 96 | +// the SBOM is written to stdout. |
| 97 | +func exportSBOM(pkg *leeway.Package, localCache cache.LocalCache, outputFile string, format string) { |
| 98 | + pkgFN := GetPackagePath(pkg, localCache) |
| 99 | + |
| 100 | + var output io.Writer = os.Stdout |
| 101 | + |
| 102 | + // Create directory if it doesn't exist |
| 103 | + if dir := filepath.Dir(outputFile); dir != "" { |
| 104 | + if err := os.MkdirAll(dir, 0755); err != nil { |
| 105 | + log.WithError(err).Fatalf("cannot create output directory %s", dir) |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + file, err := os.Create(outputFile) |
| 110 | + if err != nil { |
| 111 | + log.WithError(err).Fatalf("cannot create output file %s", outputFile) |
| 112 | + } |
| 113 | + defer file.Close() |
| 114 | + output = file |
| 115 | + |
| 116 | + // Extract and output the SBOM |
| 117 | + err = leeway.AccessSBOMInCachedArchive(pkgFN, format, func(sbomReader io.Reader) error { |
| 118 | + log.Infof("Exporting SBOM in %s format", format) |
| 119 | + _, err := io.Copy(output, sbomReader) |
| 120 | + return err |
| 121 | + }) |
| 122 | + |
| 123 | + if err != nil { |
| 124 | + if err == leeway.ErrNoSBOMFile { |
| 125 | + log.Fatalf("no SBOM file found in package %s", pkg.FullName()) |
| 126 | + } |
| 127 | + log.WithError(err).Fatal("cannot extract SBOM") |
| 128 | + } |
| 129 | + |
| 130 | + if outputFile != "" { |
| 131 | + log.Infof("SBOM exported to %s", outputFile) |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +// GetPackagePath retrieves the filesystem path to a package's cached archive. |
| 136 | +// It first checks the local cache, and if not found, attempts to download |
| 137 | +// the package from the remote cache. This function verifies that SBOM is enabled |
| 138 | +// in the workspace settings and returns the path to the package archive. |
| 139 | +// If the package cannot be found in either cache, it exits with a fatal error. |
| 140 | +func GetPackagePath(pkg *leeway.Package, localCache cache.LocalCache) (packagePath string) { |
| 141 | + // Check if SBOM is enabled in workspace settings |
| 142 | + if !pkg.C.W.SBOM.Enabled { |
| 143 | + log.Fatal("SBOM export/scan requires sbom.enabled=true in workspace settings") |
| 144 | + } |
| 145 | + |
| 146 | + if log.IsLevelEnabled(log.DebugLevel) { |
| 147 | + v, err := pkg.Version() |
| 148 | + if err != nil { |
| 149 | + log.WithError(err).Fatal("error getting version") |
| 150 | + } |
| 151 | + log.Debugf("Exporting SBOM of package %s (version %s)", pkg.FullName(), v) |
| 152 | + } |
| 153 | + |
| 154 | + // Get package location in local cache |
| 155 | + pkgFN, ok := localCache.Location(pkg) |
| 156 | + if !ok { |
| 157 | + // Package not found in local cache, check if it's in the remote cache |
| 158 | + log.Debugf("Package %s not found in local cache, checking remote cache", pkg.FullName()) |
| 159 | + |
| 160 | + remoteCache := getRemoteCache() |
| 161 | + remoteCache = &pullOnlyRemoteCache{C: remoteCache} |
| 162 | + |
| 163 | + // Convert to cache.Package interface |
| 164 | + pkgsToCheck := []cache.Package{pkg} |
| 165 | + |
| 166 | + if log.IsLevelEnabled(log.DebugLevel) { |
| 167 | + v, err := pkgsToCheck[0].Version() |
| 168 | + if err != nil { |
| 169 | + log.WithError(err).Fatal("error getting version") |
| 170 | + } |
| 171 | + log.Debugf("Checking remote of package %s (version %s)", pkgsToCheck[0].FullName(), v) |
| 172 | + } |
| 173 | + |
| 174 | + // Check if the package exists in the remote cache |
| 175 | + existingPkgs, err := remoteCache.ExistingPackages(context.Background(), pkgsToCheck) |
| 176 | + if err != nil { |
| 177 | + log.WithError(err).Warnf("Failed to check if package %s exists in remote cache", pkg.FullName()) |
| 178 | + log.Fatalf("%s is not built", pkg.FullName()) |
| 179 | + } else { |
| 180 | + _, existsInRemote := existingPkgs[pkg] |
| 181 | + if existsInRemote { |
| 182 | + log.Infof("Package %s found in remote cache, downloading...", pkg.FullName()) |
| 183 | + |
| 184 | + // Download the package from the remote cache |
| 185 | + err := remoteCache.Download(context.Background(), localCache, pkgsToCheck) |
| 186 | + if err != nil { |
| 187 | + log.WithError(err).Fatalf("Failed to download package %s from remote cache", pkg.FullName()) |
| 188 | + } |
| 189 | + |
| 190 | + // Check if the download was successful |
| 191 | + pkgFN, ok = localCache.Location(pkg) |
| 192 | + if !ok { |
| 193 | + log.Fatalf("Failed to download package %s from remote cache", pkg.FullName()) |
| 194 | + } |
| 195 | + |
| 196 | + log.Infof("Successfully downloaded package %s from remote cache", pkg.FullName()) |
| 197 | + } else { |
| 198 | + log.Fatalf("%s is not built", pkg.FullName()) |
| 199 | + } |
| 200 | + } |
| 201 | + } |
| 202 | + return pkgFN |
| 203 | +} |
0 commit comments