diff --git a/README.md b/README.md index e13108b..8cf9f6c 100644 --- a/README.md +++ b/README.md @@ -525,6 +525,9 @@ armis-cli scan repo ./my-app --sbom --sbom-format spdx # Download an AI-BOM and a CBOM armis-cli scan repo ./my-app --bom aibom,cbom + +# Also scan up to 20 SBOM files kept in the repository +armis-cli scan repo ./my-app --include-sbom-files 20 ``` #### SBOM Format @@ -656,6 +659,29 @@ Notes: skipped for `--changed` and `--include-files` partial uploads, and for subdirectory scans, since those are not faithful whole-repo snapshots. +#### Scan SBOM Files in the Repository + +Repositories sometimes keep SBOM documents, for example one per product release. +`--include-sbom-files N` scans them for vulnerabilities alongside the code: + +```bash +armis-cli scan repo . --include-sbom-files 20 +``` + +- `N` is required and is the most SBOM files to scan (at least 1). The server + may apply a lower limit for your tenant. +- Only real SBOMs are scanned: CycloneDX (JSON or XML) and SPDX (JSON or + tag-value), recognized by their format. Other JSON/XML files are scanned as + regular code. +- If more SBOMs are found than the limit, the first `N` in path order are + scanned. When any SBOM is skipped (over the limit, too large, timed out), the + CLI prints a warning naming the skipped files; their findings keep their + previous state. The exit code is not affected. +- Without the flag, SBOM files in the repository are not scanned for + vulnerabilities. +- Not to be confused with `--sbom`, which *generates* an SBOM of the scanned + repository. + ### Scan Container Image Scans a container image (local or remote) or a tarball. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 45359b6..5efb84e 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `scan repo --include-sbom-files N` scans up to N CycloneDX/SPDX files kept in the repository for vulnerabilities, alongside the code, and warns (without changing the exit code) when some SBOM files were skipped (#370) + ### Changed ### Deprecated diff --git a/internal/api/client.go b/internal/api/client.go index 879f9c9..f324b65 100644 --- a/internal/api/client.go +++ b/internal/api/client.go @@ -330,6 +330,9 @@ type IngestOptions struct { BOMFormat string // ImageRef names the scanned image for its BOMs; empty is omitted. ImageRef string + // IncludeSBOMFiles is the --include-sbom-files limit; 0 leaves SBOM files + // out of the scan. + IncludeSBOMFiles int } // StatusCallback is called on each poll with the current scan status. @@ -557,6 +560,8 @@ func (c *Client) startArtifactScan(ctx context.Context, scanID string, opts Inge BOMTypes: opts.BOMTypes, BOMFormat: opts.BOMFormat, ImageRef: opts.ImageRef, + + IncludeSBOMFiles: opts.IncludeSBOMFiles, } bodyBytes, err := json.Marshal(body) if err != nil { @@ -894,6 +899,13 @@ type ArtifactScanResultsResponse struct { // BOMSummary tells why a requested BOM type has no key in Results. Nil // from servers that predate BOMs and for scans without one. BOMSummary *BOMSummary `json:"bom_summary"` + // SBOM fields are set only when SBOM files were scanned alongside the code + // (--include-sbom-files). PARTIAL or FAILED means some SBOM files were not + // scanned; their findings keep their previous state. + SBOMScanStatus string `json:"sbom_scan_status,omitempty"` + SBOMScanReasons []string `json:"sbom_scan_reasons,omitempty"` + SBOMSkippedFiles []SkippedSBOMFile `json:"sbom_skipped_files,omitempty"` + SBOMSkippedCount int `json:"sbom_skipped_count,omitempty"` } // BOM type statuses in bom_summary.types..status. These mirror the @@ -943,6 +955,12 @@ func (e *DownloadStatusError) Error() string { return fmt.Sprintf("download failed with status %d", e.StatusCode) } +// SkippedSBOMFile is one SBOM file the backend did not scan, and why. +type SkippedSBOMFile struct { + Path string `json:"path"` + Reason string `json:"reason"` +} + // SkipMessage returns the human-readable skip reason and true if the backend // reported that a scanner was skipped for this scan. func (r *ArtifactScanResultsResponse) SkipMessage() (string, bool) { @@ -956,6 +974,64 @@ func (r *ArtifactScanResultsResponse) SkipMessage() (string, bool) { return msg, true } +// sbomSkipReasonText turns the backend's SBOM skip reasons into user wording. +var sbomSkipReasonText = map[string]string{ + "file_limit_exceeded": "over the SBOM file limit", + "file_too_large": "too large", + "grype_timeout": "timed out", + "grype_error": "could not be scanned", + "conversion_failed": "could not be read", +} + +// maxListedSkippedSBOMFiles caps how many skipped SBOM paths the warning names. +const maxListedSkippedSBOMFiles = 5 + +// SBOMScanWarning returns a warning when the backend reported that some SBOM +// files were not scanned, and true; otherwise "" and false. +func (r *ArtifactScanResultsResponse) SBOMScanWarning() (string, bool) { + if r == nil { + return "", false + } + var lead string + switch strings.ToUpper(r.SBOMScanStatus) { + case "PARTIAL": + lead = fmt.Sprintf("SBOM scan incomplete: %d SBOM file(s) were not scanned", r.SBOMSkippedCount) + case "FAILED": + lead = "SBOM scan failed: none of the SBOM files could be scanned" + default: + return "", false + } + + var reasons []string + for _, reason := range r.SBOMScanReasons { + text, ok := sbomSkipReasonText[reason] + if !ok { + text = strings.ReplaceAll(reason, "_", " ") + } + reasons = append(reasons, text) + } + msg := lead + if len(reasons) > 0 { + msg += " (" + strings.Join(reasons, ", ") + ")" + } + msg += ". Their findings keep their previous state." + + var paths []string + for i, f := range r.SBOMSkippedFiles { + if i == maxListedSkippedSBOMFiles { + break + } + paths = append(paths, f.Path) + } + if len(paths) > 0 { + msg += " Skipped: " + strings.Join(paths, ", ") + if more := r.SBOMSkippedCount - len(paths); more > 0 { + msg += fmt.Sprintf(" and %d more", more) + } + } + return msg, true +} + // FetchArtifactScanResults retrieves the scan results including pre-signed URLs for SBOM and VEX documents. func (c *Client) FetchArtifactScanResults(ctx context.Context, tenantID, scanID string) (*ArtifactScanResultsResponse, error) { endpoint := strings.TrimSuffix(c.baseURL, "/") + "/api/v1/ingest/results" diff --git a/internal/api/client_test.go b/internal/api/client_test.go index 97cecbc..595284f 100644 --- a/internal/api/client_test.go +++ b/internal/api/client_test.go @@ -343,6 +343,55 @@ func TestClient_StartIngest(t *testing.T) { } }) + t.Run("forwards include_sbom_files to /scan when set", func(t *testing.T) { + t.Parallel() + srv, state := newIngestFlowServer(t) + client := newIngestFlowClient(t, srv.URL) + + _, err := client.StartIngest(context.Background(), IngestOptions{ + TenantID: "tenant-456", ArtifactType: "repo", Filename: "test.tar.gz", + Data: bytes.NewReader([]byte("test")), Size: 4, + IncludeSBOMFiles: 20, + }) + if err != nil { + t.Fatalf("StartIngest failed: %v", err) + } + + state.mu.Lock() + body := state.lastScanRequestBody + state.mu.Unlock() + + var req model.IngestScanStartRequest + if err := json.Unmarshal(body, &req); err != nil { + t.Fatalf("failed to unmarshal /scan body: %v", err) + } + if req.IncludeSBOMFiles != 20 { + t.Errorf("include_sbom_files = %d, want 20", req.IncludeSBOMFiles) + } + }) + + t.Run("omits include_sbom_files when unset", func(t *testing.T) { + t.Parallel() + srv, state := newIngestFlowServer(t) + client := newIngestFlowClient(t, srv.URL) + + _, err := client.StartIngest(context.Background(), IngestOptions{ + TenantID: "tenant-456", ArtifactType: "repo", Filename: "test.tar.gz", + Data: bytes.NewReader([]byte("test")), Size: 4, + }) + if err != nil { + t.Fatalf("StartIngest failed: %v", err) + } + + state.mu.Lock() + body := state.lastScanRequestBody + state.mu.Unlock() + + if strings.Contains(string(body), "include_sbom_files") { + t.Errorf("expected include_sbom_files to be omitted, got body: %s", body) + } + }) + t.Run("forwards git hints to /scan when set", func(t *testing.T) { t.Parallel() srv, state := newIngestFlowServer(t) diff --git a/internal/api/sbom_scan_warning_test.go b/internal/api/sbom_scan_warning_test.go new file mode 100644 index 0000000..a64ca7e --- /dev/null +++ b/internal/api/sbom_scan_warning_test.go @@ -0,0 +1,109 @@ +package api + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestSBOMScanWarning(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + body string + wantOK bool + contains []string + absent []string + }{ + { + name: "no SBOM scanning reports nothing", + body: `{"scan_status":"COMPLETED","results":{}}`, + wantOK: false, + }, + { + name: "complete SBOM scan reports nothing", + body: `{"scan_status":"COMPLETED","results":{},"sbom_scan_status":"COMPLETED"}`, + wantOK: false, + }, + { + name: "partial scan names the reasons and the skipped files", + body: `{"scan_status":"COMPLETED","results":{}, + "sbom_scan_status":"PARTIAL", + "sbom_scan_reasons":["file_limit_exceeded","file_too_large"], + "sbom_skipped_files":[{"path":"z/bom.json","reason":"file_limit_exceeded"}, + {"path":"huge.json","reason":"file_too_large"}], + "sbom_skipped_count":2}`, + wantOK: true, + contains: []string{ + "SBOM scan incomplete: 2 SBOM file(s) were not scanned", + "over the SBOM file limit, too large", + "keep their previous state", + "Skipped: z/bom.json, huge.json", + }, + absent: []string{"more"}, + }, + { + name: "long skip lists are shortened with a total", + body: `{"scan_status":"COMPLETED","results":{}, + "sbom_scan_status":"PARTIAL","sbom_scan_reasons":["file_limit_exceeded"], + "sbom_skipped_files":[{"path":"1.json"},{"path":"2.json"},{"path":"3.json"}, + {"path":"4.json"},{"path":"5.json"},{"path":"6.json"}], + "sbom_skipped_count":40}`, + wantOK: true, + contains: []string{"40 SBOM file(s)", "1.json, 2.json, 3.json, 4.json, 5.json and 35 more"}, + absent: []string{"6.json"}, + }, + { + name: "failed scan says nothing was scanned", + body: `{"scan_status":"COMPLETED","results":{}, + "sbom_scan_status":"FAILED","sbom_scan_reasons":["grype_timeout"], + "sbom_skipped_files":[{"path":"a.json","reason":"grype_timeout"}], + "sbom_skipped_count":1}`, + wantOK: true, + contains: []string{"SBOM scan failed: none of the SBOM files could be scanned", "(timed out)"}, + }, + { + name: "an unknown reason is still shown readably", + body: `{"scan_status":"COMPLETED","results":{}, + "sbom_scan_status":"PARTIAL","sbom_scan_reasons":["new_backend_reason"], + "sbom_skipped_count":1}`, + wantOK: true, + contains: []string{"(new backend reason)"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + var resp ArtifactScanResultsResponse + if err := json.Unmarshal([]byte(tt.body), &resp); err != nil { + t.Fatalf("unmarshal: %v", err) + } + + msg, ok := resp.SBOMScanWarning() + + if ok != tt.wantOK { + t.Fatalf("ok = %v, want %v (msg %q)", ok, tt.wantOK, msg) + } + for _, want := range tt.contains { + if !strings.Contains(msg, want) { + t.Errorf("message %q does not contain %q", msg, want) + } + } + for _, unwanted := range tt.absent { + if strings.Contains(msg, unwanted) { + t.Errorf("message %q should not contain %q", msg, unwanted) + } + } + }) + } +} + +func TestSBOMScanWarningNilResponse(t *testing.T) { + t.Parallel() + var resp *ArtifactScanResultsResponse + if msg, ok := resp.SBOMScanWarning(); ok || msg != "" { + t.Errorf("nil response: got (%q, %v), want (\"\", false)", msg, ok) + } +} diff --git a/internal/cmd/scan_repo.go b/internal/cmd/scan_repo.go index 784338a..a1a2a78 100644 --- a/internal/cmd/scan_repo.go +++ b/internal/cmd/scan_repo.go @@ -22,6 +22,10 @@ var changedRef string // showSuppressed controls whether findings suppressed by .armisignore are displayed. var showSuppressed bool +// includeSBOMFiles holds the value for the --include-sbom-files flag: the +// maximum number of SBOM files to scan alongside the code (0 = flag not set). +var includeSBOMFiles int + var scanRepoCmd = &cobra.Command{ Use: "repo [path]", Short: "Scan a local repository", @@ -35,7 +39,8 @@ var scanRepoCmd = &cobra.Command{ $ armis-cli scan repo . --bom all --bom-format cyclonedx-1.6 --bom-output ./boms $ armis-cli scan repo . --changed $ armis-cli scan repo . --changed=staged - $ armis-cli scan repo . --changed=main`, + $ armis-cli scan repo . --changed=main + $ armis-cli scan repo . --include-sbom-files 20`, // MaximumNArgs(1) (not ExactArgs(1)) makes the `[path]` in Use honest: the path // is optional and defaults to the current directory, matching every example and // `scan image`'s arg handling. @@ -56,6 +61,10 @@ var scanRepoCmd = &cobra.Command{ repoPath = args[0] } + if err := validateIncludeSBOMFiles(cmd); err != nil { + return err + } + // Validate path exists and is a directory before making network calls // armis:ignore cwe:22 reason:os.Stat is read-only existence check; path is from direct CLI arg, not untrusted input info, err := os.Stat(repoPath) @@ -107,6 +116,9 @@ var scanRepoCmd = &cobra.Command{ if pollInterval > 0 { scanner = scanner.WithPollInterval(pollInterval) } + if includeSBOMFiles > 0 { + scanner = scanner.WithSBOMFiles(includeSBOMFiles) + } warnOnUnusedSBOMVEXFlags() warnOnUnusedBOMFlags() @@ -241,8 +253,22 @@ func init() { "Scan only git-changed files: --changed for uncommitted, "+ "--changed=staged for staged only, --changed=REF for changes vs a branch/tag "+ "(e.g., --changed=main). Note: 'staged' and 'uncommitted' are reserved and cannot be used as ref names") + // The limit is required (no NoOptDefVal) so "--include-sbom-files 20" parses + // as a limit of 20 rather than as a path argument. + scanRepoCmd.Flags().IntVar(&includeSBOMFiles, "include-sbom-files", 0, + "Also scan the repository's SBOM files (CycloneDX, SPDX) for vulnerabilities, "+ + "at most N of them (e.g., --include-sbom-files 20). The server may apply a lower limit") // NoOptDefVal is the value used when --changed is passed without a value scanRepoCmd.Flags().Lookup("changed").NoOptDefVal = "uncommitted" scanRepoCmd.MarkFlagsMutuallyExclusive("include-files", "changed") scanCmd.AddCommand(scanRepoCmd) } + +// validateIncludeSBOMFiles rejects a --include-sbom-files limit below 1 before +// any network call. +func validateIncludeSBOMFiles(cmd *cobra.Command) error { + if cmd.Flags().Changed("include-sbom-files") && includeSBOMFiles < 1 { + return fmt.Errorf("invalid --include-sbom-files value %d: must be at least 1", includeSBOMFiles) + } + return nil +} diff --git a/internal/cmd/scan_repo_sbom_test.go b/internal/cmd/scan_repo_sbom_test.go new file mode 100644 index 0000000..4641044 --- /dev/null +++ b/internal/cmd/scan_repo_sbom_test.go @@ -0,0 +1,180 @@ +package cmd + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/ArmisSecurity/armis-cli/internal/testutil" +) + +// setUpRepoScan points the repo command at a mock API and a one-file repo, +// restoring every global it touches when the test ends. +func setUpRepoScan(t *testing.T, cfg testutil.MockAPIConfig) string { + t.Helper() + + serverURL := testutil.GetMockServerURLWithConfig(t, cfg) + repoDir := t.TempDir() + if err := os.WriteFile(filepath.Join(repoDir, "main.go"), []byte("package main\n"), 0600); err != nil { + t.Fatalf("failed to create test file: %v", err) + } + + saved := struct { + token, tenantID, clientID, clientSecret, format, color, theme string + noUpdateCheck, noProgress bool + poll time.Duration + }{token, tenantID, clientID, clientSecret, format, colorFlag, themeFlag, noUpdateCheck, noProgress, pollInterval} + t.Cleanup(func() { + token, tenantID, clientID, clientSecret = saved.token, saved.tenantID, saved.clientID, saved.clientSecret + format, colorFlag, themeFlag = saved.format, saved.color, saved.theme + noUpdateCheck, noProgress, pollInterval = saved.noUpdateCheck, saved.noProgress, saved.poll + resetIncludeSBOMFilesFlag(t) + }) + + t.Setenv("ARMIS_API_URL", serverURL) + t.Setenv("ARMIS_CLIENT_ID", "") + t.Setenv("ARMIS_CLIENT_SECRET", "") + token = testToken + tenantID = testTenantID + clientID = "" + clientSecret = "" + format = agentFormatJSON + colorFlag = testColorNever + themeFlag = themeAuto + noUpdateCheck = true + noProgress = true + pollInterval = 10 * time.Millisecond + return repoDir +} + +func resetIncludeSBOMFilesFlag(t *testing.T) { + t.Helper() + flag := scanRepoCmd.Flags().Lookup("include-sbom-files") + if err := flag.Value.Set("0"); err != nil { + t.Fatalf("reset --include-sbom-files: %v", err) + } + flag.Changed = false +} + +// scanBodyRecorder captures the last /ingest/scan body the mock API received. +type scanBodyRecorder struct { + mu sync.Mutex + body []byte +} + +func (r *scanBodyRecorder) record(body []byte) { + r.mu.Lock() + defer r.mu.Unlock() + r.body = body +} + +func (r *scanBodyRecorder) get() []byte { + r.mu.Lock() + defer r.mu.Unlock() + return r.body +} + +func TestScanRepoRunE_IncludeSBOMFilesIsSentAndPartialScanWarns(t *testing.T) { + recorder := &scanBodyRecorder{} + repoDir := setUpRepoScan(t, testutil.MockAPIConfig{ + OnScanRequest: recorder.record, + SBOMScan: map[string]interface{}{ + "sbom_scan_status": "PARTIAL", + "sbom_scan_reasons": []string{"file_limit_exceeded"}, + "sbom_skipped_files": []map[string]string{{"path": "4x/x800_vms_sbom.json", "reason": "file_limit_exceeded"}}, + "sbom_skipped_count": 1, + }, + }) + if err := scanRepoCmd.Flags().Set("include-sbom-files", "20"); err != nil { + t.Fatalf("set flag: %v", err) + } + + var runErr error + stderr := testutil.CaptureStderr(t, func() { + runErr = scanRepoCmd.RunE(scanRepoCmd, []string{repoDir}) + }) + if runErr != nil { + t.Fatalf("a partial SBOM scan must not fail the command, got: %v", runErr) + } + + var sent map[string]interface{} + if err := json.Unmarshal(recorder.get(), &sent); err != nil { + t.Fatalf("unmarshal /ingest/scan body %q: %v", recorder.get(), err) + } + if got := sent["include_sbom_files"]; got != float64(20) { + t.Errorf("include_sbom_files = %v, want 20", got) + } + if !strings.Contains(stderr, "SBOM scan incomplete: 1 SBOM file(s) were not scanned") { + t.Errorf("expected the SBOM warning on stderr, got: %q", stderr) + } + if !strings.Contains(stderr, "4x/x800_vms_sbom.json") { + t.Errorf("expected the skipped file on stderr, got: %q", stderr) + } +} + +func TestScanRepoRunE_WithoutTheFlagNoSBOMFieldIsSent(t *testing.T) { + recorder := &scanBodyRecorder{} + repoDir := setUpRepoScan(t, testutil.MockAPIConfig{OnScanRequest: recorder.record}) + + if err := scanRepoCmd.RunE(scanRepoCmd, []string{repoDir}); err != nil { + t.Fatalf("expected successful scan, got: %v", err) + } + + if body := string(recorder.get()); strings.Contains(body, "include_sbom_files") { + t.Errorf("include_sbom_files must be omitted without the flag, got body: %s", body) + } +} + +func TestScanRepoRunE_IncludeSBOMFilesBelowOneIsRejected(t *testing.T) { + for _, value := range []string{"0", "-3"} { + t.Run(value, func(t *testing.T) { + t.Cleanup(func() { resetIncludeSBOMFilesFlag(t) }) + if err := scanRepoCmd.Flags().Set("include-sbom-files", value); err != nil { + t.Fatalf("set flag: %v", err) + } + + // No mock API: the check must fail before any network call. + err := scanRepoCmd.RunE(scanRepoCmd, []string{t.TempDir()}) + + if err == nil || !strings.Contains(err.Error(), "invalid --include-sbom-files value") { + t.Fatalf("expected an --include-sbom-files validation error, got: %v", err) + } + }) + } +} + +func TestIncludeSBOMFilesFlagParsing(t *testing.T) { + t.Cleanup(func() { resetIncludeSBOMFilesFlag(t) }) + + cmd := scanRepoCmd + if err := cmd.ParseFlags([]string{"--include-sbom-files", "20", "."}); err != nil { + t.Fatalf("parse: %v", err) + } + if includeSBOMFiles != 20 { + t.Errorf("includeSBOMFiles = %d, want 20", includeSBOMFiles) + } + if args := cmd.Flags().Args(); len(args) != 1 || args[0] != "." { + t.Errorf("path argument = %v, want [.]", args) + } + + resetIncludeSBOMFilesFlag(t) + if err := cmd.ParseFlags([]string{"--include-sbom-files"}); err == nil { + t.Error("expected an error when --include-sbom-files has no value") + } +} + +func TestIncludeSBOMFilesIsARepoOnlyFlag(t *testing.T) { + if scanRepoCmd.Flags().Lookup("include-sbom-files") == nil { + t.Error("scan repo must have --include-sbom-files") + } + if scanImageCmd.Flags().Lookup("include-sbom-files") != nil { + t.Error("scan image must not have --include-sbom-files") + } + if scanCmd.PersistentFlags().Lookup("include-sbom-files") != nil { + t.Error("--include-sbom-files must not be shared by every scan subcommand") + } +} diff --git a/internal/model/finding.go b/internal/model/finding.go index 7cd8c9c..df382ef 100644 --- a/internal/model/finding.go +++ b/internal/model/finding.go @@ -179,6 +179,10 @@ type IngestScanStartRequest struct { // ImageRef names the scanned image, such as python:3.12-slim, at the root // of its BOMs. Sent on image scans with --bom only. ImageRef string `json:"image_ref,omitempty"` + // IncludeSBOMFiles asks the backend to scan the repository's SBOM files + // alongside the code, at most this many. Omitted (0) without + // --include-sbom-files, so the body is unchanged for every other scan. + IncludeSBOMFiles int `json:"include_sbom_files,omitempty"` } // IngestStatusData represents the status information for a scan ingestion. diff --git a/internal/scan/repo/repo.go b/internal/scan/repo/repo.go index 5c4abc7..8436f9d 100644 --- a/internal/scan/repo/repo.go +++ b/internal/scan/repo/repo.go @@ -41,6 +41,7 @@ type Scanner struct { includeFiles *FileList sbomVEXOpts *scan.SBOMVEXOptions detectGitHints bool + sbomFilesLimit int } // NewScanner creates a new repository scanner with the given configuration. @@ -82,6 +83,13 @@ func (s *Scanner) WithSBOMVEXOptions(opts *scan.SBOMVEXOptions) *Scanner { return s } +// WithSBOMFiles asks the backend to scan the repository's SBOM files alongside +// the code, at most limit of them (the backend may lower it further). +func (s *Scanner) WithSBOMFiles(limit int) *Scanner { + s.sbomFilesLimit = limit + return s +} + // WithGitHints enables best-effort git-hint detection (repo_name, git_sha, // origin_sha) for incremental-scan baseline resolution (PPSC-1215). Callers // should only enable this for full-repo-root scans — not for --changed or @@ -220,6 +228,8 @@ func (s *Scanner) Scan(ctx context.Context, path string) (*model.ScanResult, err Filename: filepath.Base(absPath) + ".tar.gz", Data: tmpFile, Size: tarInfo.Size(), + + IncludeSBOMFiles: s.sbomFilesLimit, } if s.sbomVEXOpts != nil { ingestOpts.GenerateSBOM = s.sbomVEXOpts.GenerateSBOM diff --git a/internal/scan/sbom_vex.go b/internal/scan/sbom_vex.go index cde2a8c..e6e0457 100644 --- a/internal/scan/sbom_vex.go +++ b/internal/scan/sbom_vex.go @@ -129,6 +129,11 @@ func (d *SBOMVEXDownloader) Download(ctx context.Context, scanID, artifactName s } } + if msg, ok := results.SBOMScanWarning(); ok { + cli.PrintWarning(msg) + fmt.Fprintln(os.Stderr) + } + if msg, skipped := results.SkipMessage(); skipped { cli.PrintWarningf("Scanner skipped: %s", msg) fmt.Fprintln(os.Stderr) diff --git a/internal/scan/sbom_vex_test.go b/internal/scan/sbom_vex_test.go index 181670e..b8c5fa4 100644 --- a/internal/scan/sbom_vex_test.go +++ b/internal/scan/sbom_vex_test.go @@ -506,6 +506,49 @@ func TestSBOMVEXDownloader_Download(t *testing.T) { } }) + t.Run("prints a warning when some SBOM files were not scanned", func(t *testing.T) { + skipMsg := "Repository too large for AI-based scanning." + + server := testutil.NewTestServer(t, func(w http.ResponseWriter, _ *http.Request) { + response := api.ArtifactScanResultsResponse{ + ScanStatus: "COMPLETED", + Results: map[string]string{}, + SkipReason: &skipMsg, + SBOMScanStatus: "PARTIAL", + SBOMScanReasons: []string{"file_limit_exceeded"}, + SBOMSkippedFiles: []api.SkippedSBOMFile{{Path: "z/bom.json", Reason: "file_limit_exceeded"}}, + SBOMSkippedCount: 1, + } + testutil.JSONResponse(t, w, http.StatusOK, response) + }) + + httpClient := httpclient.NewClient(httpclient.Config{Timeout: 5 * time.Second}) + client, err := api.NewClient(server.URL, testutil.NewTestAuthProvider("token123"), false, 0, api.WithHTTPClient(httpClient), api.WithAllowLocalURLs(true)) + if err != nil { + t.Fatalf("NewClient failed: %v", err) + } + + // No SBOM/VEX download requested: the warning must still appear, and a + // scanner-skip message alongside it is not lost. + downloader := NewSBOMVEXDownloader(client, "tenant-123", nil) + + stderrOut := testutil.CaptureStderr(t, func() { + if _, err := downloader.Download(context.Background(), "scan-456", "test-artifact"); err != nil { + t.Fatalf("Download failed: %v", err) + } + }) + + if !strings.Contains(stderrOut, "SBOM scan incomplete: 1 SBOM file(s) were not scanned") { + t.Errorf("expected the SBOM warning, got: %q", stderrOut) + } + if !strings.Contains(stderrOut, "z/bom.json") { + t.Errorf("expected the skipped path, got: %q", stderrOut) + } + if !strings.Contains(stderrOut, "Scanner skipped:") { + t.Errorf("expected the scanner-skip warning too, got: %q", stderrOut) + } + }) + t.Run("prints skip reason when scanner was skipped", func(t *testing.T) { skipMsg := "Repository too large for AI-based scanning (6203 files exceeds the 5000-file limit)." diff --git a/internal/testutil/mockapi.go b/internal/testutil/mockapi.go index 03641e3..bb83c5f 100644 --- a/internal/testutil/mockapi.go +++ b/internal/testutil/mockapi.go @@ -2,6 +2,7 @@ package testutil import ( + "io" "net/http" "strings" "sync/atomic" @@ -47,6 +48,12 @@ type MockAPIConfig struct { // OnBOMDownload, when set, runs before a /_bom/ download is answered, // such as to cancel the scan's context mid-download. OnBOMDownload func(r *http.Request) + // OnScanRequest, when set, receives the raw POST /api/v1/ingest/scan body + // so tests can assert what the CLI sent. + OnScanRequest func(body []byte) + // SBOMScan, when set, is merged into the GET /api/v1/ingest/results body + // (sbom_scan_status, sbom_skipped_files, ...). + SBOMScan map[string]interface{} } // NewMockScanServer creates a mock Armis API server for integration testing. @@ -136,6 +143,13 @@ func createMockHandler(t *testing.T, config MockAPIConfig) http.HandlerFunc { // POST /api/v1/ingest/scan — confirms upload and triggers scan. if strings.Contains(r.URL.Path, "/api/v1/ingest/scan") && r.Method == http.MethodPost { AssertHasAuthorization(t, r) + if config.OnScanRequest != nil { + body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) + if err != nil { + t.Errorf("reading /ingest/scan body: %v", err) + } + config.OnScanRequest(body) + } JSONResponse(t, w, http.StatusOK, model.IngestUploadResponse{ ScanID: config.ScanID, ScanStatus: "INITIATED", @@ -213,6 +227,9 @@ func createMockHandler(t *testing.T, config MockAPIConfig) http.HandlerFunc { if config.BOMSummary != nil { body["bom_summary"] = config.BOMSummary } + for key, value := range config.SBOMScan { + body[key] = value + } JSONResponse(t, w, http.StatusOK, body) return }