oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package checks
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "encoding/hex"
8 "encoding/json"
9 "io"
10 "io/fs"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "reflect"
15 "runtime"
16 "slices"
17 "strings"
18
19 "amadan.net/oficina/equipo/internal/runner/workspace"
20
21 "amadan.net/oficina/equipo/internal/equipo/team"
22 "amadan.net/oficina/equipo/internal/runner/provider"
23 "amadan.net/oficina/equipo/internal/runnerproto"
24)
25
26type Command = runnerproto.CheckCommand
27type File = runnerproto.CheckFile
28type Definition = runnerproto.CheckDefinition
29type Reproduction = runnerproto.Reproduction
30type TestBaseline = runnerproto.TestBaseline
31type TestIdentity = team.TestIdentity
32
33func Digest(b []byte) string { h := sha256.Sum256(b); return hex.EncodeToString(h[:]) }
34func encode(v any) []byte { b, _ := json.Marshal(v); return b }
35func hexID(s string, n int) bool {
36 b, e := hex.DecodeString(s)
37 return e == nil && len(b)*2 == n && s == strings.ToLower(s)
38}
39func objectID(s string) bool { return hexID(s, 40) || hexID(s, 64) }
40func relative(p string) bool {
41 return p != "" && p != "." && filepath.IsLocal(p) && filepath.Clean(p) == p && !strings.ContainsAny(p, "\\\x00") && p != ".git" && !strings.HasPrefix(p, ".git/")
42}
43func commandValid(c Command, measured bool) bool {
44 if len(c.Argv) == 0 || c.TimeoutSeconds < 1 || c.TimeoutSeconds > 1200 || !(c.Dir == "." || relative(c.Dir)) {
45 return false
46 }
47 for _, arg := range c.Argv {
48 if arg == "" || strings.ContainsRune(arg, 0) {
49 return false
50 }
51 }
52 if c.Parser == "exit" {
53 return !measured && !(len(c.Argv) > 1 && filepath.Base(c.Argv[0]) == "go" && c.Argv[1] == "test")
54 }
55 if c.Parser != "go-test-json" || len(c.Argv) < 4 || c.Argv[0] != "go" || c.Argv[1] != "test" {
56 return false
57 }
58 jsonFlag, count, packages := false, false, false
59 // Only flags that preserve complete discovery are accepted in v1.
60 for _, arg := range c.Argv[2:] {
61 switch {
62 case arg == "-json":
63 jsonFlag = true
64 case arg == "-count=1":
65 count = true
66 case arg == "./..." || arg == "." || relative(arg) && !strings.HasPrefix(arg, "-"):
67 packages = true
68 case strings.HasPrefix(arg, "-tags="):
69 case arg == "-short":
70 default:
71 return false
72 }
73 }
74 return jsonFlag && count && packages
75}
76func ParseDefinition(ctx context.Context, b []byte, repo, base string) (Definition, error) {
77 var d Definition
78 if ctx.Err() != nil {
79 return d, ctx.Err()
80 }
81 if runnerproto.DecodeLimit(bytes.NewReader(b), &d, team.MaxArtifactBytes) != nil {
82 return d, provider.ErrContract
83 }
84 if d.Repository == "" {
85 d.Repository = repo
86 }
87 if d.Base == "" {
88 d.Base = base
89 }
90 if d.Version != 1 || repo == "" || d.Repository != repo || d.Base != base || !objectID(base) || len(d.Commands) == 0 || !commandValid(d.Reproduction, true) {
91 return d, provider.ErrContract
92 }
93 if d.Render != nil && (d.Render.Version != 1 || d.Render.Command.Parser != "exit" || !commandValid(d.Render.Command, false) || !exitMaterialDeclared(d, d.Render.Command)) {
94 return d, provider.ErrContract
95 }
96 measured := false
97 for _, c := range d.Commands {
98 if !commandValid(c, false) || !exitMaterialDeclared(d, c) {
99 return d, provider.ErrContract
100 }
101 if c.Parser == "go-test-json" {
102 measured = true
103 if !reflect.DeepEqual(c, d.Reproduction) {
104 return d, provider.ErrContract
105 }
106 }
107 }
108 if !measured {
109 return d, provider.ErrContract
110 }
111 if d.GOOS == "" {
112 d.GOOS = runtime.GOOS
113 }
114 if d.GOARCH == "" {
115 d.GOARCH = runtime.GOARCH
116 }
117 if d.GOOS != runtime.GOOS || d.GOARCH != runtime.GOARCH {
118 return d, provider.ErrContract
119 }
120 if len(d.Baseline.Names) > 0 && d.Baseline.Hash != setHash(d.Baseline.Names) {
121 return d, provider.ErrIdentity
122 }
123 for _, p := range d.TrustedPaths {
124 if !relative(p) || strings.HasSuffix(p, "_test.go") {
125 return d, provider.ErrContract
126 }
127 }
128 for _, f := range d.Files {
129 if !trustedMaterial(d, f.Path) || strings.HasSuffix(f.Path, "_test.go") {
130 return d, provider.ErrContract
131 }
132 }
133 if err := filesValid(d.Files, false); err != nil {
134 return d, err
135 }
136 seen := map[string]bool{}
137 for _, p := range d.TestFiles {
138 if !relative(p) || !strings.HasSuffix(p, "_test.go") || seen[p] {
139 return d, provider.ErrContract
140 }
141 seen[p] = true
142 }
143 return d, nil
144}
145func filesValid(files []File, tests bool) error {
146 seen := map[string]bool{}
147 total := 0
148 for _, f := range files {
149 total += len(f.Bytes)
150 if !relative(f.Path) || seen[f.Path] || tests && !strings.HasSuffix(f.Path, "_test.go") || total > team.MaxArtifactBytes {
151 return provider.ErrContract
152 }
153 seen[f.Path] = true
154 }
155 return nil
156}
157func namesSorted(names []TestIdentity) []TestIdentity {
158 out := append([]TestIdentity(nil), names...)
159 slices.SortFunc(out, func(a, b TestIdentity) int {
160 if c := strings.Compare(a.Package, b.Package); c != 0 {
161 return c
162 }
163 return strings.Compare(a.Name, b.Name)
164 })
165 return slices.Compact(out)
166}
167func setHash(names []TestIdentity) string { return Digest(encode(namesSorted(names))) }
168func superset(observed, required []TestIdentity) bool {
169 if len(required) == 0 {
170 return false
171 }
172 for _, r := range required {
173 if r.Package == "" || !slices.Contains(observed, r) {
174 return false
175 }
176 }
177 return true
178}
179
180func FreezeMaterial(ctx context.Context, d Definition, base string) (Definition, error) {
181 d.Files = nil
182 d.TestFiles = nil
183 var total int64
184 for _, p := range d.TrustedPaths {
185 if err := safePath(base, p, false); err != nil {
186 return d, err
187 }
188 }
189 err := filepath.WalkDir(base, func(path string, entry fs.DirEntry, err error) error {
190 if err != nil {
191 return err
192 }
193 if ctx.Err() != nil {
194 return ctx.Err()
195 }
196 rel, e := filepath.Rel(base, path)
197 if e != nil {
198 return e
199 }
200 if rel == ".git" {
201 return filepath.SkipDir
202 }
203 if entry.Type()&os.ModeSymlink != 0 {
204 return provider.ErrPolicy
205 }
206 if entry.IsDir() {
207 return nil
208 }
209 if !entry.Type().IsRegular() {
210 return provider.ErrPolicy
211 }
212 if strings.HasSuffix(rel, "_test.go") {
213 d.TestFiles = append(d.TestFiles, rel)
214 }
215 if trustedMaterial(d, rel) {
216 if strings.HasSuffix(rel, "_test.go") {
217 return provider.ErrContract
218 }
219 info, e := entry.Info()
220 if e != nil {
221 return provider.ErrContract
222 }
223 total += info.Size()
224 if total > team.MaxArtifactBytes {
225 return provider.ErrContract
226 }
227 b, e := os.ReadFile(path)
228 if e != nil {
229 return e
230 }
231 d.Files = append(d.Files, File{Path: rel, Bytes: b})
232 }
233 return nil
234 })
235 if err != nil {
236 return d, err
237 }
238 if filesValid(d.Files, false) != nil || len(encode(d)) > team.MaxArtifactBytes {
239 return d, provider.ErrContract
240 }
241 return d, nil
242}
243func LoadDefinition(ctx context.Context, baseRoot, repo, base string) (Definition, error) {
244 p := filepath.Join(baseRoot, ".equipo/checks.json")
245 if err := safePath(baseRoot, ".equipo/checks.json", false); err != nil {
246 return Definition{}, err
247 }
248 b, err := os.ReadFile(p)
249 if err != nil {
250 return Definition{}, provider.ErrContract
251 }
252 d, err := ParseDefinition(ctx, b, repo, base)
253 if err != nil {
254 return d, err
255 }
256 return FreezeMaterial(ctx, d, baseRoot)
257}
258func safePath(root, rel string, missing bool) error {
259 if !relative(rel) {
260 return provider.ErrPolicy
261 }
262 cur := root
263 for _, part := range strings.Split(rel, string(filepath.Separator)) {
264 cur = filepath.Join(cur, part)
265 st, err := os.Lstat(cur)
266 if os.IsNotExist(err) && missing {
267 return nil
268 }
269 if err != nil {
270 return provider.ErrPolicy
271 }
272 if st.Mode()&os.ModeSymlink != 0 {
273 return provider.ErrPolicy
274 }
275 }
276 return nil
277}
278func copyTree(src, dst string) error {
279 if err := os.Mkdir(dst, 0700); err != nil {
280 return err
281 }
282 return filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {
283 if err != nil {
284 return err
285 }
286 rel, e := filepath.Rel(src, path)
287 if e != nil {
288 return e
289 }
290 if rel == "." {
291 return nil
292 }
293 if rel == ".git" {
294 return filepath.SkipDir
295 }
296 if d.Type()&os.ModeSymlink != 0 {
297 return provider.ErrPolicy
298 }
299 to := filepath.Join(dst, rel)
300 if d.IsDir() {
301 return os.Mkdir(to, 0700)
302 }
303 if !d.Type().IsRegular() {
304 return provider.ErrPolicy
305 }
306 b, e := os.ReadFile(path)
307 if e != nil {
308 return e
309 }
310 info, e := d.Info()
311 if e != nil {
312 return e
313 }
314 return os.WriteFile(to, b, info.Mode().Perm()&0700)
315 })
316}
317
318func gitBytes(ctx context.Context, repo string, args ...string) ([]byte, error) {
319 cmd := exec.CommandContext(ctx, "/usr/bin/git", args...)
320 cmd.Dir = repo
321 cmd.Env = []string{"HOME=/nonexistent"}
322 for k, v := range workspace.GitEnvironment() {
323 cmd.Env = append(cmd.Env, k+"="+v)
324 }
325 cmd.Stderr = io.Discard
326 b, err := cmd.Output()
327 if err != nil {
328 return nil, provider.ErrIdentity
329 }
330 return b, nil
331}
332func ExportBase(ctx context.Context, repo, commit, dest string) error {
333 if !objectID(commit) {
334 return provider.ErrIdentity
335 }
336 kind, err := gitBytes(ctx, repo, "cat-file", "-t", commit)
337 if err != nil || string(kind) != "commit\n" {
338 return provider.ErrIdentity
339 }
340 tree, err := gitBytes(ctx, repo, "ls-tree", "-rz", "--full-tree", commit)
341 if err != nil {
342 return err
343 }
344 if err = os.Mkdir(dest, 0700); err != nil {
345 return err
346 }
347 ok := false
348 defer func() {
349 if !ok {
350 _ = os.RemoveAll(dest)
351 }
352 }()
353 for _, entry := range bytes.Split(tree, []byte{0}) {
354 if len(entry) == 0 {
355 continue
356 }
357 parts := bytes.SplitN(entry, []byte{'\t'}, 2)
358 if len(parts) != 2 {
359 return provider.ErrIdentity
360 }
361 fields := strings.Fields(string(parts[0]))
362 path := string(parts[1])
363 if len(fields) != 3 || fields[1] != "blob" || (fields[0] != "100644" && fields[0] != "100755") || !objectID(fields[2]) || !relative(path) {
364 return provider.ErrIdentity
365 }
366 b, err := gitBytes(ctx, repo, "cat-file", "blob", fields[2])
367 if err != nil {
368 return err
369 }
370 p := filepath.Join(dest, path)
371 if err = os.MkdirAll(filepath.Dir(p), 0700); err != nil {
372 return err
373 }
374 mode := os.FileMode(0600)
375 if fields[0] == "100755" {
376 mode = 0700
377 }
378 if err = os.WriteFile(p, b, mode); err != nil {
379 return err
380 }
381 }
382 ok = true
383 return nil
384}
385func LoadBaseDefinition(ctx context.Context, repoDir, repository, base, scratchRoot string) (Definition, error) {
386 dir, err := os.MkdirTemp(scratchRoot, "definition-")
387 if err != nil {
388 return Definition{}, err
389 }
390 defer os.RemoveAll(dir)
391 work := filepath.Join(dir, "base")
392 if err = ExportBase(ctx, repoDir, base, work); err != nil {
393 return Definition{}, err
394 }
395 return LoadDefinition(ctx, work, repository, base)
396}
397
398func CandidateHash(c team.GitCandidate) string {
399 return Digest(encode(map[string]string{"repository": c.Repository, "base_commit": c.BaseCommit, "commit": c.Commit, "tree": c.Tree}))
400}
401
402var baseMaterialPaths = []string{".equipo/checks.json", "go.mod", "go.sum", "go.work", "go.work.sum", "Makefile", "GNUmakefile", "makefile", ".amadan/ci", ".amadan/ci.d"}
403
404func materialPaths(d Definition) []string {
405 return append(append([]string(nil), baseMaterialPaths...), d.TrustedPaths...)
406}
407func trustedMaterial(d Definition, path string) bool {
408 for _, p := range materialPaths(d) {
409 if within(p, path) {
410 return true
411 }
412 }
413 return false
414}
415
416func exitMaterialDeclared(d Definition, c Command) bool {
417 if c.Parser != "exit" {
418 return true
419 }
420 program := filepath.Base(c.Argv[0])
421 if c.Argv[0] != program && c.Argv[0] != "/bin/"+program && c.Argv[0] != "/usr/bin/"+program {
422 return false
423 }
424 switch program {
425 case "sh", "bash":
426 if len(c.Argv) < 2 || strings.HasPrefix(c.Argv[1], "-") || !frozenArgument(d, c.Dir, c.Argv[1]) {
427 return false
428 }
429 case "make":
430 // Default makefiles are pinned at the repository root. No option or variable overrides.
431 if c.Dir != "." {
432 return false
433 }
434 for _, arg := range c.Argv[1:] {
435 if strings.HasPrefix(arg, "-") || strings.Contains(arg, "=") {
436 return false
437 }
438 }
439 case "go":
440 // vet uses its default package. Explicit path operands must be frozen below.
441 if c.Argv[0] != "go" || len(c.Argv) < 2 || c.Argv[1] != "vet" {
442 return false
443 }
444 for _, arg := range c.Argv[2:] {
445 if strings.HasPrefix(arg, "-") || !frozenArgument(d, c.Dir, arg) {
446 return false
447 }
448 }
449 return true
450 default:
451 return false
452 }
453 for _, arg := range c.Argv[1:] {
454 value := arg
455 if _, after, ok := strings.Cut(arg, "="); ok {
456 value = after
457 }
458 if strings.ContainsAny(value, "/\\") || strings.HasPrefix(value, ".") || filepath.Ext(value) != "" {
459 if !frozenArgument(d, c.Dir, value) {
460 return false
461 }
462 }
463 }
464 return true
465}
466
467func frozenArgument(d Definition, dir, arg string) bool {
468 return relative(arg) && trustedMaterial(d, filepath.Join(dir, arg))
469}
470