package thin import ( "amadan.net/oficina/equipo/internal/release" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/wire" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "net/url" "os" "os/exec" "path/filepath" "runtime" "strconv" "strings" "time" ) const previewHeadersTemplate = "/*\n Content-Security-Policy: default-src 'none'; connect-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; media-src 'self'; form-action 'none'; frame-src 'none'; base-uri 'none'; object-src 'none'; frame-ancestors %s\n X-Content-Type-Options: nosniff\n Referrer-Policy: no-referrer\n X-DNS-Prefetch-Control: off\n" func previewHeaders(origin string) string { ancestor := "'none'" u, err := url.Parse(origin) if err == nil && u.Host != "" && u.User == nil && u.Path == "" && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && !strings.ContainsAny(u.Host, "* ;\r\n\t'\"\\") && (u.Scheme == "https" || u.Scheme == "http" && u.Hostname() == "127.0.0.1") { ancestor = u.Scheme + "://" + u.Host } return fmt.Sprintf(previewHeadersTemplate, ancestor) } func previewCSP(origin string) string { _, value, _ := strings.Cut(strings.Split(previewHeaders(origin), "\n")[1], ": ") return value } const previewSecretRules = `[extend] useDefault = true [[rules]] id = "equipo-github-token" regex = '''(?:ghs_|ghu_|gho_|ghr_)[A-Za-z0-9_]{20,}''' [[rules]] id = "equipo-private-key-header" regex = '''-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----''' ` const previewScanner = "github.com/zricethezav/gitleaks/v8@" + release.GitleaksVersion var previewScannerTool = func(c runner.Config) (string, string) { return filepath.Join(filepath.Dir(c.Executable), "gitleaks"), release.GitleaksSHA256() } // previewToolHealth is whether the preview scanner is installed and is the // pinned build, as scanPreview checks it before every scan: a fixed state // for the coordinator's status, never the path or the pin. func previewToolHealth(c runner.Config) *wire.ToolHealth { binary, pin := previewScannerTool(c) state := wire.ToolHealthy switch info, err := os.Lstat(binary); { case !filepath.IsAbs(binary) || err != nil || !info.Mode().IsRegular(): state = wire.ToolMissing case pin == "": state = wire.ToolUnpinned case !release.VerifyGitleaks(binary, pin): state = wire.ToolMismatch } return &wire.ToolHealth{Scanner: state} } func (e *Engineer) scanPreview(ctx context.Context, stage string) string { found, err := e.gitleaks(ctx, stage) switch { case found: return "preview_secrets" case err != nil: return "preview_scanner" } return "" } // errScanner: the pinned gitleaks could not say (missing, not the pinned // build, failed, timed out or wrote no readable report). var errScanner = errors.New("the secret scanner could not scan") // gitleaks runs the pinned scanner with the trusted rules over the files // under stage, offline and confined (sandbox-exec deny-default on a Mac, // bubblewrap with nothing shared on Linux): found when it reported any // finding, else errScanner when it could not tell. Its report is read // for a count only: no finding's text is kept. func (e *Engineer) gitleaks(ctx context.Context, stage string) (bool, error) { return e.gitleaksWith(ctx, stage, previewSecretRules) } // gitleaksWith is gitleaks with the trusted rules given. func (e *Engineer) gitleaksWith(ctx context.Context, stage, rules string) (bool, error) { binary, pin := previewScannerTool(e.O.Runner) return e.gitleaksAt(ctx, binary, pin, stage, rules) } // gitleaksAt is gitleaksWith with the scanner binary and its pin given // (the test build's fake Mac worker names its own). func (e *Engineer) gitleaksAt(ctx context.Context, binary, pin, stage, rules string) (bool, error) { if !release.VerifyGitleaks(binary, pin) { return false, errScanner } dir, err := os.MkdirTemp(filepath.Dir(stage), "preview-scan-") if err != nil { return false, errScanner } defer os.RemoveAll(dir) config := filepath.Join(dir, "trusted.toml") ignore := filepath.Join(dir, "empty.ignore") report := filepath.Join(dir, "findings.json") if os.WriteFile(config, []byte(rules), 0600) != nil || os.WriteFile(ignore, nil, 0600) != nil { return false, errScanner } args := func(bin, cfg, ign, rep, files string) []string { return []string{bin, "dir", "--config", cfg, "--gitleaks-ignore-path", ign, "--ignore-gitleaks-allow", "--no-banner", "--redact", "--log-level", "error", "--max-archive-depth", "10", "--max-decode-depth", "5", "--report-format", "json", "--report-path", rep, files} } var command string var argv []string if runtime.GOOS == "darwin" { command = "/usr/bin/sandbox-exec" profile := fmt.Sprintf(`(version 1)(deny default)(allow process*)(allow sysctl-read)(allow file-read* (subpath "/System") (subpath "/usr/lib") (subpath %s) (subpath %s) (literal %s) (literal "/dev/null"))(allow file-write* (literal %s) (literal "/dev/null"))`, strconv.Quote(stage), strconv.Quote(dir), strconv.Quote(binary), strconv.Quote(report)) argv = append([]string{"-p", profile}, args(binary, config, ignore, report, stage)...) } else { command = firstNonEmpty(e.O.Runner.BwrapPath, "/usr/bin/bwrap") argv = []string{"--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", "--ro-bind", binary, "/scanner", "--ro-bind", stage, "/files", "--bind", dir, "/output", "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--chdir", "/tmp", "--clearenv", "--setenv", "HOME", "/tmp", "--setenv", "PATH", "/nonexistent"} argv = append(argv, args("/scanner", "/output/trusted.toml", "/output/empty.ignore", "/output/findings.json", "/files")...) } scanCtx, cancel := context.WithTimeout(ctx, 2*time.Minute) defer cancel() cmd := exec.CommandContext(scanCtx, command, argv...) cmd.Dir = dir cmd.Env = []string{"PATH=/usr/bin:/bin", "HOME=" + dir} _, clipped, scanErr := boundedOutput(cmd, 4096) if clipped || scanCtx.Err() != nil { return false, errScanner } found, err := readFindings(report) if err != nil || found { return found, err } if scanErr != nil { return false, errScanner } return false, nil } // readFindings reads a gitleaks report for whether it has any finding; // errScanner when it is missing, too large or not a report. No // finding's text is kept. func readFindings(report string) (bool, error) { info, err := os.Stat(report) if err != nil || !info.Mode().IsRegular() || info.Size() > 2<<20 { return false, errScanner } raw, err := os.ReadFile(report) var findings []json.RawMessage if err != nil || json.Unmarshal(raw, &findings) != nil || findings == nil { return false, errScanner } return len(findings) > 0, nil } // workerLeaks is the worker's scanner off a Mac (the test build's fake // worker on Linux): the preview scanner's bubblewrap with the worker's // trusted rules; marker and record are not needed there. func (e *Engineer) workerLeaks(ctx context.Context, stage, _ string, _ func(string) error) (bool, error) { return e.gitleaksWith(ctx, stage, workerSecretRules()) } type previewRefusalError struct{ reason string } func (e *previewRefusalError) Error() string { return e.reason } func previewPublishFailure(out string) string { if strings.Contains(out, "_headers:") && strings.Contains(out, "is not supported yet") { return "preview_headers" } return "preview_failed" } func previewSecurityStamp(origin string) string { sum := sha256.Sum256([]byte("preview/v1\n" + previewHeaders(origin) + previewScanner)) return hex.EncodeToString(sum[:]) }