| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/base64" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "os/exec" |
| 10 | "slices" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "time" |
| 14 | "unicode/utf8" |
| 15 | |
| 16 | "amadan.net/oficina/equipo/internal/diffscan" |
| 17 | "amadan.net/oficina/equipo/internal/runner/forge" |
| 18 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 19 | "amadan.net/oficina/equipo/internal/wire" |
| 20 | ) |
| 21 | |
| 22 | func displayGit(ctx context.Context, git, dir string, limit int, args ...string) (string, bool, error) { |
| 23 | cmd := exec.CommandContext(ctx, git, append([]string{"--git-dir=" + dir, "-c", "core.quotePath=false", "-c", "core.hooksPath=/nonexistent"}, args...)...) |
| 24 | env := workspace.GitEnvironment() |
| 25 | env["HOME"] = "/nonexistent" |
| 26 | env["GIT_LITERAL_PATHSPECS"] = "1" |
| 27 | env["GIT_NO_LAZY_FETCH"] = "1" |
| 28 | env["GIT_ALLOW_PROTOCOL"] = "" |
| 29 | for k, v := range env { |
| 30 | cmd.Env = append(cmd.Env, k+"="+v) |
| 31 | } |
| 32 | raw, cut, err := boundedOutput(cmd, limit) |
| 33 | return string(raw), cut, err |
| 34 | } |
| 35 | |
| 36 | // Read only a regular Git blob. Tree modes, object size and aggregate input |
| 37 | // are checked before cat-file; a checkout symlink is never dereferenced. |
| 38 | func displayBlob(ctx context.Context, git, dir, sha, path string, budget *int) (string, string) { |
| 39 | if sha == "" { |
| 40 | return "", "" |
| 41 | } |
| 42 | raw, cut, err := displayGit(ctx, git, dir, 8192, "ls-tree", "-z", sha, "--", path) |
| 43 | if err != nil || cut { |
| 44 | return "", wire.DiffUnavailable |
| 45 | } |
| 46 | if raw == "" { |
| 47 | return "", "" |
| 48 | } |
| 49 | if strings.Count(raw, "\x00") != 1 { |
| 50 | return "", wire.DiffUnavailable |
| 51 | } |
| 52 | header, name, ok := strings.Cut(strings.TrimSuffix(raw, "\x00"), "\t") |
| 53 | fields := strings.Fields(header) |
| 54 | if !ok || name != path || len(fields) != 3 || fields[0] != "100644" && fields[0] != "100755" || fields[1] != "blob" || !shaPattern.MatchString(fields[2]) { |
| 55 | return "", wire.DiffUnavailable |
| 56 | } |
| 57 | size, cut, err := displayGit(ctx, git, dir, 64, "cat-file", "-s", fields[2]) |
| 58 | n, e := strconv.Atoi(strings.TrimSpace(size)) |
| 59 | if err != nil || cut || e != nil || n < 0 { |
| 60 | return "", wire.DiffUnavailable |
| 61 | } |
| 62 | if n > wire.MaxDiffBlobBytes || n > *budget { |
| 63 | return "", wire.DiffTooLarge |
| 64 | } |
| 65 | *budget -= n |
| 66 | data, cut, err := displayGit(ctx, git, dir, n, "cat-file", "blob", fields[2]) |
| 67 | if err != nil || cut || len(data) != n { |
| 68 | return "", wire.DiffUnavailable |
| 69 | } |
| 70 | if !utf8.ValidString(data) || strings.ContainsRune(data, 0) { |
| 71 | return "", wire.DiffBinary |
| 72 | } |
| 73 | return data, "" |
| 74 | } |
| 75 | |
| 76 | func collectChangeDiffs(ctx context.Context, git, dir string, facts *wire.ChangeFiles, known []string) []wire.FileDiff { |
| 77 | if !wire.ValidChangeFiles(facts) { |
| 78 | return nil |
| 79 | } |
| 80 | ctx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| 81 | defer cancel() |
| 82 | entries := slices.Clone(facts.Entries) |
| 83 | slices.SortFunc(entries, func(a, b wire.ChangedFile) int { return strings.Compare(a.Path, b.Path) }) |
| 84 | files := make([]wire.FileDiff, 0, len(entries)) |
| 85 | input, left := wire.MaxDiffInputBytes, wire.MaxCandidateDiffBytes |
| 86 | for _, file := range entries { |
| 87 | d := wire.FileDiff{Path: file.Path, Reason: wire.DiffUnavailable} |
| 88 | if ctx.Err() != nil { |
| 89 | files = append(files, d) |
| 90 | continue |
| 91 | } |
| 92 | if file.Binary { |
| 93 | d.Reason = wire.DiffBinary |
| 94 | files = append(files, d) |
| 95 | continue |
| 96 | } |
| 97 | old := file.Path |
| 98 | if file.OldPath != "" { |
| 99 | old = file.OldPath |
| 100 | } |
| 101 | before, why := displayBlob(ctx, git, dir, facts.Base, old, &input) |
| 102 | if why == "" { |
| 103 | why = diffscan.Check(ctx, before, known) |
| 104 | } |
| 105 | if why == "" { |
| 106 | var after string |
| 107 | after, why = displayBlob(ctx, git, dir, facts.SHA, file.Path, &input) |
| 108 | if why == "" { |
| 109 | why = diffscan.Check(ctx, after, known) |
| 110 | } |
| 111 | } |
| 112 | if why != "" { |
| 113 | d.Reason = why |
| 114 | files = append(files, d) |
| 115 | continue |
| 116 | } |
| 117 | pair := []string{facts.Base, facts.SHA} |
| 118 | if facts.Base == "" { |
| 119 | pair = []string{"--root", "--no-commit-id", facts.SHA} |
| 120 | } |
| 121 | args := append([]string{"diff-tree", "-p", "-r", "-M", "--no-ext-diff", "--no-textconv", "--no-color"}, pair...) |
| 122 | args = append(args, "--", file.Path) |
| 123 | if old != file.Path { |
| 124 | args = append(args, old) |
| 125 | } |
| 126 | patch, cut, err := displayGit(ctx, git, dir, wire.MaxFileDiffBytes, args...) |
| 127 | // Overflow kills Git intentionally. The complete input blobs were scanned. |
| 128 | if ctx.Err() != nil || err != nil && !cut { |
| 129 | files = append(files, d) |
| 130 | continue |
| 131 | } |
| 132 | patch, clipped := clipDisplayPatch(patch) |
| 133 | d = wire.FileDiff{Path: file.Path, Patch: patch, Truncated: cut || clipped} |
| 134 | if len(patch) > left { |
| 135 | d = wire.FileDiff{Path: file.Path, Reason: wire.DiffTooLarge} |
| 136 | } else if why := diffscan.Check(ctx, patch, known); why != "" { |
| 137 | d = wire.FileDiff{Path: file.Path, Reason: why} |
| 138 | } |
| 139 | if !wire.ValidFileDiff(d) { |
| 140 | d = wire.FileDiff{Path: file.Path, Reason: wire.DiffUnavailable} |
| 141 | } |
| 142 | left -= len(d.Patch) |
| 143 | files = append(files, d) |
| 144 | } |
| 145 | return files |
| 146 | } |
| 147 | |
| 148 | func clipDisplayPatch(s string) (string, bool) { |
| 149 | end, lines := 0, 0 |
| 150 | for end < len(s) && lines < wire.MaxFileDiffLines { |
| 151 | n := strings.IndexByte(s[end:], '\n') |
| 152 | if n < 0 || end+n+1 > wire.MaxFileDiffBytes { |
| 153 | break |
| 154 | } |
| 155 | end += n + 1 |
| 156 | lines++ |
| 157 | } |
| 158 | return s[:end], end < len(s) |
| 159 | } |
| 160 | |
| 161 | // queueChangeDiffs queues the display diffs of f, already screened |
| 162 | // (screenChangeFiles) against known. |
| 163 | func (e *Engineer) queueChangeDiffs(ctx context.Context, r stepRow, git, dir string, f *wire.ChangeFiles, known []string) string { |
| 164 | if f == nil || e.O.State == nil || e.O.Protocol == nil || e.O.Protocol() < wire.ProtocolChangeDiffs || !e.diffCollect.TryLock() { |
| 165 | return "" |
| 166 | } |
| 167 | defer e.diffCollect.Unlock() |
| 168 | ups, collection := changeDiffUploads(ctx, wire.ChangeDiffUpload{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt}, git, dir, f, known) |
| 169 | if len(ups) == 0 { |
| 170 | return "" |
| 171 | } |
| 172 | err := e.O.State.tx(ctx, func(tx *sql.Tx) error { |
| 173 | for _, v := range ups { |
| 174 | if err := e.O.State.enqueue(tx, wire.FrameChangeDiff, "", v); err != nil { |
| 175 | return err |
| 176 | } |
| 177 | } |
| 178 | return nil |
| 179 | }) |
| 180 | if err != nil { |
| 181 | return "" |
| 182 | } |
| 183 | return collection |
| 184 | } |
| 185 | |
| 186 | // knownSecrets are the secrets this runner knows that must never reach a |
| 187 | // display measurement: its diff secrets (the runner's bearer token) and |
| 188 | // the forge credential it already uses for repo. ok is false when the |
| 189 | // credential cannot be read. |
| 190 | func (e *Engineer) knownSecrets(ctx context.Context, repo string) (known []string, ok bool) { |
| 191 | known = slices.Clone(e.DiffSecrets) |
| 192 | // Read only the credential file already used for this runner's forge work; |
| 193 | // never resolve a remote credential or access the network for display. |
| 194 | if e.O.Runner.AmadanCredentialPath != "" { |
| 195 | credential, err := (forge.FileCredentials{Path: e.O.Runner.AmadanCredentialPath}).Credential(ctx, repo) |
| 196 | if err != nil { |
| 197 | return nil, false |
| 198 | } |
| 199 | known = append(known, credential.Bearer, credential.GitPassword) |
| 200 | } |
| 201 | return known, true |
| 202 | } |
| 203 | |
| 204 | // screenChangeFiles is f as it may leave this runner, with the known |
| 205 | // secrets it was screened against: nil when they cannot be read, or when |
| 206 | // a listed file name or a renamed file's old name holds one of them or |
| 207 | // anything else a diff would withhold (a file name can be the secret, |
| 208 | // and it travels in the change files and in every diff upload). |
| 209 | func (e *Engineer) screenChangeFiles(ctx context.Context, repo string, f *wire.ChangeFiles) (*wire.ChangeFiles, []string) { |
| 210 | if f == nil { |
| 211 | return nil, nil |
| 212 | } |
| 213 | known, ok := e.knownSecrets(ctx, repo) |
| 214 | if !ok { |
| 215 | return nil, nil |
| 216 | } |
| 217 | for _, entry := range f.Entries { |
| 218 | for _, name := range []string{entry.Path, entry.OldPath} { |
| 219 | if name != "" && diffscan.Check(ctx, name, known) != "" { |
| 220 | e.log("change files", errors.New("a file name is withheld, so the measurement is")) |
| 221 | return nil, nil |
| 222 | } |
| 223 | } |
| 224 | } |
| 225 | return f, known |
| 226 | } |
| 227 | |
| 228 | // changeDiffUploads is the display collection of f as uploads naming |
| 229 | // at's task, step, attempt and (for a worker's candidate) publication, |
| 230 | // with the known secrets left out. Nothing when a frame would be too |
| 231 | // large. |
| 232 | func changeDiffUploads(ctx context.Context, at wire.ChangeDiffUpload, git, dir string, f *wire.ChangeFiles, known []string) ([]wire.ChangeDiffUpload, string) { |
| 233 | files := collectChangeDiffs(ctx, git, dir, f, known) |
| 234 | if len(files) == 0 { |
| 235 | return nil, "" |
| 236 | } |
| 237 | collection := wire.DiffCollection(files) |
| 238 | ups := make([]wire.ChangeDiffUpload, 0, len(files)) |
| 239 | for i, file := range files { |
| 240 | 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} |
| 241 | raw, _ := json.Marshal(v) |
| 242 | if len(raw) > wire.MaxFrameBytes-1024 { |
| 243 | return nil, "" |
| 244 | } |
| 245 | ups = append(ups, v) |
| 246 | } |
| 247 | return ups, collection |
| 248 | } |
| 249 | |
| 250 | // publicationDiffs measures a worker's pushed candidate on its base in |
| 251 | // the publication's private repository: the change files, and the diffs |
| 252 | // bound to the publication (protocol 37; an older instance has no words |
| 253 | // for either). Any failure is a diagnostic: the push stands, with fewer |
| 254 | // facts. |
| 255 | func (e *Engineer) publicationDiffs(ctx context.Context, p pubRow, dir string) (*wire.ChangeFiles, string, []wire.ChangeDiffUpload) { |
| 256 | if e.O.Protocol == nil || e.O.Protocol() < wire.ProtocolMacEngineering { |
| 257 | return nil, "", nil |
| 258 | } |
| 259 | files, known := e.screenChangeFiles(ctx, p.Repo, changeFiles(ctx, e.O.Runner.GitPath, dir, p.BaseSHA, p.CandidateSHA)) |
| 260 | if files == nil { |
| 261 | e.log("publication change files", errors.New("the candidate could not be measured on its base, or not safely")) |
| 262 | return nil, "", nil |
| 263 | } |
| 264 | e.diffCollect.Lock() |
| 265 | defer e.diffCollect.Unlock() |
| 266 | 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) |
| 267 | if len(ups) == 0 { |
| 268 | e.log("publication change diffs", errors.New("no diffs for the candidate")) |
| 269 | } |
| 270 | return files, collection, ups |
| 271 | } |
| 272 | |