package thin import ( "context" "database/sql" "encoding/base64" "encoding/json" "errors" "os/exec" "slices" "strconv" "strings" "time" "unicode/utf8" "amadan.net/oficina/equipo/internal/diffscan" "amadan.net/oficina/equipo/internal/runner/forge" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/wire" ) func displayGit(ctx context.Context, git, dir string, limit int, args ...string) (string, bool, error) { cmd := exec.CommandContext(ctx, git, append([]string{"--git-dir=" + dir, "-c", "core.quotePath=false", "-c", "core.hooksPath=/nonexistent"}, args...)...) env := workspace.GitEnvironment() env["HOME"] = "/nonexistent" env["GIT_LITERAL_PATHSPECS"] = "1" env["GIT_NO_LAZY_FETCH"] = "1" env["GIT_ALLOW_PROTOCOL"] = "" for k, v := range env { cmd.Env = append(cmd.Env, k+"="+v) } raw, cut, err := boundedOutput(cmd, limit) return string(raw), cut, err } // Read only a regular Git blob. Tree modes, object size and aggregate input // are checked before cat-file; a checkout symlink is never dereferenced. func displayBlob(ctx context.Context, git, dir, sha, path string, budget *int) (string, string) { if sha == "" { return "", "" } raw, cut, err := displayGit(ctx, git, dir, 8192, "ls-tree", "-z", sha, "--", path) if err != nil || cut { return "", wire.DiffUnavailable } if raw == "" { return "", "" } if strings.Count(raw, "\x00") != 1 { return "", wire.DiffUnavailable } header, name, ok := strings.Cut(strings.TrimSuffix(raw, "\x00"), "\t") fields := strings.Fields(header) if !ok || name != path || len(fields) != 3 || fields[0] != "100644" && fields[0] != "100755" || fields[1] != "blob" || !shaPattern.MatchString(fields[2]) { return "", wire.DiffUnavailable } size, cut, err := displayGit(ctx, git, dir, 64, "cat-file", "-s", fields[2]) n, e := strconv.Atoi(strings.TrimSpace(size)) if err != nil || cut || e != nil || n < 0 { return "", wire.DiffUnavailable } if n > wire.MaxDiffBlobBytes || n > *budget { return "", wire.DiffTooLarge } *budget -= n data, cut, err := displayGit(ctx, git, dir, n, "cat-file", "blob", fields[2]) if err != nil || cut || len(data) != n { return "", wire.DiffUnavailable } if !utf8.ValidString(data) || strings.ContainsRune(data, 0) { return "", wire.DiffBinary } return data, "" } func collectChangeDiffs(ctx context.Context, git, dir string, facts *wire.ChangeFiles, known []string) []wire.FileDiff { if !wire.ValidChangeFiles(facts) { return nil } ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() entries := slices.Clone(facts.Entries) slices.SortFunc(entries, func(a, b wire.ChangedFile) int { return strings.Compare(a.Path, b.Path) }) files := make([]wire.FileDiff, 0, len(entries)) input, left := wire.MaxDiffInputBytes, wire.MaxCandidateDiffBytes for _, file := range entries { d := wire.FileDiff{Path: file.Path, Reason: wire.DiffUnavailable} if ctx.Err() != nil { files = append(files, d) continue } if file.Binary { d.Reason = wire.DiffBinary files = append(files, d) continue } old := file.Path if file.OldPath != "" { old = file.OldPath } before, why := displayBlob(ctx, git, dir, facts.Base, old, &input) if why == "" { why = diffscan.Check(ctx, before, known) } if why == "" { var after string after, why = displayBlob(ctx, git, dir, facts.SHA, file.Path, &input) if why == "" { why = diffscan.Check(ctx, after, known) } } if why != "" { d.Reason = why files = append(files, d) continue } pair := []string{facts.Base, facts.SHA} if facts.Base == "" { pair = []string{"--root", "--no-commit-id", facts.SHA} } args := append([]string{"diff-tree", "-p", "-r", "-M", "--no-ext-diff", "--no-textconv", "--no-color"}, pair...) args = append(args, "--", file.Path) if old != file.Path { args = append(args, old) } patch, cut, err := displayGit(ctx, git, dir, wire.MaxFileDiffBytes, args...) // Overflow kills Git intentionally. The complete input blobs were scanned. if ctx.Err() != nil || err != nil && !cut { files = append(files, d) continue } patch, clipped := clipDisplayPatch(patch) d = wire.FileDiff{Path: file.Path, Patch: patch, Truncated: cut || clipped} if len(patch) > left { d = wire.FileDiff{Path: file.Path, Reason: wire.DiffTooLarge} } else if why := diffscan.Check(ctx, patch, known); why != "" { d = wire.FileDiff{Path: file.Path, Reason: why} } if !wire.ValidFileDiff(d) { d = wire.FileDiff{Path: file.Path, Reason: wire.DiffUnavailable} } left -= len(d.Patch) files = append(files, d) } return files } func clipDisplayPatch(s string) (string, bool) { end, lines := 0, 0 for end < len(s) && lines < wire.MaxFileDiffLines { n := strings.IndexByte(s[end:], '\n') if n < 0 || end+n+1 > wire.MaxFileDiffBytes { break } end += n + 1 lines++ } return s[:end], end < len(s) } // queueChangeDiffs queues the display diffs of f, already screened // (screenChangeFiles) against known. func (e *Engineer) queueChangeDiffs(ctx context.Context, r stepRow, git, dir string, f *wire.ChangeFiles, known []string) string { if f == nil || e.O.State == nil || e.O.Protocol == nil || e.O.Protocol() < wire.ProtocolChangeDiffs || !e.diffCollect.TryLock() { return "" } defer e.diffCollect.Unlock() ups, collection := changeDiffUploads(ctx, wire.ChangeDiffUpload{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt}, git, dir, f, known) if len(ups) == 0 { return "" } err := e.O.State.tx(ctx, func(tx *sql.Tx) error { for _, v := range ups { if err := e.O.State.enqueue(tx, wire.FrameChangeDiff, "", v); err != nil { return err } } return nil }) if err != nil { return "" } return collection } // knownSecrets are the secrets this runner knows that must never reach a // display measurement: its diff secrets (the runner's bearer token) and // the forge credential it already uses for repo. ok is false when the // credential cannot be read. func (e *Engineer) knownSecrets(ctx context.Context, repo string) (known []string, ok bool) { known = slices.Clone(e.DiffSecrets) // Read only the credential file already used for this runner's forge work; // never resolve a remote credential or access the network for display. if e.O.Runner.AmadanCredentialPath != "" { credential, err := (forge.FileCredentials{Path: e.O.Runner.AmadanCredentialPath}).Credential(ctx, repo) if err != nil { return nil, false } known = append(known, credential.Bearer, credential.GitPassword) } return known, true } // screenChangeFiles is f as it may leave this runner, with the known // secrets it was screened against: nil when they cannot be read, or when // a listed file name or a renamed file's old name holds one of them or // anything else a diff would withhold (a file name can be the secret, // and it travels in the change files and in every diff upload). func (e *Engineer) screenChangeFiles(ctx context.Context, repo string, f *wire.ChangeFiles) (*wire.ChangeFiles, []string) { if f == nil { return nil, nil } known, ok := e.knownSecrets(ctx, repo) if !ok { return nil, nil } for _, entry := range f.Entries { for _, name := range []string{entry.Path, entry.OldPath} { if name != "" && diffscan.Check(ctx, name, known) != "" { e.log("change files", errors.New("a file name is withheld, so the measurement is")) return nil, nil } } } return f, known } // changeDiffUploads is the display collection of f as uploads naming // at's task, step, attempt and (for a worker's candidate) publication, // with the known secrets left out. Nothing when a frame would be too // large. func changeDiffUploads(ctx context.Context, at wire.ChangeDiffUpload, git, dir string, f *wire.ChangeFiles, known []string) ([]wire.ChangeDiffUpload, string) { files := collectChangeDiffs(ctx, git, dir, f, known) if len(files) == 0 { return nil, "" } collection := wire.DiffCollection(files) ups := make([]wire.ChangeDiffUpload, 0, len(files)) for i, file := range files { v := wire.ChangeDiffUpload{TaskID: at.TaskID, StepID: at.StepID, Attempt: at.Attempt, Publication: at.Publication, Base: f.Base, Candidate: f.SHA, Collection: collection, Index: i, Total: len(files), Path: file.Path, Size: len(file.Patch), SHA256: wire.DiffDigest([]byte(file.Patch)), Data: base64.StdEncoding.EncodeToString([]byte(file.Patch)), Reason: file.Reason, Truncated: file.Truncated} raw, _ := json.Marshal(v) if len(raw) > wire.MaxFrameBytes-1024 { return nil, "" } ups = append(ups, v) } return ups, collection } // publicationDiffs measures a worker's pushed candidate on its base in // the publication's private repository: the change files, and the diffs // bound to the publication (protocol 37; an older instance has no words // for either). Any failure is a diagnostic: the push stands, with fewer // facts. func (e *Engineer) publicationDiffs(ctx context.Context, p pubRow, dir string) (*wire.ChangeFiles, string, []wire.ChangeDiffUpload) { if e.O.Protocol == nil || e.O.Protocol() < wire.ProtocolMacEngineering { return nil, "", nil } files, known := e.screenChangeFiles(ctx, p.Repo, changeFiles(ctx, e.O.Runner.GitPath, dir, p.BaseSHA, p.CandidateSHA)) if files == nil { e.log("publication change files", errors.New("the candidate could not be measured on its base, or not safely")) return nil, "", nil } e.diffCollect.Lock() defer e.diffCollect.Unlock() ups, collection := changeDiffUploads(ctx, wire.ChangeDiffUpload{TaskID: p.TaskID, StepID: p.StepID, Attempt: p.Attempt, Publication: p.Publication}, e.O.Runner.GitPath, dir, files, known) if len(ups) == 0 { e.log("publication change diffs", errors.New("no diffs for the candidate")) } return files, collection, ups }