// Package main implements the IntegraCI secret-scan Dagger module. // // Catches committed credentials/keys before they ship — a best-practice // gate every service should run regardless of CI engine. Translates the // build_secret_scan_step intent from the GitHub-Actions security pipeline // adapter into engine-agnostic container-exec recipes. // // Supported tools (mirrors governance.secret_scan): // // gitleaks — zricethezav/gitleaks, fast, no token (default) // trufflehog — trufflesecurity/trufflehog, verified+unknown results // detect-secrets — Yelp detect-secrets baseline scan (python image) // none — no-op skip (governance.secret_scan=none) // // Usage: // // dagger call scan --source . // dagger call scan --source . --tool trufflehog // dagger call scan --source . --tool detect-secrets // dagger call scan --source . --tool none package main import ( "context" "dagger/secret-scan/internal/dagger" "fmt" "strings" ) // SecretScan is the IntegraCI secret-scanning module. type SecretScan struct{} // ScanResult is the normalised output of any secret-scan tool we run. type ScanResult struct { Tool string `json:"tool"` // gitleaks | trufflehog | detect-secrets | none Skipped bool `json:"skipped"` // true for the "none" no-op branch Findings int `json:"findings"` // best-effort count of detected secrets Report string `json:"report"` // raw tool stdout/report Pass bool `json:"pass"` // false when secrets were detected Error string `json:"error,omitempty"` // failure detail, if any } // Scan runs the selected secret-detection tool over the source tree. // // Each tool runs its canonical CLI inside its official image, and each argv // NAMES THE BINARY. Dagger's WithExec does not use the image ENTRYPOINT, so an // argv that starts at the subcommand (`detect …`, `filesystem …`) is looked up // as an executable of that name and there is none. Measured on a live build: // the Secret Scan stage ran, found nothing, and reported a pass — because the // scanner had never started. // // Findings must not be confused with a scanner that could not run. Every tool // below is therefore configured to exit 0 WHEN IT COMPLETES (gitleaks // `--exit-code 0`; trufflehog without `--fail`) and the exec error is returned // rather than swallowed, so a missing binary, an unpullable image or a crashed // scan fails the stage while a real finding is still surfaced through // Pass/Findings for the caller (any CI engine) to gate on. func (m *SecretScan) Scan( ctx context.Context, // Source directory to scan source *dagger.Directory, // Tool: gitleaks | trufflehog | detect-secrets | none // +optional // +default="gitleaks" tool string, ) (*ScanResult, error) { switch tool { case "none": // Mirrors _comment_skip — governance.secret_scan=none. return &ScanResult{Tool: "none", Skipped: true, Pass: true}, nil case "gitleaks": return runGitleaks(ctx, source) case "trufflehog": return runTruffleHog(ctx, source) case "detect-secrets": return runDetectSecrets(ctx, source) default: return nil, fmt.Errorf("unsupported secret-scan tool: %q (want gitleaks|trufflehog|detect-secrets|none)", tool) } } // Sarif runs gitleaks and returns its SARIF report, for a pipeline to export // and archive (#2143 phase 2): // // dagger call sarif --source=. export --path=integraci-sarif/secrets.sarif // // `--redact` is the point of this function, not a detail: without it the // SARIF carries every matched secret in its snippets, and the archived report // becomes a second, longer-lived copy of the credential it found. Only // gitleaks writes SARIF; the other tools are refused rather than faked. func (m *SecretScan) Sarif( ctx context.Context, // Source directory to scan source *dagger.Directory, // Tool: gitleaks // +optional // +default="gitleaks" tool string, ) (*dagger.File, error) { if tool != "gitleaks" { return nil, fmt.Errorf("secret-scan tool %q writes no SARIF; sarif supports gitleaks", tool) } const reportPath = "/tmp/gitleaks-results.sarif" report := dag.Container(). From("zricethezav/gitleaks:v8.21.2"). WithMountedDirectory("/src", source). WithWorkdir("/src"). WithExec([]string{ "gitleaks", "detect", "--source=/src", "--no-git", "--redact", "--exit-code", "0", "--report-format", "sarif", "--report-path", reportPath, }). File(reportPath) if _, err := report.Contents(ctx); err != nil { return nil, fmt.Errorf("gitleaks sarif failed: %w", err) } return report, nil } // runGitleaks runs `gitleaks detect --source=/src --no-git -v --exit-code 0`. // --no-git scans the working tree (the Dagger-mounted source has no .git), -v // prints each leak. // // The argv NAMES `gitleaks` — this is the same invocation the security-scan // module has always used, and it used to read just `detect` here, which is not // an executable in that image. // // `--exit-code 0` turns gitleaks' documented exit-1-on-findings into a plain // success, which is what makes the remaining error meaningful: with it, a // non-zero exit can only be the scan failing to run, so it is returned instead // of discarded. Leaks are still reported — through Findings/Pass below. func runGitleaks(ctx context.Context, source *dagger.Directory) (*ScanResult, error) { out, err := dag.Container(). From("zricethezav/gitleaks:v8.21.2"). WithMountedDirectory("/src", source). WithWorkdir("/src"). WithExec([]string{"gitleaks", "detect", "--source=/src", "--no-git", "-v", "--exit-code", "0"}). Stdout(ctx) if err != nil { return &ScanResult{ Tool: "gitleaks", Error: fmt.Sprintf("gitleaks could not run: %v", err), }, fmt.Errorf("gitleaks execution failed: %w", err) } result := &ScanResult{Tool: "gitleaks", Report: out} // gitleaks prints a "leaks found: N" / "Finding:" line per secret. result.Findings = strings.Count(out, "Finding:") if result.Findings == 0 { // Fall back to the summary line when -v output is buffered to stderr. result.Findings = countGitleaksSummary(out) } result.Pass = result.Findings == 0 if !result.Pass { result.Error = fmt.Sprintf("gitleaks: %d secret(s) detected", result.Findings) } return result, nil } // runTruffleHog runs `trufflehog filesystem /src --results=verified,unknown`. // // The argv NAMES `trufflehog`: the trufflesecurity image puts the CLI behind an // ENTRYPOINT, which Dagger's WithExec does not use, so the previous argv // starting at `filesystem` asked for an executable of that name. // // `--fail` is deliberately absent. Its only purpose is to make the process exit // non-zero when results are found, which the caller then has to swallow — and // swallowing it also hides the scan never having started. Findings are counted // from the report below, so without --fail a non-zero exit means exactly one // thing: trufflehog could not run. func runTruffleHog(ctx context.Context, source *dagger.Directory) (*ScanResult, error) { out, err := dag.Container(). From("trufflesecurity/trufflehog:3.88.0"). WithMountedDirectory("/src", source). WithWorkdir("/src"). WithExec([]string{"trufflehog", "filesystem", "/src", "--results=verified,unknown"}). Stdout(ctx) if err != nil { return &ScanResult{ Tool: "trufflehog", Error: fmt.Sprintf("trufflehog could not run: %v", err), }, fmt.Errorf("trufflehog execution failed: %w", err) } result := &ScanResult{Tool: "trufflehog", Report: out} // trufflehog emits one finding block per detector hit. result.Findings = strings.Count(out, "Found ") if result.Findings == 0 { result.Findings = strings.Count(out, "DetectorType:") } result.Pass = result.Findings == 0 if !result.Pass { result.Error = fmt.Sprintf("trufflehog: %d secret(s) detected", result.Findings) } return result, nil } // runDetectSecrets installs Yelp detect-secrets and runs a full-tree scan, // producing a baseline JSON on stdout. detect-secrets scan exits 0 even // when secrets are present (the baseline is the artifact), so we parse the // baseline for results. // // This one was already right on both counts the other two got wrong: the argv // starts at `sh`, a real executable in the python image, and the exec error is // returned rather than dropped. Left as the shape the others now match. func runDetectSecrets(ctx context.Context, source *dagger.Directory) (*ScanResult, error) { out, err := dag.Container(). From("python:3.12-slim"). WithMountedDirectory("/src", source). WithWorkdir("/src"). WithExec([]string{ "sh", "-c", "pip install --quiet detect-secrets && detect-secrets scan --all-files", }). Stdout(ctx) if err != nil { return &ScanResult{ Tool: "detect-secrets", Error: fmt.Sprintf("detect-secrets scan failed: %v", err), }, fmt.Errorf("detect-secrets scan failed: %w", err) } result := &ScanResult{Tool: "detect-secrets", Report: out} result.Findings = countDetectSecrets(out) result.Pass = result.Findings == 0 if !result.Pass { result.Error = fmt.Sprintf("detect-secrets: %d potential secret(s) detected", result.Findings) } return result, nil } // ───── helpers (zero-dep, substring-based) ───── // countGitleaksSummary extracts N from gitleaks' "leaks found: N" summary. func countGitleaksSummary(out string) int { for _, line := range strings.Split(out, "\n") { l := strings.ToLower(line) if strings.Contains(l, "leaks found:") { fields := strings.Fields(l) for i, f := range fields { if f == "found:" && i+1 < len(fields) { return atoiSafe(fields[i+1]) } } } } return 0 } // countDetectSecrets counts secret entries in detect-secrets' baseline // JSON. The "results" object maps filename -> [secrets]; each entry has a // "type" key. Counting "type":"..." occurrences is a reliable, zero-dep // proxy for the number of flagged secrets. func countDetectSecrets(out string) int { return strings.Count(out, `"type":`) } // atoiSafe parses a leading integer, ignoring trailing punctuation. func atoiSafe(s string) int { n := 0 found := false for _, r := range s { if r < '0' || r > '9' { if found { break } continue } found = true n = n*10 + int(r-'0') } return n }