// Package main implements the IntegraCI iac-scan Dagger module. // // Runs Infrastructure-as-Code (IaC) security scanning over a source directory // (Terraform / Helm / Dockerfile / Kubernetes manifests), counts // misconfigurations by severity, and optionally POSTs the result to the // IntegraCI API. Engine-agnostic: callable from any CI engine via // `dagger call`. // // Supported tools (each runs the vendor's canonical CLI inside its official // container image): // // trivy aquasec/trivy trivy config --format json . // checkov bridgecrew/checkov checkov -d . -o json // none no-op skip // // Usage: // // dagger call scan --source . --api-url http://localhost:8000 --token env:TOKEN --service-id $SVC_ID // dagger call scan --source . --tool checkov // dagger call scan --source . --tool none package main import ( "bytes" "context" "dagger/iac-scan/internal/dagger" "encoding/json" "fmt" "net/http" "strings" "time" ) // IacScan is the IntegraCI Infrastructure-as-Code scanning module. type IacScan struct{} // ScanResult contains the output of an IaC scan. type ScanResult struct { Tool string `json:"tool"` Findings int `json:"findings"` Critical int `json:"critical"` High int `json:"high"` Medium int `json:"medium"` Low int `json:"low"` Report string `json:"report,omitempty"` Skipped bool `json:"skipped"` Success bool `json:"success"` // Suppression files the scan of record removed from the scanned copy. IgnoredSuppressions []string `json:"ignored_suppressions,omitempty"` } // Scan runs an IaC misconfiguration pass over the source directory with the // selected tool, counts findings by severity, and optionally POSTs the result // to the IntegraCI API. Mirrors sast-scan.Scan's reporting contract. func (m *IacScan) Scan( ctx context.Context, // Source directory to scan (Terraform / Helm / Dockerfile / K8s manifests) source *dagger.Directory, // IaC tool: trivy | checkov | none // +optional // +default="trivy" tool string, // IntegraCI API URL for posting results // +optional apiURL string, // JWT token for API authentication // +optional token *dagger.Secret, // Service ID to link scan results // +optional serviceID string, // Version (commit SHA / image tag) the scan applies to // +optional version string, // The analysis job of record (ADR-0093 §4, WP-05): the repository's // suppression files (trivy.yaml, .trivyignore[.yaml], .checkov.yaml, ...) // are removed from the scanned copy and Trivy reads no configuration from // the tree. Off for every other caller. // +optional scanOfRecord bool, ) (*ScanResult, error) { result := &ScanResult{Tool: tool} if scanOfRecord { var err error source, result.IgnoredSuppressions, err = dropSuppression(ctx, source, func(ctx context.Context, pattern string) ([]string, error) { return source.Glob(ctx, pattern) }, func(d *dagger.Directory, paths []string) *dagger.Directory { return d.WithoutFiles(paths) }, ) if err != nil { return nil, err } } var ( report string err error ) switch strings.ToLower(tool) { case "none": result.Skipped = true result.Success = true return result, nil case "trivy": report, err = m.runTrivyConfig(ctx, source, scanOfRecord) case "checkov": report, err = m.runCheckov(ctx, source) default: return nil, fmt.Errorf( "unsupported iac tool %q (expected one of: trivy, checkov, none)", tool, ) } if err != nil { return nil, fmt.Errorf("%s iac scan failed: %w", tool, err) } result.Report = report result.Critical = countSeverity(report, "CRITICAL") result.High = countSeverity(report, "HIGH") result.Medium = countSeverity(report, "MEDIUM") result.Low = countSeverity(report, "LOW") result.Findings = result.Critical + result.High + result.Medium + result.Low // POST results to the IntegraCI API when configured. Skipped silently // when apiURL or token is empty so local runs still work. if apiURL != "" && token != nil { if err := m.postResults(ctx, apiURL, token, serviceID, version, result); err != nil { return nil, fmt.Errorf("posting results to API failed: %w", err) } } result.Success = true return result, nil } // runTrivyConfig runs "trivy config" over the source directory in JSON mode. // Trivy exits non-zero when misconfigurations are present; we force // --exit-code 0 and read the JSON report rather than relying on the exit code. func (m *IacScan) runTrivyConfig(ctx context.Context, source *dagger.Directory, scanOfRecord bool) (string, error) { report, err := dag.Container(). From("aquasec/trivy:0.76.1"). // Persist Trivy's misconfig/policy DB across runs (avoids re-downloading it). WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")). WithMountedDirectory("/src", source). WithWorkdir("/src"). WithExec(iacTrivyArgs(scanOfRecord)). File(iacReportPath). Contents(ctx) if err != nil { return "", fmt.Errorf("read trivy config JSON output: %w", err) } return report, nil } const iacReportPath = "/tmp/iac-report.json" // iacTrivyArgs is the `trivy config` argv; the scan of record adds // trustedConfigArgs before the target. func iacTrivyArgs(scanOfRecord bool) []string { return withTrustedConfig([]string{ "trivy", "config", "--format", "json", "--output", iacReportPath, "--exit-code", "0", ".", }, scanOfRecord) } // runCheckov runs Checkov over the source directory in JSON mode. Checkov // exits non-zero when failed checks are present, so we tolerate the exit code // and read the JSON emitted on stdout. func (m *IacScan) runCheckov(ctx context.Context, source *dagger.Directory) (string, error) { c := dag.Container(). From("bridgecrew/checkov:3.2.334"). WithMountedDirectory("/src", source). WithWorkdir("/src"). WithExec([]string{"sh", "-c", "checkov -d . -o json --compact || true"}) return c.Stdout(ctx) } // countSeverity tallies findings of a given severity level from an IaC scan // report. Both Trivy (`"Severity": "HIGH"`) and Checkov (`"severity": "HIGH"`) // emit uppercase severity strings under a severity key; we count occurrences // of that key/value pair, tolerant of the optional space after the colon. // Zero-dep, matching the license-scan / sast-scan substring approach. func countSeverity(report, level string) int { total := 0 for _, key := range []string{`"Severity"`, `"severity"`} { for _, sep := range []string{":", ": "} { total += strings.Count(report, key+sep+`"`+level+`"`) } } return total } // postResults sends the IaC scan result to the IntegraCI generic scan-ingest // endpoint. Shape matches api/app/schemas/scan.py ScanResultCreate: the // per-severity misconfig counts populate the typed columns, and the // iac_critical / iac_high counters are mirrored into report_data (the fields // the deploy OPA gate reads — see deploy_policy_gate.py _build_scan_results). func (m *IacScan) postResults( ctx context.Context, apiURL string, token *dagger.Secret, serviceID string, version string, result *ScanResult, ) error { payload := map[string]any{ "service_id": serviceID, "version": version, "scan_type": "iac", "scanner": result.Tool, "report_format": "json", "findings_count": result.Findings, "critical_count": result.Critical, "high_count": result.High, "medium_count": result.Medium, "low_count": result.Low, "report_data": map[string]any{ "iac_critical": result.Critical, "iac_high": result.High, "ignored_suppressions": result.IgnoredSuppressions, }, } body, err := json.Marshal(payload) if err != nil { return fmt.Errorf("marshal scan payload: %w", err) } endpoint := strings.TrimRight(apiURL, "/") + "/api/v1/scans" req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body)) if err != nil { return fmt.Errorf("build request: %w", err) } req.Header.Set("Content-Type", "application/json") tokenStr, err := token.Plaintext(ctx) if err != nil { return fmt.Errorf("read token secret: %w", err) } req.Header.Set("Authorization", "Bearer "+tokenStr) client := &http.Client{Timeout: 30 * time.Second} resp, err := client.Do(req) if err != nil { return fmt.Errorf("API post to %s failed: %w", endpoint, err) } defer resp.Body.Close() if resp.StatusCode >= 300 { return fmt.Errorf("API post to %s returned %d", endpoint, resp.StatusCode) } return nil }