package main // History secret scan (ADR-0093 ยง10 item 1, WP-13 13a). // // Run ONCE, when a service is onboarded: gitleaks over every commit of every // ref (`git log --all`), not only the working tree. A secret that was ever // committed is in the history whatever the tree says now; a change cannot fix // it, only a rotation can. So the findings are the service's BASELINE: posted // with report_data.scope = "history", which the security verdict never reads // as evidence about a change (security_verdict / prebuild_verdict), and the // platform opens a rotation task for each one. // // What is posted is the finding's LOCATION and FINGERPRINT (gitleaks' // `:::`), never the secret: `--redact` is on and the // report's Secret / Match fields are dropped before anything leaves the job. // // The source MUST carry its .git directory (a full clone, not a shallow one; // `fetch-depth: 0`). A tree without history is refused (could_not_run), never // scanned as if it were the history: that would report "nothing ever leaked" // for a repository whose past was not read. import ( "bytes" "context" "dagger/secret-scan/internal/dagger" "encoding/json" "fmt" "net/http" "strings" "time" ) // HistoryFinding is one secret found in the history, without the secret. type HistoryFinding struct { Fingerprint string `json:"fingerprint"` Rule string `json:"rule"` File string `json:"file"` Line int `json:"line"` Commit string `json:"commit"` } // HistoryResult is what History returns and posts. type HistoryResult struct { Outcome string `json:"outcome"` // ran | could_not_run Findings []HistoryFinding `json:"findings"` Posted bool `json:"posted"` Error string `json:"error,omitempty"` } // historyArgs is the gitleaks argv for the history scan. A function so the // test pins it: no `--no-git` (that would scan only the tree), every ref. func historyArgs(reportPath string) []string { return []string{ "gitleaks", "detect", "--source=/src", "--log-opts=--all", "--redact", "--exit-code", "0", "--report-format", "json", "--report-path", reportPath, } } // parseHistoryReport turns gitleaks' JSON report into findings with no secret // material. Unknown fields (Secret, Match, ...) are not decoded at all. func parseHistoryReport(report string) ([]HistoryFinding, error) { var raw []struct { RuleID string `json:"RuleID"` File string `json:"File"` StartLine int `json:"StartLine"` Commit string `json:"Commit"` Fingerprint string `json:"Fingerprint"` } if strings.TrimSpace(report) == "" { return []HistoryFinding{}, nil } if err := json.Unmarshal([]byte(report), &raw); err != nil { return nil, fmt.Errorf("gitleaks report unreadable: %w", err) } out := make([]HistoryFinding, 0, len(raw)) for _, r := range raw { fp := r.Fingerprint if fp == "" { fp = fmt.Sprintf("%s:%s:%s:%d", r.Commit, r.File, r.RuleID, r.StartLine) } out = append(out, HistoryFinding{ Fingerprint: fp, Rule: r.RuleID, File: r.File, Line: r.StartLine, Commit: r.Commit, }) } return out, nil } // History scans the full git history of source once and posts the findings as // the service's baseline (scan_type=secret, report_data.scope=history). func (m *SecretScan) History( ctx context.Context, // A FULL clone including .git (fetch-depth 0). source *dagger.Directory, // +optional apiURL string, // +optional token *dagger.Secret, // +optional serviceID string, // The commit the clone is at (the onboarding revision). // +optional version string, ) (*HistoryResult, error) { res := &HistoryResult{Outcome: "ran", Findings: []HistoryFinding{}} entries, err := source.Entries(ctx) hasGit := false for _, e := range entries { if strings.TrimSuffix(e, "/") == ".git" { hasGit = true } } if err != nil || !hasGit { res.Outcome = "could_not_run" res.Error = "the source has no .git directory: clone with full history (fetch-depth 0)" return res, m.postHistory(ctx, res, apiURL, token, serviceID, version) } const reportPath = "/tmp/gitleaks-history.json" report, err := dag.Container(). From("zricethezav/gitleaks:v8.21.2"). WithMountedDirectory("/src", source). WithWorkdir("/src"). WithExec(historyArgs(reportPath)). File(reportPath). Contents(ctx) if err == nil { res.Findings, err = parseHistoryReport(report) } if err != nil { res.Outcome = "could_not_run" res.Error = fmt.Sprintf("gitleaks history scan could not run: %v", err) res.Findings = []HistoryFinding{} } return res, m.postHistory(ctx, res, apiURL, token, serviceID, version) } func (m *SecretScan) postHistory(ctx context.Context, res *HistoryResult, apiURL string, token *dagger.Secret, serviceID, version string) error { if apiURL == "" || token == nil { return nil } findings := res.Findings if len(findings) > 1000 { findings = findings[:1000] } data := map[string]any{ // The onboarding revision, NOT "version": the deploy gate and the // verdict bind scans by version, and a baseline is not evidence about // any commit (deploying the onboarding commit must not be blocked by // secrets that only a rotation can fix). "revision": version, "scope": "history", "outcome": res.Outcome, // NOT secret_count, and no critical_count: the deploy gate's legacy // layer reads those on the newest row when a deploy names no version, // and a baseline must not deny any deploy (only a rotation fixes it). "history_secret_count": len(res.Findings), "history_findings": findings, } if res.Error != "" { data["error"] = res.Error } body, err := json.Marshal(map[string]any{ "service_id": serviceID, "scan_type": "secret", "scanner": "gitleaks-history", "report_format": "json", "findings_count": len(res.Findings), "report_data": data, }) if err != nil { return fmt.Errorf("marshal history payload: %w", err) } req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(apiURL, "/")+"/api/v1/scans", bytes.NewReader(body)) if err != nil { return fmt.Errorf("build request: %w", err) } tok, err := token.Plaintext(ctx) if err != nil { return fmt.Errorf("read token secret: %w", err) } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+tok) resp, err := (&http.Client{Timeout: 60 * time.Second}).Do(req) if err != nil { return fmt.Errorf("post history scan: %w", err) } defer resp.Body.Close() if resp.StatusCode >= 300 { return fmt.Errorf("post history scan returned %d", resp.StatusCode) } res.Posted = true return nil }