package thin import ( "sync" gitleaksconfig "github.com/zricethezav/gitleaks/v8/config" "time" "amadan.net/oficina/equipo/internal/release" "bufio" "bytes" "context" "encoding/base64" "encoding/hex" "errors" "fmt" "io" "os" "os/exec" "path/filepath" "slices" "strconv" "strings" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/wire" ) // The object scan (Mac runners spec §8.3): before a worker's candidate // leaves the Mac, every object it adds to the base (rev-list --objects // ^base candidate) is read whole: blobs (binary ones too, and symlink // targets, which are blobs), trees (file names) and the commit (message // and identity). Each is searched for every known secret of the worker, // raw, in base64 (standard and URL, at each alignment) and in hex; then // the pinned gitleaks scans the new blobs with the trusted rules. It // fails closed. What it reports names an object by id and kind only. // workerScanBound is the largest object the scan reads (the pack bound): // one past it refuses the candidate. var workerScanBound = int64(wire.MaxTransferBytes) // workerPackBound is the largest outbound pack (the transfer bound): // objects each within workerScanBound can still make a larger one. var workerPackBound = int64(wire.MaxTransferBytes) // minSecret is the shortest known secret searched for: shorter ones // would match ordinary text. const minSecret = 16 // scanHit is why the scan refused: the object and its kind ("" object // for gitleaks, which scans the blobs together; kind "scanner" when the // scan could not tell). type scanHit struct { object, kind string // unproven: the scanner's end is not proven (the attempt stays // unterminated). unproven bool } // secretForms are the byte strings each secret is searched as: raw, hex // (both cases), and base64 standard and URL at each of the three // alignments it can have inside a longer encoding (the groups that hold // neighbouring bytes are left out). Longest first, so a redaction never // leaves part of a longer form. func secretForms(secrets []string) [][]byte { seen := map[string]bool{} var out [][]byte add := func(b []byte) { if len(b) >= minSecret && !seen[string(b)] { seen[string(b)] = true out = append(out, b) } } for _, s := range secrets { if len(s) < minSecret { continue } raw := []byte(s) add(raw) h := hex.EncodeToString(raw) add([]byte(h)) add([]byte(strings.ToUpper(h))) for _, enc := range []*base64.Encoding{base64.StdEncoding, base64.URLEncoding} { for k := range 3 { full := enc.EncodeToString(append(make([]byte, k), raw...)) start, end := 0, (k+len(raw))/3*4 if k > 0 { start = 4 } if end > start { add([]byte(full[start:end])) } } } } slices.SortStableFunc(out, func(a, b []byte) int { return len(b) - len(a) }) return out } // redactText replaces every form of a known secret, and anything the // generic patterns take for one, with ***. func redactText(s string, forms [][]byte) string { for _, f := range forms { s = strings.ReplaceAll(s, string(f), "***") } return runnerproto.RedactText(s, nil) } // redactReport is rep with every string it carries redacted. func redactReport(rep wire.StepReport, forms [][]byte) wire.StepReport { rep.Headline, rep.Summary, rep.LogTail, rep.Output = redactText(rep.Headline, forms), redactText(rep.Summary, forms), redactText(rep.LogTail, forms), redactText(rep.Output, forms) if len(rep.Findings) > 0 { f := slices.Clone(rep.Findings) for i := range f { f[i].Text, f[i].Path = redactText(f[i].Text, forms), redactText(f[i].Path, forms) } rep.Findings = f } return rep } // scan reads every new object of the candidate in the store; nil when // none holds a known secret and gitleaks found nothing. func (w *Worker) scan(ctx context.Context, store, dir, base, sha string, forms [][]byte, record func(string) error) *scanHit { unreadable := &scanHit{kind: "scanner"} list, err := w.git(ctx, nil, "--git-dir="+store, "rev-list", "--objects", "--end-of-options", sha, "^"+base) if err != nil { w.Engine.log("worker scan list", err) return unreadable } var ids []string for _, line := range strings.Split(list, "\n") { // Only the id: a path is never kept (a file name can be the secret). if id, _, _ := strings.Cut(line, " "); wire.ValidCommitSHA(id) { ids = append(ids, id) } } if len(ids) == 0 { return unreadable } var hit *scanHit err = w.readObjects(ctx, store, ids, func(id, kind string, body []byte) error { for _, f := range forms { if bytes.Contains(body, f) { hit = &scanHit{object: id, kind: kind} return errScanHit } } return nil }) switch { case hit != nil: return hit case errors.Is(err, errScanBound): return &scanHit{object: boundObject(err), kind: "too_large"} case err != nil: w.Engine.log("worker scan read", err) return unreadable } // gitleaks reads the changed files at their own paths (some rules go // by the file's name), a renamed file's contents included. The paths // stay in the stage: nothing logs them. stage := filepath.Join(dir, "scan", "files") if err := os.RemoveAll(filepath.Dir(stage)); err != nil { return unreadable } if err := os.MkdirAll(stage, 0700); err != nil { return unreadable } defer os.RemoveAll(filepath.Dir(stage)) if err := w.stageChanged(ctx, store, base, sha, stage); err != nil { if errors.Is(err, errScanBound) { return &scanHit{object: boundObject(err), kind: "too_large"} } w.Engine.log("worker scan stage", err) return unreadable } found, err := w.Eng.Leaks(ctx, stage, engineeringMarker(stage), record) switch { case found: return &scanHit{kind: "gitleaks"} case errors.Is(err, errScanUnproven): return &scanHit{kind: "scanner", unproven: true} case err != nil: w.Engine.log("worker scan gitleaks", err) return unreadable } return nil } // stageChanged writes every file the candidate adds or changes against // the base (no rename detection: a moved file is a new path) under stage // at its path, its contents the blob's (a symbolic link's target as a // plain file); a gitlink has no contents here. A path with an empty, "." // or ".." part is refused. func (w *Worker) stageChanged(ctx context.Context, store, base, sha, stage string) error { out, err := w.git(ctx, nil, "--git-dir="+store, "diff-tree", "-r", "-z", "--no-renames", "--no-commit-id", "--no-ext-diff", "--no-textconv", "--end-of-options", base, sha) if err != nil { return err } paths := map[string][]string{} var ids []string fields := strings.Split(strings.Trim(out, "\x00"), "\x00") for i := 0; i+1 < len(fields); i += 2 { meta, path := strings.Fields(strings.TrimPrefix(fields[i], ":")), fields[i+1] if len(meta) != 5 { return errors.New("the changed files could not be read") } mode, id, status := meta[1], meta[3], meta[4] if status == "D" || mode == "160000" { continue } for _, part := range strings.Split(path, "/") { if part == "" || part == "." || part == ".." { return errors.New("a changed path the stage cannot hold") } } if !wire.ValidCommitSHA(id) { return errors.New("the changed files could not be read") } if paths[id] == nil { ids = append(ids, id) } paths[id] = append(paths[id], path) } if len(ids) == 0 { return nil } return w.readObjects(ctx, store, ids, func(id, kind string, body []byte) error { for _, p := range paths[id] { target := filepath.Join(stage, filepath.FromSlash(p)) if err := os.MkdirAll(filepath.Dir(target), 0700); err != nil { return err } if err := os.WriteFile(target, body, 0600); err != nil { return err } } return nil }) } var ( // errScanUnproven: the scanner ran in the gate and its end is not // proven. errScanUnproven = errors.New("the secret scanner's end is not proven") errScanHit = errors.New("a known secret in the candidate") errScanBound = errors.New("an object past the scan bound") ) // boundError names the object past the bound. type boundError struct{ id string } func (e *boundError) Error() string { return "object " + e.id + " is past the scan bound" } func (e *boundError) Unwrap() error { return errScanBound } func boundObject(err error) string { var b *boundError if errors.As(err, &b) { return b.id } return "" } // readObjects reads each object whole with cat-file --batch, sizes first // (--batch-check): one past workerScanBound stops the read before any // is read (objects are content-addressed: the sizes cannot change). func (w *Worker) readObjects(ctx context.Context, store string, ids []string, each func(id, kind string, body []byte) error) error { input := strings.Join(ids, "\n") + "\n" check, err := w.git(ctx, strings.NewReader(input), "--git-dir="+store, "cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)") if err != nil { return err } lines := strings.Split(check, "\n") if len(lines) != len(ids) { return errors.New("the object list and its sizes disagree") } for i, line := range lines { f := strings.Fields(line) if len(f) != 3 || f[0] != ids[i] { return errors.New("an object could not be read") } if n, err := strconv.ParseInt(f[2], 10, 64); err != nil || n > workerScanBound { return &boundError{id: ids[i]} } } cmd := exec.CommandContext(ctx, w.Engine.O.Runner.GitPath, "--git-dir="+store, "cat-file", "--batch") cmd.Stdin, cmd.Env = strings.NewReader(input), w.gitEnv() out, err := cmd.StdoutPipe() if err != nil { return err } if err := mac.StartOwn(cmd); err != nil { return err } read := func() error { br := bufio.NewReader(out) for _, id := range ids { header, err := br.ReadString('\n') if err != nil { return err } var got, kind string var size int64 if n, err := fmt.Sscanf(header, "%s %s %d\n", &got, &kind, &size); n != 3 || err != nil || got != id || size < 0 { return errors.New("an object could not be read") } body := make([]byte, size+1) if _, err := io.ReadFull(br, body); err != nil || body[size] != '\n' { return errors.New("an object could not be read") } if err := each(id, kind, body[:size]); err != nil { return err } } return nil } err = read() if err != nil { _ = cmd.Process.Kill() } _, _ = io.Copy(io.Discard, out) return errors.Join(err, cmd.Wait()) } // gateLeaks runs the pinned gitleaks over stage in the gate g: on a Mac // the checks gate, srt with the checks profile probe P2 proves (no // network, reads kept from §4.2's places, writes only to the gate's tree // and scratch). The tree is stage's parent, which holds the trusted // rules, the empty ignore file and the report; marker and record are the // scan's process record, as a check's. func gateLeaks(ctx context.Context, g *mac.Gate, binary, pin, stage, marker string, record func(string) error) (bool, error) { if !release.VerifyGitleaks(binary, pin) { return false, errScanner } root := filepath.Dir(stage) config, ignore, report := filepath.Join(root, "trusted.toml"), filepath.Join(root, "empty.ignore"), filepath.Join(root, "findings.json") if os.WriteFile(config, []byte(workerSecretRules()), 0600) != nil || os.WriteFile(ignore, nil, 0600) != nil { return false, errScanner } if record == nil { record = func(string) error { return nil } } argv := []string{binary, "dir", "--config", config, "--gitleaks-ignore-path", ignore, "--ignore-gitleaks-allow", "--no-banner", "--redact", "--log-level", "error", "--max-archive-depth", "10", "--max-decode-depth", "5", "--report-format", "json", "--report-path", report, stage} res := g.Run(ctx, marker, root, argv, 2*time.Minute, record) switch { case !res.Terminated: return false, errScanUnproven case res.Reason == "checks_unavailable": // The gate's start failed, a record write included (the scan's // marker or group, or its turn's record: Gate.Run reports each // so), or its turn's record was lost while it ran: its end is not // proven, whatever ran. return false, errScanUnproven case res.Reason != "": return false, errScanner } found, err := readFindings(report) if err != nil || found { return found, err } if res.Code != 0 { return false, errScanner } return false, nil } // workerSecretRules is the worker's trusted gitleaks configuration: the // pinned build's own default rules (gitleaks' config.DefaultConfig, the // same version as the scanner), with every path exclusion taken out (the // global list, and each rule's allow list that names paths, whole), so a // secret under node_modules, in gitleaks.toml or in a .bin file is found // like any other; the rules that go by a file's name (nuget.config, // .p12) stay. The runner's own rules are added, as for previews. var workerSecretRules = sync.OnceValue(func() string { var out []string for _, block := range tomlBlocks(gitleaksconfig.DefaultConfig) { header := strings.TrimSpace(strings.SplitN(block, "\n", 2)[0]) switch { case header == "[[rules.allowlists]]" && hasPaths(block): continue case header == "[allowlist]": block = withoutPaths(block) } out = append(out, block) } return strings.Join(out, "") + "\n" + strings.TrimPrefix(previewSecretRules, "[extend]\nuseDefault = true\n") }) // tomlBlocks splits a TOML document before each table header (a line // starting "["), keeping every byte. func tomlBlocks(doc string) []string { var out []string start := 0 for i := 0; i < len(doc); { end := strings.IndexByte(doc[i:], '\n') if end < 0 { break } next := i + end + 1 if next < len(doc) && doc[next] == '[' { out = append(out, doc[start:next]) start = next } i = next } return append(out, doc[start:]) } // hasPaths: the block sets paths. func hasPaths(block string) bool { for _, line := range strings.Split(block, "\n") { if strings.HasPrefix(strings.TrimSpace(line), "paths") && strings.Contains(line, "=") { return true } } return false } // withoutPaths is the block with its paths array (to its closing "]" // line) removed. func withoutPaths(block string) string { var out []string skipping := false for _, line := range strings.SplitAfter(block, "\n") { t := strings.TrimSpace(line) switch { case !skipping && strings.HasPrefix(t, "paths") && strings.Contains(t, "="): skipping = !strings.HasSuffix(t, "]") case skipping: skipping = t != "]" default: out = append(out, line) } } return strings.Join(out, "") }