// Package main implements the IntegraCI security-scan Dagger module. // // Runs Trivy filesystem vuln scan + Gitleaks secret detection + (opt-in) // Trivy static IaC misconfig scan + (opt-in) Trivy CIS-benchmark/hardening // compliance scan + Trivy license scan, outputs SARIF / CycloneDX reports, and // POSTs results to the IntegraCI API. The misconfig and CIS passes are off by // default (--iac-scan none, --cis none) so they never change a pipeline's // baseline until a tenant enables them. // // Usage: // // dagger call scan --source . --api-url http://localhost:8000 --token $TOKEN --service-id $SVC_ID // dagger call scan --source . --iac-scan trivy --api-url ... --token $TOKEN --service-id $SVC_ID // dagger call license-scan --source . --forbidden GPL-2.0,GPL-3.0,AGPL-3.0 // dagger call image-scan --image-ref reg/app:tag --registry-username u --registry-password env://P --api-url ... --token $TOKEN --service-id $SVC_ID package main import ( "bytes" "context" "dagger/security-scan/internal/dagger" "encoding/json" "fmt" "net/http" "regexp" "strings" "time" ) // Trivy writes its JSON with json.MarshalIndent — `"Severity": "HIGH"`, a // space after the colon (measured on aquasec/trivy:0.58.1). The counters below // once matched `"Severity":"` with no space and so counted ZERO findings in // every real report: every Trivy scan the pipelines posted read clean, and the // deploy gate's CVE and licence thresholds never saw a thing. Whitespace- // tolerant patterns match both the indented and the compact form. var ( severityPattern = regexp.MustCompile(`"Severity"\s*:\s*"([A-Za-z]+)"`) licensePattern = regexp.MustCompile(`"License"\s*:\s*"([^"]*)"`) ruleIDPattern = regexp.MustCompile(`"RuleID"\s*:\s*"`) ) // SecurityScan is the IntegraCI security scanning module. type SecurityScan struct{} // ScanResult contains the output of a security scan. type ScanResult struct { TrivyFindings int `json:"trivy_findings"` GitleaksFindings int `json:"gitleaks_findings"` LicenseFindings int `json:"license_findings"` ForbiddenFound int `json:"forbidden_found"` Critical int `json:"critical"` High int `json:"high"` Medium int `json:"medium"` SecretCount int `json:"secret_count"` IacCritical int `json:"iac_critical"` IacHigh int `json:"iac_high"` // IacScanned is true only when the IaC misconfig scan RAN. The zeros in // iac_critical/iac_high are posted either way, so the security verdict // (ADR-0093) reads this flag to tell "nothing found" from "not scanned". IacScanned bool `json:"iac_scanned"` // Suppression files the scan of record removed from the scanned copy // (ADR-0093 §4). Empty for every other scan. IgnoredSuppressions []string `json:"ignored_suppressions,omitempty"` SarifPath string `json:"sarif_path,omitempty"` // Trivy's VulnerabilityDB.UpdatedAt for an image scan (vulndb.go); empty // when Trivy reported none. VulnDBUpdatedAt string `json:"vuln_db_updated_at,omitempty"` Success bool `json:"success"` } // LicenseReport summarises Trivy's license scan output. type LicenseReport struct { Total int `json:"total"` Forbidden int `json:"forbidden"` ForbiddenList []string `json:"forbidden_list"` UnknownLicenses int `json:"unknown_licenses"` JSONReport string `json:"json_report"` Pass bool `json:"pass"` } // Scan runs Trivy vulnerability scan + Gitleaks secret detection. func (m *SecurityScan) Scan( ctx context.Context, // Source directory to scan source *dagger.Directory, // 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, // Static IaC misconfig scan: "trivy" (trivy config) or "none". // Opt-in (default none) so enabling it never changes a pipeline's baseline. // +optional // +default="none" iacScan string, // CIS Benchmark / hardening scan: "trivy" (trivy config --compliance // docker-cis) or "none". Opt-in; failed CIS controls fold into iac_high. // +optional // +default="none" cis string, // The analysis job of record (ADR-0093 §4, WP-05): suppression files the // repository ships are removed from the scanned copy, gitleaks ignores // `gitleaks:allow`, and what was ignored is posted as information. Off for // every other caller, so branch and pull request jobs scan as before. // +optional scanOfRecord bool, ) (*ScanResult, error) { result := &ScanResult{} source = withoutCITooling(source) if scanOfRecord { var err error source, result.IgnoredSuppressions, err = withoutSuppression(ctx, source) if err != nil { return nil, err } } // Run Trivy filesystem scan critical, high, medium, err := m.runTrivy(ctx, source, scanOfRecord) if err != nil { return nil, fmt.Errorf("trivy scan failed: %w", err) } result.Critical = critical result.High = high result.Medium = medium result.TrivyFindings = critical + high + medium // Run Gitleaks secret detection secretCount, err := m.runGitleaks(ctx, source, scanOfRecord) if err != nil { return nil, fmt.Errorf("gitleaks failed: %w", err) } result.SecretCount = secretCount result.GitleaksFindings = secretCount // Optional static IaC misconfig scan (opt-in). trivy config detects // insecure Dockerfiles / k8s manifests / Terraform (open ports, missing // encryption, privileged containers, ...). Counts land in report_data as // iac_critical/iac_high, which the deploy OPA gate reads. When disabled // they stay 0 — identical to the pre-existing payload, so no flag day — // and iac_scanned stays false, so the security verdict (ADR-0093) reads // those zeros as "not scanned", never as "nothing found". if iacScan != "" && iacScan != "none" { iacCritical, iacHigh, inline, err := m.runTrivyConfig(ctx, source, scanOfRecord) if err != nil { return nil, fmt.Errorf("trivy config (iac misconfig) scan failed: %w", err) } result.IgnoredSuppressions = append(result.IgnoredSuppressions, inline...) result.IacCritical = iacCritical result.IacHigh = iacHigh result.IacScanned = true } // Optional CIS Benchmark / hardening scan (opt-in). Trivy's docker-cis // compliance scan technically tests config against CIS controls (closing // the SOP-004 / STD-TI-001 hardening requirement, distinct from the // compliance *mapping* the platform already ships). Failed controls fold // into iac_high so hardening failures gate like IaC misconfig. Off by // default → 0, identical payload, no flag day. if cis != "" && cis != "none" { failed := m.runTrivyCisCompliance(ctx, source) result.IacHigh += failed } // 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 } // ImageScan scans the image the build PUBLISHED — the artifact that is promoted // — for vulnerabilities and embedded secrets, and posts the counts as scanner // "trivy-image". `Scan` looks at the source tree; an image carries its base // layers and whatever the build copied in, which a source scan cannot see. // // The image is pulled from the registry by reference, with the build's own // registry credentials, so what is scanned is what the engine will promote. // exit-code 0: gating is the deploy policy gate's job, and it reads these // counts per (scan_type, scanner), so this row cannot hide the source scan's. func (m *SecurityScan) ImageScan( ctx context.Context, // Image reference the build pushed (`/:` or `@sha256:`) imageRef string, // +optional registryUsername string, // +optional registryPassword *dagger.Secret, // Registry without TLS (a tenant Nexus on plain HTTP) // +optional registryInsecure bool, // +optional apiURL string, // +optional token *dagger.Secret, // +optional serviceID string, // Version (commit SHA / image tag) the scan applies to // +optional version string, ) (*ScanResult, error) { if strings.TrimSpace(imageRef) == "" { return nil, fmt.Errorf("image-scan needs --image-ref") } const reportPath = "/tmp/trivy-image.json" args := []string{ "trivy", "image", "--image-src", "remote", "--scanners", "vuln,secret", "--format", "json", "--severity", "CRITICAL,HIGH,MEDIUM", "--exit-code", "0", "--output", reportPath, } if registryInsecure { args = append(args, "--insecure") } args = append(args, imageRef) ctr := dag.Container(). From("aquasec/trivy:0.76.1"). WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")) if registryUsername != "" && registryPassword != nil { ctr = ctr. WithEnvVariable("TRIVY_USERNAME", registryUsername). WithSecretVariable("TRIVY_PASSWORD", registryPassword) } scanned := ctr.WithExec(args) report, err := scanned.File(reportPath).Contents(ctx) if err != nil { return nil, fmt.Errorf("trivy image scan of %s failed: %w", imageRef, err) } // The age of the DB that scan used, read from the same cache with no // network call (ADR-0093 §8). A failure here is not a scan failure: the // platform treats a missing date as `cve = unknown`. versionJSON, _ := scanned.WithExec([]string{"trivy", "version", "--format", "json"}).Stdout(ctx) critical, high, medium := countTrivySeverities(report) result := &ScanResult{ Critical: critical, High: high, Medium: medium, TrivyFindings: critical + high + medium, SecretCount: len(ruleIDPattern.FindAllStringIndex(report, -1)), VulnDBUpdatedAt: vulnDBUpdatedAt(versionJSON), } if apiURL != "" && token != nil { if err := m.postScan(ctx, apiURL, token, serviceID, version, "trivy-image", imageRef, result); err != nil { return nil, fmt.Errorf("posting image scan to API failed: %w", err) } } result.Success = true return result, nil } // ArchiveScan scans the image the build wrote as an OCI ARCHIVE, before // anything is pushed (ADR-0093 §5 step 2, scan before push), and posts the // counts as scanner "trivy-image" -- the same row ImageScan posts after a // push, so the deploy gate and the security verdict read one scanner either // way. The archive's manifest digest rides in report_data.image_ref as // `archive:sha256:`, for the record only: the verdict does NOT match on // it (a caller-chosen digest is never identity, WP-01 review); it reads the // scan by --version, the tag the archive was built as. // // No registry, no credential: the layout is read from the directory the build // exported. Same scanners and severities as ImageScan. func (m *SecurityScan) ArchiveScan( ctx context.Context, // The OCI image layout `standard-build build --archive` exported layout *dagger.Directory, // The archive's manifest digest (standard-build `archive-digest`) archiveDigest string, // +optional apiURL string, // +optional token *dagger.Secret, // +optional serviceID string, // The tag the archive was built as // +optional version string, ) (*ScanResult, error) { if !archiveDigestRE.MatchString(archiveDigest) { return nil, fmt.Errorf("archive-scan: --archive-digest %q is not sha256", archiveDigest) } const reportPath = "/tmp/trivy-image.json" ctr := dag.Container(). From("aquasec/trivy:0.76.1"). WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")). WithDirectory("/layout", layout). // trivy reads an OCI archive (tar of the layout) with --input; the // working directory is empty, so no trivy.yaml / .trivyignore from the // checkout can change what it reports (ADR-0093 §4, condition 3). WithWorkdir("/work"). WithExec([]string{"sh", "-c", "tar -cf /tmp/image.tar -C /layout ."}) report, err := ctr.WithExec([]string{ "trivy", "image", "--input", "/tmp/image.tar", "--scanners", "vuln,secret", "--format", "json", "--severity", "CRITICAL,HIGH,MEDIUM", "--exit-code", "0", "--output", reportPath, }).File(reportPath).Contents(ctx) if err != nil { return nil, fmt.Errorf("trivy scan of the archive %s failed: %w", archiveDigest, err) } critical, high, medium := countTrivySeverities(report) result := &ScanResult{ Critical: critical, High: high, Medium: medium, TrivyFindings: critical + high + medium, SecretCount: len(ruleIDPattern.FindAllStringIndex(report, -1)), } if apiURL != "" && token != nil { if err := m.postScan(ctx, apiURL, token, serviceID, version, "trivy-image", "archive:"+archiveDigest, result); err != nil { return nil, fmt.Errorf("posting archive scan to API failed: %w", err) } } result.Success = true return result, nil } // archiveDigestRE is the manifest digest grammar (lower-case sha256). var archiveDigestRE = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`) // withoutCITooling removes what the PIPELINE put into the checkout before the // scan: the dagger CLI (`./bin/dagger`, installed by every stage's install // script) and the platform's module mirror (`./.integraci-modules`). They are // the platform's tools, not the tenant's code, and scanning them charged every // tenant with the CVEs of a Go binary and its module graph — measured // 2026-09-26: a repository with no dependencies at all reported 13 HIGH on two // different commits, identically. Only these two exact paths go; an // application's own `bin/` stays in scope. func withoutCITooling(source *dagger.Directory) *dagger.Directory { return source.WithoutFile("bin/dagger").WithoutDirectory(".integraci-modules") } // suppressionFiles are the files a scanner reads from the tree it scans and // obeys: each one can silence a finding in the very change that adds it. The // scan of record (ADR-0093 §4, WP-05) removes them, wherever they are in the // tree, and reports which. Suppression goes through the platform's waivers. var suppressionFiles = []string{ ".gitleaksignore", ".gitleaks.toml", ".trivyignore", ".trivyignore.yaml", "trivy.yaml", "trivy.yml", ".semgrepignore", ".checkov.yaml", ".checkov.yml", // Trivy loads ./trivy-secret.yaml by default; it can disable built-in // secret rules or allow-list a path. "trivy-secret.yaml", "trivy-secret.yml", } // withoutSuppression removes every suppressionFiles entry from source and // returns the paths it removed. A tree that cannot be listed is an error: a // scan of record that could not drop the suppressions is not one. func withoutSuppression(ctx context.Context, source *dagger.Directory) (*dagger.Directory, []string, error) { return 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) }, ) } // dropSuppression is withoutSuppression over any tree: glob lists it by // pattern, without returns it minus paths. A test passes an in-memory tree, // so the DIRECTORY that comes back is checked, not just the reported names. func dropSuppression[T any]( ctx context.Context, source T, glob func(context.Context, string) ([]string, error), without func(T, []string) T, ) (T, []string, error) { var found []string for _, name := range suppressionFiles { for _, pattern := range []string{name, "**/" + name} { matches, err := glob(ctx, pattern) if err != nil { var none T return none, nil, fmt.Errorf("list %s for the scan of record: %w", name, err) } found = append(found, matches...) } } seen := map[string]bool{} var removed []string for _, path := range found { if !seen[path] { seen[path] = true removed = append(removed, path) } } if len(removed) == 0 { return source, nil, nil } return without(source, removed), removed, nil } // trustedConfigArgs are the Trivy flags the scan of record adds: no // configuration, ignore file or secret configuration is read from the tree // it scans (Trivy 0.76 docs, "Disabling configuration files"). The files are // removed from the scanned copy too; these flags also cover a renamed path a // later Trivy might look up by default. func trustedConfigArgs(scanOfRecord bool) []string { if !scanOfRecord { return nil } return []string{"--config=", "--ignorefile=", "--secret-config="} } // inlineIgnoreScript neutralises Trivy/tfsec inline ignore comments // (`#trivy:ignore:AVD-...`, `#tfsec:ignore:...`) in the IaC files of the // scanned copy, and prints each file it changed. Trivy has no flag that turns // inline ignores off, and a change could otherwise silence its own // misconfiguration next to the resource it adds (ADR-0093 §4). Only the // container's copy is rewritten. POSIX find/grep/sed: runs on the Trivy // image's busybox. const inlineIgnoreScript = `find . -type f \( -name '*.tf' -o -name '*.tf.json' -o -name '*.hcl' ` + `-o -name '*.yaml' -o -name '*.yml' -o -name '*.json' -o -name '*.tpl' ` + `-o -name 'Dockerfile*' -o -name '*.dockerfile' -o -name 'Containerfile*' \) ` + `-exec grep -lE '(trivy|tfsec):ignore' {} \; ` + `-exec sed -i -E 's/(trivy|tfsec):ignore/\1-ignore-disabled-by-scan-of-record/g' {} \;` // inlineIgnoredFiles turns inlineIgnoreScript's output into report entries. func inlineIgnoredFiles(out string) []string { var files []string for _, line := range strings.Split(out, "\n") { line = strings.TrimPrefix(strings.TrimSpace(line), "./") if line != "" { files = append(files, "inline:"+line) } } return files } // postResults sends the security-scan result back to the IntegraCI scans // endpoint. Shape matches api/app/schemas/scan.py ScanResultCreate: typed // severity columns plus the report_data counters the deploy OPA gate reads // (see deploy.py _build_scan_results). func (m *SecurityScan) postResults( ctx context.Context, apiURL string, token *dagger.Secret, serviceID string, version string, result *ScanResult, ) error { return m.postScan(ctx, apiURL, token, serviceID, version, "trivy", "", result) } // postScan posts one scanner's counts. `scanner` keeps the source scan // ("trivy") and the image scan ("trivy-image") apart for the deploy gate. func (m *SecurityScan) postScan( ctx context.Context, apiURL string, token *dagger.Secret, serviceID string, version string, scanner string, imageRef string, result *ScanResult, ) error { payload := map[string]any{ "service_id": serviceID, "version": version, "scan_type": "container", "scanner": scanner, "report_format": "json", "findings_count": result.Critical + result.High + result.Medium, "critical_count": result.Critical, "high_count": result.High, "medium_count": result.Medium, "report_data": map[string]any{ "ignored_suppressions": result.IgnoredSuppressions, "secret_count": result.SecretCount, "dast_high": 0, "dast_critical": 0, "sast_errors": 0, "iac_critical": result.IacCritical, "iac_high": result.IacHigh, "iac_scanned": result.IacScanned, "sbom_present": false, "signed": false, }, } if imageRef != "" { payload["report_data"].(map[string]any)["image_ref"] = imageRef } if result.VulnDBUpdatedAt != "" { // security/services/vuln_db_freshness.py VULN_DB_UPDATED_AT_KEY. payload["report_data"].(map[string]any)["vuln_db_updated_at"] = result.VulnDBUpdatedAt } 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 } // LicenseScan runs Trivy in license-scan mode and fails when forbidden // licenses are detected. Default forbidden list mirrors the "no GPL in // production" policy from the Phase 5 PRD (5.6). func (m *SecurityScan) LicenseScan( ctx context.Context, // Source directory to scan source *dagger.Directory, // Comma-separated list of forbidden SPDX license identifiers // +optional // +default="GPL-2.0,GPL-3.0,AGPL-3.0,LGPL-3.0,SSPL-1.0,Commons-Clause" forbidden string, // Exit non-zero when forbidden licenses are found // +optional // +default=true failOnForbidden bool, ) (*LicenseReport, error) { forbiddenList := strings.Split(forbidden, ",") for i, s := range forbiddenList { forbiddenList[i] = strings.TrimSpace(s) } trivy := dag.Container(). From("aquasec/trivy:0.76.1"). // Persist Trivy's vulnerability DB across runs (avoids re-downloading it). WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")). WithDirectory("/src", withoutCITooling(source)). WithWorkdir("/src"). WithExec([]string{ "trivy", "fs", "--scanners", "license", "--format", "json", "--license-full", "--severity", "UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL", "--exit-code", "0", "--output", "/tmp/trivy-licenses.json", ".", }) if _, err := trivy.Stdout(ctx); err != nil { return nil, fmt.Errorf("trivy license scan failed: %w", err) } jsonOut, err := trivy.File("/tmp/trivy-licenses.json").Contents(ctx) if err != nil { return nil, fmt.Errorf("read trivy license output: %w", err) } report := classifyLicenses(jsonOut, forbiddenList) report.JSONReport = jsonOut if failOnForbidden && report.Forbidden > 0 { return report, fmt.Errorf( "license scan: %d forbidden license(s) detected: %s", report.Forbidden, strings.Join(report.ForbiddenList, ", "), ) } return report, nil } // classifyLicenses parses Trivy's JSON and returns a summary. We avoid // pulling in a JSON schema dependency; the surface area we care about is // just License + PkgName. func classifyLicenses(rawJSON string, forbidden []string) *LicenseReport { report := &LicenseReport{ForbiddenList: []string{}, Pass: true} forbiddenSet := map[string]bool{} for _, l := range forbidden { if l != "" { forbiddenSet[strings.ToUpper(l)] = true } } // Every "License" value in the report (whitespace-tolerant, see // licensePattern). for _, match := range licensePattern.FindAllStringSubmatch(rawJSON, -1) { license := match[1] if license == "" { continue } report.Total++ upper := strings.ToUpper(license) if upper == "UNKNOWN" { report.UnknownLicenses++ continue } for f := range forbiddenSet { if strings.Contains(upper, f) { report.Forbidden++ report.ForbiddenList = append(report.ForbiddenList, license) report.Pass = false break } } } return report } // Sarif runs Trivy's filesystem vulnerability scan and returns the report as // SARIF, for a pipeline to export and archive (#2143 phase 2): // // dagger call sarif --source=. export --path=integraci-sarif/trivy.sarif // // `--scanners vuln` only: secrets are reported by the secret-scan module's // redacted SARIF, and a second copy of a matched secret in an archived report // is a leak. Nothing is posted; Scan remains the step that reports. func (m *SecurityScan) Sarif( ctx context.Context, // Source directory to scan source *dagger.Directory, ) (*dagger.File, error) { const reportPath = "/tmp/trivy-results.sarif" report := dag.Container(). From("aquasec/trivy:0.76.1"). WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")). WithDirectory("/src", source.WithoutFile("bin/dagger").WithoutDirectory(".integraci-modules")). WithWorkdir("/src"). WithExec([]string{ "trivy", "fs", "--scanners", "vuln", "--format", "sarif", "--exit-code", "0", "--output", reportPath, ".", }). File(reportPath) if _, err := report.Contents(ctx); err != nil { return nil, fmt.Errorf("trivy sarif failed: %w", err) } return report, nil } // runTrivy runs a Trivy filesystem scan and returns the critical/high/medium // vulnerability counts parsed from the JSON report. Trivy may exit non-zero // when vulnerabilities are present, so counts are read from the report file // rather than the exit code. func (m *SecurityScan) runTrivy(ctx context.Context, source *dagger.Directory, scanOfRecord bool) (int, int, int, error) { const reportPath = "/tmp/trivy-results.json" trivy := dag.Container(). From("aquasec/trivy:0.76.1"). // Persist Trivy's vulnerability DB across runs (avoids re-downloading it). WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")). WithDirectory("/src", source). WithWorkdir("/src"). WithExec(trivyArgs("fs", reportPath, scanOfRecord)) report, err := trivy.File(reportPath).Contents(ctx) if err != nil { return 0, 0, 0, fmt.Errorf("read trivy output: %w", err) } critical, high, medium := countTrivySeverities(report) return critical, high, medium, nil } // runTrivyConfig runs a Trivy static misconfiguration scan (`trivy config`) // over the source tree and returns the critical/high misconfig counts parsed // from the JSON report. Reuses countTrivySeverities — trivy config emits the // same "Severity":"" shape as the vuln scan. exit-code 0 so findings // don't fail the container step; gating is the deploy OPA gate's job. // // For the scan of record, inline ignore comments are neutralised first // (inlineIgnoreScript) and the files that carried one are returned, so they // are posted as `ignored_suppressions`. func (m *SecurityScan) runTrivyConfig(ctx context.Context, source *dagger.Directory, scanOfRecord bool) (int, int, []string, error) { const reportPath = "/tmp/trivy-config.json" base := dag.Container(). From("aquasec/trivy:0.76.1"). // Persist Trivy's DB across runs (avoids re-downloading it). WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")). WithDirectory("/src", source). WithWorkdir("/src") var inline []string if scanOfRecord { base = base.WithExec([]string{"sh", "-c", inlineIgnoreScript}) out, err := base.Stdout(ctx) if err != nil { // Not "nothing to neutralise": a scan of record that could not // drop the inline ignores is not one. return 0, 0, nil, fmt.Errorf("neutralise inline ignores for the scan of record: %w", err) } inline = inlineIgnoredFiles(out) } trivy := base.WithExec(trivyArgs("config", reportPath, scanOfRecord)) report, err := trivy.File(reportPath).Contents(ctx) if err != nil { return 0, 0, nil, fmt.Errorf("read trivy config output: %w", err) } critical, high, _ := countTrivySeverities(report) return critical, high, inline, nil } // trivyArgs is the argv of `trivy fs` / `trivy config` with a JSON report at // reportPath; the scan of record adds trustedConfigArgs. func trivyArgs(sub, reportPath string, scanOfRecord bool) []string { args := []string{ "trivy", sub, "--format", "json", "--severity", "CRITICAL,HIGH,MEDIUM", "--exit-code", "0", "--output", reportPath, } args = append(args, trustedConfigArgs(scanOfRecord)...) return append(args, ".") } // runTrivyCisCompliance runs `trivy config --compliance docker-cis-1.6.0` over // the source and returns the number of FAILED CIS controls. exit-code 0 so // failures don't fail the container step; gating is the deploy gate's job. func (m *SecurityScan) runTrivyCisCompliance(ctx context.Context, source *dagger.Directory) int { out, _ := dag.Container(). From("aquasec/trivy:0.76.1"). WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")). WithDirectory("/src", source). WithWorkdir("/src"). WithExec([]string{ "trivy", "config", "--compliance", "docker-cis-1.6.0", "--report", "summary", "--format", "json", "--exit-code", "0", ".", }). Stdout(ctx) // Trivy's compliance report marks each control PASS/FAIL; counting FAIL // statuses is a zero-dep proxy for failed CIS controls. return strings.Count(out, `"FAIL"`) + strings.Count(out, `"status":"FAIL"`) } // runGitleaks runs Gitleaks secret detection and returns the number of // detected secrets, parsed from the SARIF report (one "ruleId" per finding). func (m *SecurityScan) runGitleaks(ctx context.Context, source *dagger.Directory, ignoreInlineAllow bool) (int, error) { const reportPath = "/tmp/gitleaks-results.sarif" gitleaks := dag.Container(). From("zricethezav/gitleaks:v8.21.2"). WithDirectory("/src", source). WithWorkdir("/src"). WithExec(gitleaksArgs(reportPath, ignoreInlineAllow)) report, err := gitleaks.File(reportPath).Contents(ctx) if err != nil { return 0, fmt.Errorf("read gitleaks output: %w", err) } return countSarifResults(report), nil } // gitleaksArgs is the gitleaks argv. For the scan of record it also ignores // inline `gitleaks:allow` comments: a change could otherwise mark its own // secret allowed (ADR-0093 §4). func gitleaksArgs(reportPath string, ignoreInlineAllow bool) []string { args := []string{ "gitleaks", "detect", "--source", ".", "--report-format", "sarif", "--report-path", reportPath, "--exit-code", "0", } if ignoreInlineAllow { args = append(args, "--ignore-gitleaks-allow") } return args } // countTrivySeverities tallies CRITICAL/HIGH/MEDIUM occurrences from Trivy's // JSON report: one "Severity" per finding (see severityPattern for why the // match is whitespace-tolerant). func countTrivySeverities(rawJSON string) (critical, high, medium int) { for _, match := range severityPattern.FindAllStringSubmatch(rawJSON, -1) { switch strings.ToUpper(match[1]) { case "CRITICAL": critical++ case "HIGH": high++ case "MEDIUM": medium++ } } return critical, high, medium } // countSarifResults counts findings in a SARIF document by tallying // "ruleId" occurrences (one per result). Zero-dep, matching sast-scan. func countSarifResults(report string) int { count := 0 idx := 0 for { k := strings.Index(report[idx:], `"ruleId":`) if k < 0 { break } count++ idx += k + len(`"ruleId":`) } return count }