// 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"` SarifPath string `json:"sarif_path,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, ) (*ScanResult, error) { result := &ScanResult{} source = withoutCITooling(source) // Run Trivy filesystem scan critical, high, medium, err := m.runTrivy(ctx, source) 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) 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. if iacScan != "" && iacScan != "none" { iacCritical, iacHigh, err := m.runTrivyConfig(ctx, source) if err != nil { return nil, fmt.Errorf("trivy config (iac misconfig) scan failed: %w", err) } result.IacCritical = iacCritical result.IacHigh = iacHigh } // 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.58.1"). WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")) if registryUsername != "" && registryPassword != nil { ctr = ctr. WithEnvVariable("TRIVY_USERNAME", registryUsername). WithSecretVariable("TRIVY_PASSWORD", registryPassword) } report, err := ctr.WithExec(args).File(reportPath).Contents(ctx) if err != nil { return nil, fmt.Errorf("trivy image scan of %s failed: %w", imageRef, 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", imageRef, result); err != nil { return nil, fmt.Errorf("posting image scan to API failed: %w", err) } } result.Success = true return result, nil } // 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") } // 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{ "secret_count": result.SecretCount, "dast_high": 0, "dast_critical": 0, "sast_errors": 0, "iac_critical": result.IacCritical, "iac_high": result.IacHigh, "sbom_present": false, "signed": false, }, } if imageRef != "" { payload["report_data"].(map[string]any)["image_ref"] = imageRef } 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.58.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.58.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) (int, int, int, error) { const reportPath = "/tmp/trivy-results.json" trivy := dag.Container(). From("aquasec/trivy:0.58.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([]string{ "trivy", "fs", "--format", "json", "--severity", "CRITICAL,HIGH,MEDIUM", "--exit-code", "0", "--output", reportPath, ".", }) 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. func (m *SecurityScan) runTrivyConfig(ctx context.Context, source *dagger.Directory) (int, int, error) { const reportPath = "/tmp/trivy-config.json" trivy := dag.Container(). From("aquasec/trivy:0.58.1"). // Persist Trivy's DB across runs (avoids re-downloading it). WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")). WithDirectory("/src", source). WithWorkdir("/src"). WithExec([]string{ "trivy", "config", "--format", "json", "--severity", "CRITICAL,HIGH,MEDIUM", "--exit-code", "0", "--output", reportPath, ".", }) report, err := trivy.File(reportPath).Contents(ctx) if err != nil { return 0, 0, fmt.Errorf("read trivy config output: %w", err) } critical, high, _ := countTrivySeverities(report) return critical, high, nil } // 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.58.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) (int, error) { const reportPath = "/tmp/gitleaks-results.sarif" gitleaks := dag.Container(). From("zricethezav/gitleaks:v8.21.2"). WithDirectory("/src", source). WithWorkdir("/src"). WithExec([]string{ "gitleaks", "detect", "--source", ".", "--report-format", "sarif", "--report-path", reportPath, "--exit-code", "0", }) report, err := gitleaks.File(reportPath).Contents(ctx) if err != nil { return 0, fmt.Errorf("read gitleaks output: %w", err) } return countSarifResults(report), nil } // 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 }