Skip to content
Open
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
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
76 changes: 76 additions & 0 deletions internal/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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.<type>.status. These mirror the
Expand Down Expand Up @@ -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) {
Expand All @@ -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"
Expand Down
49 changes: 49 additions & 0 deletions internal/api/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
109 changes: 109 additions & 0 deletions internal/api/sbom_scan_warning_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
28 changes: 27 additions & 1 deletion internal/cmd/scan_repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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.
Expand All @@ -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)
Expand Down Expand Up @@ -107,6 +116,9 @@ var scanRepoCmd = &cobra.Command{
if pollInterval > 0 {
scanner = scanner.WithPollInterval(pollInterval)
}
if includeSBOMFiles > 0 {
scanner = scanner.WithSBOMFiles(includeSBOMFiles)
}

warnOnUnusedSBOMVEXFlags()
warnOnUnusedBOMFlags()
Expand Down Expand Up @@ -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
}
Loading
Loading