| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "sync" |
| 5 | |
| 6 | gitleaksconfig "github.com/zricethezav/gitleaks/v8/config" |
| 7 | "time" |
| 8 | |
| 9 | "amadan.net/oficina/equipo/internal/release" |
| 10 | "bufio" |
| 11 | "bytes" |
| 12 | "context" |
| 13 | "encoding/base64" |
| 14 | "encoding/hex" |
| 15 | "errors" |
| 16 | "fmt" |
| 17 | "io" |
| 18 | "os" |
| 19 | "os/exec" |
| 20 | "path/filepath" |
| 21 | "slices" |
| 22 | "strconv" |
| 23 | "strings" |
| 24 | |
| 25 | "amadan.net/oficina/equipo/internal/runner/mac" |
| 26 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 27 | "amadan.net/oficina/equipo/internal/wire" |
| 28 | ) |
| 29 | |
| 30 | // The object scan (Mac runners spec §8.3): before a worker's candidate |
| 31 | // leaves the Mac, every object it adds to the base (rev-list --objects |
| 32 | // ^base candidate) is read whole: blobs (binary ones too, and symlink |
| 33 | // targets, which are blobs), trees (file names) and the commit (message |
| 34 | // and identity). Each is searched for every known secret of the worker, |
| 35 | // raw, in base64 (standard and URL, at each alignment) and in hex; then |
| 36 | // the pinned gitleaks scans the new blobs with the trusted rules. It |
| 37 | // fails closed. What it reports names an object by id and kind only. |
| 38 | |
| 39 | // workerScanBound is the largest object the scan reads (the pack bound): |
| 40 | // one past it refuses the candidate. |
| 41 | var workerScanBound = int64(wire.MaxTransferBytes) |
| 42 | |
| 43 | // workerPackBound is the largest outbound pack (the transfer bound): |
| 44 | // objects each within workerScanBound can still make a larger one. |
| 45 | var workerPackBound = int64(wire.MaxTransferBytes) |
| 46 | |
| 47 | // minSecret is the shortest known secret searched for: shorter ones |
| 48 | // would match ordinary text. |
| 49 | const minSecret = 16 |
| 50 | |
| 51 | // scanHit is why the scan refused: the object and its kind ("" object |
| 52 | // for gitleaks, which scans the blobs together; kind "scanner" when the |
| 53 | // scan could not tell). |
| 54 | type scanHit struct { |
| 55 | object, kind string |
| 56 | // unproven: the scanner's end is not proven (the attempt stays |
| 57 | // unterminated). |
| 58 | unproven bool |
| 59 | } |
| 60 | |
| 61 | // secretForms are the byte strings each secret is searched as: raw, hex |
| 62 | // (both cases), and base64 standard and URL at each of the three |
| 63 | // alignments it can have inside a longer encoding (the groups that hold |
| 64 | // neighbouring bytes are left out). Longest first, so a redaction never |
| 65 | // leaves part of a longer form. |
| 66 | func secretForms(secrets []string) [][]byte { |
| 67 | seen := map[string]bool{} |
| 68 | var out [][]byte |
| 69 | add := func(b []byte) { |
| 70 | if len(b) >= minSecret && !seen[string(b)] { |
| 71 | seen[string(b)] = true |
| 72 | out = append(out, b) |
| 73 | } |
| 74 | } |
| 75 | for _, s := range secrets { |
| 76 | if len(s) < minSecret { |
| 77 | continue |
| 78 | } |
| 79 | raw := []byte(s) |
| 80 | add(raw) |
| 81 | h := hex.EncodeToString(raw) |
| 82 | add([]byte(h)) |
| 83 | add([]byte(strings.ToUpper(h))) |
| 84 | for _, enc := range []*base64.Encoding{base64.StdEncoding, base64.URLEncoding} { |
| 85 | for k := range 3 { |
| 86 | full := enc.EncodeToString(append(make([]byte, k), raw...)) |
| 87 | start, end := 0, (k+len(raw))/3*4 |
| 88 | if k > 0 { |
| 89 | start = 4 |
| 90 | } |
| 91 | if end > start { |
| 92 | add([]byte(full[start:end])) |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | slices.SortStableFunc(out, func(a, b []byte) int { return len(b) - len(a) }) |
| 98 | return out |
| 99 | } |
| 100 | |
| 101 | // redactText replaces every form of a known secret, and anything the |
| 102 | // generic patterns take for one, with ***. |
| 103 | func redactText(s string, forms [][]byte) string { |
| 104 | for _, f := range forms { |
| 105 | s = strings.ReplaceAll(s, string(f), "***") |
| 106 | } |
| 107 | return runnerproto.RedactText(s, nil) |
| 108 | } |
| 109 | |
| 110 | // redactReport is rep with every string it carries redacted. |
| 111 | func redactReport(rep wire.StepReport, forms [][]byte) wire.StepReport { |
| 112 | rep.Headline, rep.Summary, rep.LogTail, rep.Output = redactText(rep.Headline, forms), redactText(rep.Summary, forms), redactText(rep.LogTail, forms), redactText(rep.Output, forms) |
| 113 | if len(rep.Findings) > 0 { |
| 114 | f := slices.Clone(rep.Findings) |
| 115 | for i := range f { |
| 116 | f[i].Text, f[i].Path = redactText(f[i].Text, forms), redactText(f[i].Path, forms) |
| 117 | } |
| 118 | rep.Findings = f |
| 119 | } |
| 120 | return rep |
| 121 | } |
| 122 | |
| 123 | // scan reads every new object of the candidate in the store; nil when |
| 124 | // none holds a known secret and gitleaks found nothing. |
| 125 | func (w *Worker) scan(ctx context.Context, store, dir, base, sha string, forms [][]byte, record func(string) error) *scanHit { |
| 126 | unreadable := &scanHit{kind: "scanner"} |
| 127 | list, err := w.git(ctx, nil, "--git-dir="+store, "rev-list", "--objects", "--end-of-options", sha, "^"+base) |
| 128 | if err != nil { |
| 129 | w.Engine.log("worker scan list", err) |
| 130 | return unreadable |
| 131 | } |
| 132 | var ids []string |
| 133 | for _, line := range strings.Split(list, "\n") { |
| 134 | // Only the id: a path is never kept (a file name can be the secret). |
| 135 | if id, _, _ := strings.Cut(line, " "); wire.ValidCommitSHA(id) { |
| 136 | ids = append(ids, id) |
| 137 | } |
| 138 | } |
| 139 | if len(ids) == 0 { |
| 140 | return unreadable |
| 141 | } |
| 142 | var hit *scanHit |
| 143 | err = w.readObjects(ctx, store, ids, func(id, kind string, body []byte) error { |
| 144 | for _, f := range forms { |
| 145 | if bytes.Contains(body, f) { |
| 146 | hit = &scanHit{object: id, kind: kind} |
| 147 | return errScanHit |
| 148 | } |
| 149 | } |
| 150 | return nil |
| 151 | }) |
| 152 | switch { |
| 153 | case hit != nil: |
| 154 | return hit |
| 155 | case errors.Is(err, errScanBound): |
| 156 | return &scanHit{object: boundObject(err), kind: "too_large"} |
| 157 | case err != nil: |
| 158 | w.Engine.log("worker scan read", err) |
| 159 | return unreadable |
| 160 | } |
| 161 | // gitleaks reads the changed files at their own paths (some rules go |
| 162 | // by the file's name), a renamed file's contents included. The paths |
| 163 | // stay in the stage: nothing logs them. |
| 164 | stage := filepath.Join(dir, "scan", "files") |
| 165 | if err := os.RemoveAll(filepath.Dir(stage)); err != nil { |
| 166 | return unreadable |
| 167 | } |
| 168 | if err := os.MkdirAll(stage, 0700); err != nil { |
| 169 | return unreadable |
| 170 | } |
| 171 | defer os.RemoveAll(filepath.Dir(stage)) |
| 172 | if err := w.stageChanged(ctx, store, base, sha, stage); err != nil { |
| 173 | if errors.Is(err, errScanBound) { |
| 174 | return &scanHit{object: boundObject(err), kind: "too_large"} |
| 175 | } |
| 176 | w.Engine.log("worker scan stage", err) |
| 177 | return unreadable |
| 178 | } |
| 179 | found, err := w.Eng.Leaks(ctx, stage, engineeringMarker(stage), record) |
| 180 | switch { |
| 181 | case found: |
| 182 | return &scanHit{kind: "gitleaks"} |
| 183 | case errors.Is(err, errScanUnproven): |
| 184 | return &scanHit{kind: "scanner", unproven: true} |
| 185 | case err != nil: |
| 186 | w.Engine.log("worker scan gitleaks", err) |
| 187 | return unreadable |
| 188 | } |
| 189 | return nil |
| 190 | } |
| 191 | |
| 192 | // stageChanged writes every file the candidate adds or changes against |
| 193 | // the base (no rename detection: a moved file is a new path) under stage |
| 194 | // at its path, its contents the blob's (a symbolic link's target as a |
| 195 | // plain file); a gitlink has no contents here. A path with an empty, "." |
| 196 | // or ".." part is refused. |
| 197 | func (w *Worker) stageChanged(ctx context.Context, store, base, sha, stage string) error { |
| 198 | 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) |
| 199 | if err != nil { |
| 200 | return err |
| 201 | } |
| 202 | paths := map[string][]string{} |
| 203 | var ids []string |
| 204 | fields := strings.Split(strings.Trim(out, "\x00"), "\x00") |
| 205 | for i := 0; i+1 < len(fields); i += 2 { |
| 206 | meta, path := strings.Fields(strings.TrimPrefix(fields[i], ":")), fields[i+1] |
| 207 | if len(meta) != 5 { |
| 208 | return errors.New("the changed files could not be read") |
| 209 | } |
| 210 | mode, id, status := meta[1], meta[3], meta[4] |
| 211 | if status == "D" || mode == "160000" { |
| 212 | continue |
| 213 | } |
| 214 | for _, part := range strings.Split(path, "/") { |
| 215 | if part == "" || part == "." || part == ".." { |
| 216 | return errors.New("a changed path the stage cannot hold") |
| 217 | } |
| 218 | } |
| 219 | if !wire.ValidCommitSHA(id) { |
| 220 | return errors.New("the changed files could not be read") |
| 221 | } |
| 222 | if paths[id] == nil { |
| 223 | ids = append(ids, id) |
| 224 | } |
| 225 | paths[id] = append(paths[id], path) |
| 226 | } |
| 227 | if len(ids) == 0 { |
| 228 | return nil |
| 229 | } |
| 230 | return w.readObjects(ctx, store, ids, func(id, kind string, body []byte) error { |
| 231 | for _, p := range paths[id] { |
| 232 | target := filepath.Join(stage, filepath.FromSlash(p)) |
| 233 | if err := os.MkdirAll(filepath.Dir(target), 0700); err != nil { |
| 234 | return err |
| 235 | } |
| 236 | if err := os.WriteFile(target, body, 0600); err != nil { |
| 237 | return err |
| 238 | } |
| 239 | } |
| 240 | return nil |
| 241 | }) |
| 242 | } |
| 243 | |
| 244 | var ( |
| 245 | // errScanUnproven: the scanner ran in the gate and its end is not |
| 246 | // proven. |
| 247 | errScanUnproven = errors.New("the secret scanner's end is not proven") |
| 248 | errScanHit = errors.New("a known secret in the candidate") |
| 249 | errScanBound = errors.New("an object past the scan bound") |
| 250 | ) |
| 251 | |
| 252 | // boundError names the object past the bound. |
| 253 | type boundError struct{ id string } |
| 254 | |
| 255 | func (e *boundError) Error() string { return "object " + e.id + " is past the scan bound" } |
| 256 | func (e *boundError) Unwrap() error { return errScanBound } |
| 257 | |
| 258 | func boundObject(err error) string { |
| 259 | var b *boundError |
| 260 | if errors.As(err, &b) { |
| 261 | return b.id |
| 262 | } |
| 263 | return "" |
| 264 | } |
| 265 | |
| 266 | // readObjects reads each object whole with cat-file --batch, sizes first |
| 267 | // (--batch-check): one past workerScanBound stops the read before any |
| 268 | // is read (objects are content-addressed: the sizes cannot change). |
| 269 | func (w *Worker) readObjects(ctx context.Context, store string, ids []string, each func(id, kind string, body []byte) error) error { |
| 270 | input := strings.Join(ids, "\n") + "\n" |
| 271 | check, err := w.git(ctx, strings.NewReader(input), "--git-dir="+store, "cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)") |
| 272 | if err != nil { |
| 273 | return err |
| 274 | } |
| 275 | lines := strings.Split(check, "\n") |
| 276 | if len(lines) != len(ids) { |
| 277 | return errors.New("the object list and its sizes disagree") |
| 278 | } |
| 279 | for i, line := range lines { |
| 280 | f := strings.Fields(line) |
| 281 | if len(f) != 3 || f[0] != ids[i] { |
| 282 | return errors.New("an object could not be read") |
| 283 | } |
| 284 | if n, err := strconv.ParseInt(f[2], 10, 64); err != nil || n > workerScanBound { |
| 285 | return &boundError{id: ids[i]} |
| 286 | } |
| 287 | } |
| 288 | cmd := exec.CommandContext(ctx, w.Engine.O.Runner.GitPath, "--git-dir="+store, "cat-file", "--batch") |
| 289 | cmd.Stdin, cmd.Env = strings.NewReader(input), w.gitEnv() |
| 290 | out, err := cmd.StdoutPipe() |
| 291 | if err != nil { |
| 292 | return err |
| 293 | } |
| 294 | if err := mac.StartOwn(cmd); err != nil { |
| 295 | return err |
| 296 | } |
| 297 | read := func() error { |
| 298 | br := bufio.NewReader(out) |
| 299 | for _, id := range ids { |
| 300 | header, err := br.ReadString('\n') |
| 301 | if err != nil { |
| 302 | return err |
| 303 | } |
| 304 | var got, kind string |
| 305 | var size int64 |
| 306 | if n, err := fmt.Sscanf(header, "%s %s %d\n", &got, &kind, &size); n != 3 || err != nil || got != id || size < 0 { |
| 307 | return errors.New("an object could not be read") |
| 308 | } |
| 309 | body := make([]byte, size+1) |
| 310 | if _, err := io.ReadFull(br, body); err != nil || body[size] != '\n' { |
| 311 | return errors.New("an object could not be read") |
| 312 | } |
| 313 | if err := each(id, kind, body[:size]); err != nil { |
| 314 | return err |
| 315 | } |
| 316 | } |
| 317 | return nil |
| 318 | } |
| 319 | err = read() |
| 320 | if err != nil { |
| 321 | _ = cmd.Process.Kill() |
| 322 | } |
| 323 | _, _ = io.Copy(io.Discard, out) |
| 324 | return errors.Join(err, cmd.Wait()) |
| 325 | } |
| 326 | |
| 327 | // gateLeaks runs the pinned gitleaks over stage in the gate g: on a Mac |
| 328 | // the checks gate, srt with the checks profile probe P2 proves (no |
| 329 | // network, reads kept from §4.2's places, writes only to the gate's tree |
| 330 | // and scratch). The tree is stage's parent, which holds the trusted |
| 331 | // rules, the empty ignore file and the report; marker and record are the |
| 332 | // scan's process record, as a check's. |
| 333 | func gateLeaks(ctx context.Context, g *mac.Gate, binary, pin, stage, marker string, record func(string) error) (bool, error) { |
| 334 | if !release.VerifyGitleaks(binary, pin) { |
| 335 | return false, errScanner |
| 336 | } |
| 337 | root := filepath.Dir(stage) |
| 338 | config, ignore, report := filepath.Join(root, "trusted.toml"), filepath.Join(root, "empty.ignore"), filepath.Join(root, "findings.json") |
| 339 | if os.WriteFile(config, []byte(workerSecretRules()), 0600) != nil || os.WriteFile(ignore, nil, 0600) != nil { |
| 340 | return false, errScanner |
| 341 | } |
| 342 | if record == nil { |
| 343 | record = func(string) error { return nil } |
| 344 | } |
| 345 | 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} |
| 346 | res := g.Run(ctx, marker, root, argv, 2*time.Minute, record) |
| 347 | switch { |
| 348 | case !res.Terminated: |
| 349 | return false, errScanUnproven |
| 350 | case res.Reason == "checks_unavailable": |
| 351 | // The gate's start failed, a record write included (the scan's |
| 352 | // marker or group, or its turn's record: Gate.Run reports each |
| 353 | // so), or its turn's record was lost while it ran: its end is not |
| 354 | // proven, whatever ran. |
| 355 | return false, errScanUnproven |
| 356 | case res.Reason != "": |
| 357 | return false, errScanner |
| 358 | } |
| 359 | found, err := readFindings(report) |
| 360 | if err != nil || found { |
| 361 | return found, err |
| 362 | } |
| 363 | if res.Code != 0 { |
| 364 | return false, errScanner |
| 365 | } |
| 366 | return false, nil |
| 367 | } |
| 368 | |
| 369 | // workerSecretRules is the worker's trusted gitleaks configuration: the |
| 370 | // pinned build's own default rules (gitleaks' config.DefaultConfig, the |
| 371 | // same version as the scanner), with every path exclusion taken out (the |
| 372 | // global list, and each rule's allow list that names paths, whole), so a |
| 373 | // secret under node_modules, in gitleaks.toml or in a .bin file is found |
| 374 | // like any other; the rules that go by a file's name (nuget.config, |
| 375 | // .p12) stay. The runner's own rules are added, as for previews. |
| 376 | var workerSecretRules = sync.OnceValue(func() string { |
| 377 | var out []string |
| 378 | for _, block := range tomlBlocks(gitleaksconfig.DefaultConfig) { |
| 379 | header := strings.TrimSpace(strings.SplitN(block, "\n", 2)[0]) |
| 380 | switch { |
| 381 | case header == "[[rules.allowlists]]" && hasPaths(block): |
| 382 | continue |
| 383 | case header == "[allowlist]": |
| 384 | block = withoutPaths(block) |
| 385 | } |
| 386 | out = append(out, block) |
| 387 | } |
| 388 | return strings.Join(out, "") + "\n" + strings.TrimPrefix(previewSecretRules, "[extend]\nuseDefault = true\n") |
| 389 | }) |
| 390 | |
| 391 | // tomlBlocks splits a TOML document before each table header (a line |
| 392 | // starting "["), keeping every byte. |
| 393 | func tomlBlocks(doc string) []string { |
| 394 | var out []string |
| 395 | start := 0 |
| 396 | for i := 0; i < len(doc); { |
| 397 | end := strings.IndexByte(doc[i:], '\n') |
| 398 | if end < 0 { |
| 399 | break |
| 400 | } |
| 401 | next := i + end + 1 |
| 402 | if next < len(doc) && doc[next] == '[' { |
| 403 | out = append(out, doc[start:next]) |
| 404 | start = next |
| 405 | } |
| 406 | i = next |
| 407 | } |
| 408 | return append(out, doc[start:]) |
| 409 | } |
| 410 | |
| 411 | // hasPaths: the block sets paths. |
| 412 | func hasPaths(block string) bool { |
| 413 | for _, line := range strings.Split(block, "\n") { |
| 414 | if strings.HasPrefix(strings.TrimSpace(line), "paths") && strings.Contains(line, "=") { |
| 415 | return true |
| 416 | } |
| 417 | } |
| 418 | return false |
| 419 | } |
| 420 | |
| 421 | // withoutPaths is the block with its paths array (to its closing "]" |
| 422 | // line) removed. |
| 423 | func withoutPaths(block string) string { |
| 424 | var out []string |
| 425 | skipping := false |
| 426 | for _, line := range strings.SplitAfter(block, "\n") { |
| 427 | t := strings.TrimSpace(line) |
| 428 | switch { |
| 429 | case !skipping && strings.HasPrefix(t, "paths") && strings.Contains(t, "="): |
| 430 | skipping = !strings.HasSuffix(t, "]") |
| 431 | case skipping: |
| 432 | skipping = t != "]" |
| 433 | default: |
| 434 | out = append(out, line) |
| 435 | } |
| 436 | } |
| 437 | return strings.Join(out, "") |
| 438 | } |
| 439 | |