oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package mac
2
3import (
4 "context"
5 "errors"
6 "os"
7 "path/filepath"
8 "strings"
9 "sync"
10 "testing"
11 "time"
12
13 "amadan.net/oficina/equipo/internal/wire"
14)
15
16// userTempFixture is a stand-in for /private/var/folders with one
17// user's T in it, 0700 and this test's own.
18func userTempFixture(t *testing.T) (prefix, temp string) {
19 t.Helper()
20 prefix, err := filepath.EvalSymlinks(t.TempDir())
21 if err != nil {
22 t.Fatal(err)
23 }
24 temp = filepath.Join(prefix, "4m", "abc123_def", "T")
25 if err := os.MkdirAll(temp, 0700); err != nil {
26 t.Fatal(err)
27 }
28 return prefix, temp
29}
30
31func getconf(out string, err error) Exec {
32 return func(_ context.Context, name string, args ...string) (string, error) {
33 if name != "/usr/bin/getconf" || strings.Join(args, " ") != "DARWIN_USER_TEMP_DIR" {
34 return "", errors.New("not getconf")
35 }
36 return out, err
37 }
38}
39
40// T is getconf's answer with its symlinks resolved and no trailing
41// slash, and only when it is the runner user's own 0700 directory
42// under the system's user folders; otherwise why, in words.
43func TestUserTemp(t *testing.T) {
44 prefix, temp := userTempFixture(t)
45 uid := os.Getuid()
46 // macOS names it through /var, a symlink to /private/var.
47 link := filepath.Join(t.TempDir(), "var-T")
48 if err := os.Symlink(temp, link); err != nil {
49 t.Fatal(err)
50 }
51 if got, err := UserTemp(context.Background(), getconf(link+"/\n", nil), uid, prefix); err != nil || got != temp {
52 t.Fatalf("resolved %q %v, want %q", got, err, temp)
53 }
54 refused := func(name, why string, x Exec, uid int) {
55 t.Helper()
56 got, err := UserTemp(context.Background(), x, uid, prefix)
57 var e *UserTempError
58 if got != "" || !errors.Is(err, ErrUserTemp) || !errors.As(err, &e) || e.Why != why || strings.Contains(e.Why, "/") {
59 t.Fatalf("%s: %q %v", name, got, err)
60 }
61 }
62 refused("another owner", "another user owns it", getconf(temp, nil), uid+1)
63 refused("getconf failed", "getconf did not name it", getconf("", errors.New("exit 1")), uid)
64 refused("relative", "getconf did not name it", getconf("T/", nil), uid)
65 refused("missing", "it does not exist", getconf(temp+"-gone", nil), uid)
66 refused("the prefix itself", "it is not under the system's user folders", getconf(prefix, nil), uid)
67 elsewhere := t.TempDir()
68 if err := os.Chmod(elsewhere, 0700); err != nil {
69 t.Fatal(err)
70 }
71 refused("outside the user folders", "it is not under the system's user folders", getconf(elsewhere, nil), uid)
72 // A link inside the user folders that leads out of them.
73 if err := os.Symlink(elsewhere, filepath.Join(prefix, "out")); err != nil {
74 t.Fatal(err)
75 }
76 refused("linked out", "it is not under the system's user folders", getconf(filepath.Join(prefix, "out"), nil), uid)
77 file := filepath.Join(prefix, "file")
78 if err := os.WriteFile(file, nil, 0700); err != nil {
79 t.Fatal(err)
80 }
81 refused("a file", "it is not a directory", getconf(file, nil), uid)
82 if err := os.Chmod(temp, 0755); err != nil {
83 t.Fatal(err)
84 }
85 refused("readable by others", "its mode is not 0700", getconf(temp, nil), uid)
86}
87
88// tempTree writes what T holds before an attempt: a file, a folder,
89// TemporaryItems with one entry, and a folder outside T.
90func tempTree(t *testing.T, temp string) (outside string) {
91 t.Helper()
92 for _, d := range []string{"keepdir", "TemporaryItems/old", "shared"} {
93 if err := os.MkdirAll(filepath.Join(temp, d), 0700); err != nil {
94 t.Fatal(err)
95 }
96 }
97 for _, f := range []string{"keep", "shared/a"} {
98 if err := os.WriteFile(filepath.Join(temp, f), []byte("before"), 0600); err != nil {
99 t.Fatal(err)
100 }
101 }
102 outside = t.TempDir()
103 if err := os.WriteFile(filepath.Join(outside, "precious"), []byte("x"), 0600); err != nil {
104 t.Fatal(err)
105 }
106 return outside
107}
108
109func exists(p string) bool { _, err := os.Lstat(p); return err == nil }
110
111// Once a sandboxed run is proven over, what appeared in T and in
112// T/TemporaryItems goes and what was there stays, even rewritten; a
113// symlink goes as itself, never what it leads to.
114func TestGateCleansUserTemp(t *testing.T) {
115 g, dir := gateFixture(t, true)
116 _, temp := userTempFixture(t)
117 outside := tempTree(t, temp)
118 g.UserTemp = temp
119 script := `T=` + quote(temp) + `
120echo after > "$T/keep"
121mkdir -p "$T/new/deep" "$T/swbuild.tmp.1" "$T/TemporaryItems/NSIRD_xcodebuild_1" && touch "$T/new/deep/f" "$T/TemporaryDirectory.2"
122ln -s ` + quote(outside) + ` "$T/link"
123ln -s ` + quote(outside) + ` "$T/TemporaryItems/NSIRD_link"`
124 if res, _ := run(g, dir, "checks-t-1", time.Minute, script); res.Code != 0 || !res.Terminated {
125 t.Fatalf("%+v", res)
126 }
127 for _, kept := range []string{"keep", "keepdir", "shared/a", "TemporaryItems", "TemporaryItems/old"} {
128 if !exists(filepath.Join(temp, kept)) {
129 t.Fatalf("%s was there before and is gone", kept)
130 }
131 }
132 for _, gone := range []string{"new", "swbuild.tmp.1", "TemporaryDirectory.2", "link", "TemporaryItems/NSIRD_xcodebuild_1", "TemporaryItems/NSIRD_link"} {
133 if exists(filepath.Join(temp, gone)) {
134 t.Fatalf("%s appeared during the run and is left", gone)
135 }
136 }
137 if !exists(filepath.Join(outside, "precious")) {
138 t.Fatal("the cleanup followed a symlink out of T")
139 }
140}
141
142// TemporaryItems swapped for a symlink to a folder that was in T before:
143// the link goes, the folder and what it held stay.
144func TestGateCleanupKeepsASwappedTemporaryItemsTarget(t *testing.T) {
145 g, dir := gateFixture(t, true)
146 _, temp := userTempFixture(t)
147 tempTree(t, temp)
148 g.UserTemp = temp
149 // Relative, so it stays inside T, where os.Root would follow it.
150 script := `T=` + quote(temp) + `; rm -rf "$T/TemporaryItems" && ln -s shared "$T/TemporaryItems"`
151 if res, _ := run(g, dir, "checks-t-2", time.Minute, script); res.Code != 0 || !res.Terminated {
152 t.Fatalf("%+v", res)
153 }
154 if exists(filepath.Join(temp, "TemporaryItems")) || !exists(filepath.Join(temp, "shared/a")) {
155 t.Fatal("a swapped TemporaryItems was followed, or left")
156 }
157}
158
159// A run whose end is not proven may still be writing T: nothing is
160// removed then; by that attempt's own proof (Verify), never by the next
161// gate's turn.
162func TestGateCleanupWaitsForTheProvenEnd(t *testing.T) {
163 g, dir := gateFixture(t, true)
164 _, temp := userTempFixture(t)
165 g.UserTemp, g.Settle, g.Turns = temp, 500*time.Millisecond, NewTurns(filepath.Join(t.TempDir(), "lock"))
166 g.procs = withPhantom()
167 quieted := 0
168 g.QuietSimulators = func(context.Context) { quieted++ }
169 res, id := run(g, dir, "checks-t-3", time.Minute, `touch `+quote(filepath.Join(temp, "late")))
170 if res.Terminated || !exists(filepath.Join(temp, "late")) || quieted != 0 {
171 t.Fatalf("cleaned before the end was proven: %+v", res)
172 }
173 // The next gate's turn neither finishes it nor runs.
174 g.procs = nil
175 if res, _ := run(g, dir, "checks-t-3b", time.Minute, `touch `+quote(filepath.Join(temp, "next"))); res.Reason != "checks_unavailable" || exists(filepath.Join(temp, "next")) || !exists(filepath.Join(temp, "late")) || !g.Turns.Pending() {
176 t.Fatalf("another turn finished or ran past the cleanup: %+v", res)
177 }
178 // Its own proof finishes it; then gates run again.
179 if !g.Verify(id) || exists(filepath.Join(temp, "late")) || g.Turns.Pending() {
180 t.Fatal("the attempt's proof did not finish its cleanup")
181 }
182 res, _ = run(g, dir, "checks-t-3c", time.Minute, `ls `+quote(temp)+`; touch `+quote(filepath.Join(temp, "next")))
183 if !res.Terminated || strings.Contains(res.Output, "late") || exists(filepath.Join(temp, "next")) || exists(g.Turns.pending()) {
184 t.Fatalf("not run, or not cleaned, after the proof: %+v", res)
185 }
186 // One that cannot be finished (T is no longer a folder of this
187 // user's): its proof says not over, and nothing runs.
188 g.procs = withPhantom()
189 _, id = run(g, dir, "checks-t-3d", time.Minute, `true`)
190 g.procs = nil
191 if err := os.Chmod(temp, 0755); err != nil {
192 t.Fatal(err)
193 }
194 if g.Verify(id) {
195 t.Fatal("proven over with its cleanup not done")
196 }
197 if res, _ := run(g, dir, "checks-t-3e", time.Minute, `touch `+quote(filepath.Join(temp, "ran"))); res.Reason != "checks_unavailable" || exists(filepath.Join(temp, "ran")) {
198 t.Fatalf("ran with a cleanup left that cannot be finished: %+v", res)
199 }
200 if err := os.Chmod(temp, 0700); err != nil {
201 t.Fatal(err)
202 }
203 if !g.Verify(id) || g.Turns.Pending() {
204 t.Fatal("the cleanup was not finished once it could be")
205 }
206 // A T that cannot be listed: nothing runs.
207 g.UserTemp = filepath.Join(temp, "gone")
208 if res, _ := run(g, dir, "checks-t-4", time.Minute, `touch `+quote(filepath.Join(temp, "ran"))); res.Reason != "checks_unavailable" || exists(filepath.Join(temp, "ran")) {
209 t.Fatalf("ran without a listing of T: %+v", res)
210 }
211}
212
213// Gates sharing the Mac's turns never overlap, sandboxed or not, and one
214// waiting for its turn can be cancelled before anything of it runs.
215func TestGatesTakeTurns(t *testing.T) {
216 // Two processes' turns over one lock file (the worker and
217 // the probe command): as one.
218 lock := filepath.Join(t.TempDir(), "lock")
219 turns := NewTurns(lock)
220 a, dirA := gateFixture(t, true)
221 b, dirB := gateFixture(t, false)
222 a.Turns, b.Turns = turns, NewTurns(lock)
223 log := filepath.Join(t.TempDir(), "log")
224 step := func(name string) string {
225 return `echo ` + name + `-start >> ` + quote(log) + `; sleep 0.3; echo ` + name + `-end >> ` + quote(log)
226 }
227 var wg sync.WaitGroup
228 for _, g := range []struct {
229 g *Gate
230 dir string
231 name string
232 }{{a, dirA, "a"}, {b, dirB, "b"}} {
233 wg.Add(1)
234 go func() {
235 defer wg.Done()
236 if res, _ := run(g.g, g.dir, "checks-turn-"+g.name, time.Minute, step(g.name)); res.Code != 0 {
237 t.Errorf("%s: %+v", g.name, res)
238 }
239 }()
240 }
241 wg.Wait()
242 raw, _ := os.ReadFile(log)
243 lines := strings.Fields(string(raw))
244 if len(lines) != 4 || strings.TrimSuffix(lines[0], "-start") != strings.TrimSuffix(lines[1], "-end") {
245 t.Fatalf("gates overlapped: %v", lines)
246 }
247 held, err := turns.Take(context.Background(), OpEngineering)
248 if err != nil {
249 t.Fatal(err)
250 }
251 if _, ok := b.Turns.TryTake(OpWarm); ok {
252 t.Fatal("TryTake while another holds the turn")
253 }
254 ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
255 defer cancel()
256 res := b.Run(ctx, "checks-turn-c", dirB, []string{"/bin/sh", "-c", "touch " + quote(log+".c")}, time.Minute, func(string) error { return nil })
257 held.Give()
258 if res.Reason != "cancelled" || !res.Terminated || exists(log+".c") {
259 t.Fatalf("ran without its turn: %+v", res)
260 }
261}
262
263// P2 needs the user's T: refused, it says why (in words) and checks
264// wait for the sandbox.
265func TestP2NeedsTheUserTemp(t *testing.T) {
266 f := newProbeFixture(t, allLines("denied"))
267 f.h.Paths.UserTemp, f.h.Paths.UserTempWhy = "", "its mode is not 0700"
268 p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools))
269 if ran || p.Verdict != wire.ProbeUnavailable || p.Detail != "user_temp_refused" {
270 t.Fatalf("%+v", p)
271 }
272}
273
274// What the attempt made unreadable is still removed; a T replaced by a
275// symlink during the run is cleaned by the folder it was (never where
276// the link leads), and the next gate runs nothing.
277func TestGateCleanupHoldsT(t *testing.T) {
278 g, dir := gateFixture(t, true)
279 _, temp := userTempFixture(t)
280 outside := tempTree(t, temp)
281 g.UserTemp, g.Turns = temp, NewTurns(filepath.Join(t.TempDir(), "lock"))
282 locked := `T=` + quote(temp) + `; mkdir -p "$T/left/deep" && touch "$T/left/deep/payload" && chmod 000 "$T/left/deep" "$T/left"`
283 if res, _ := run(g, dir, "checks-t-5", time.Minute, locked); res.Code != 0 || exists(filepath.Join(temp, "left")) || exists(g.Turns.pending()) {
284 t.Fatalf("a locked folder was left: %+v", res)
285 }
286 moved := filepath.Join(filepath.Dir(temp), "T-moved")
287 swap := `T=` + quote(temp) + `; touch "$T/new" && mv "$T" ` + quote(moved) + ` && ln -s ` + quote(outside) + ` "$T"`
288 if res, _ := run(g, dir, "checks-t-6", time.Minute, swap); res.Code != 0 || !res.Terminated {
289 t.Fatalf("%+v", res)
290 }
291 if exists(filepath.Join(moved, "new")) || !exists(filepath.Join(moved, "keep")) || !exists(filepath.Join(outside, "precious")) {
292 t.Fatal("the cleanup did not hold the T it listed")
293 }
294 if res, _ := run(g, dir, "checks-t-7", time.Minute, `touch `+quote(filepath.Join(outside, "ran"))); res.Reason != "checks_unavailable" || exists(filepath.Join(outside, "ran")) {
295 t.Fatalf("ran with T a symlink: %+v", res)
296 }
297}
298
299// The digest names a profile ChecksSettings makes, not a refusal.
300func TestProfileDigest(t *testing.T) {
301 if _, err := ChecksSettings(digestInput()); err != nil {
302 t.Fatal(err)
303 }
304}
305
306// Simulators are shut down once the end is proven and before T is
307// cleaned (CoreSimulator's processes may still be writing it); however
308// long that takes, the cleanup then runs and the run's result stands.
309func TestGateQuietsSimulatorsBeforeCleaning(t *testing.T) {
310 g, dir := gateFixture(t, true)
311 _, temp := userTempFixture(t)
312 g.UserTemp = temp
313 var saw []bool
314 g.QuietSimulators = func(context.Context) {
315 saw = append(saw, exists(filepath.Join(temp, "new")))
316 time.Sleep(300 * time.Millisecond)
317 }
318 res, _ := run(g, dir, "checks-t-8", time.Minute, `touch `+quote(filepath.Join(temp, "new")))
319 if len(saw) != 1 || !saw[0] || exists(filepath.Join(temp, "new")) || res.Code != 0 || res.Reason != "" || !res.Terminated {
320 t.Fatalf("quieted %v before cleaning, result %+v", saw, res)
321 }
322}
323
324// The cleanup is on record before anything of an attempt starts: a
325// runner killed mid-run leaves it to the next gate (any process), which
326// first proves that attempt over, then cleans T, then runs. Not proven,
327// unreadable or unrecordable: nothing runs.
328func TestGatePendingCleanupSurvivesTheRunner(t *testing.T) {
329 g, dir := gateFixture(t, true)
330 _, temp := userTempFixture(t)
331 tempTree(t, temp)
332 lock := filepath.Join(t.TempDir(), "lock")
333 g.UserTemp, g.Turns, g.Settle = temp, NewTurns(lock), 500*time.Millisecond
334 // The killed runner's attempt: its record, then what it left.
335 s, err := openTemp(temp, nil)
336 if err != nil {
337 t.Fatal(err)
338 }
339 if err := g.Turns.writePending(pendingRecord{Attempt: "checks-dead", Before: s.before}); err != nil {
340 t.Fatal(err)
341 }
342 s.close()
343 if err := os.WriteFile(filepath.Join(temp, "leftover"), nil, 0600); err != nil {
344 t.Fatal(err)
345 }
346 // Still running (a process with its marker): nothing runs, nothing goes.
347 g.procs = withPhantom("checks-dead")
348 ran := filepath.Join(t.TempDir(), "ran")
349 if res, _ := run(g, dir, "checks-p-1", time.Minute, `touch `+quote(ran)); res.Reason != "checks_unavailable" || exists(ran) || !exists(filepath.Join(temp, "leftover")) {
350 t.Fatalf("ran beside an unproven attempt: %+v", res)
351 }
352 // Over: its leftovers go before the next gate runs, and the record.
353 g.procs = nil
354 quieted := 0
355 g.QuietSimulators = func(context.Context) { quieted++ }
356 res, _ := run(g, dir, "checks-p-2", time.Minute, `ls `+quote(temp))
357 if res.Code != 0 || strings.Contains(res.Output, "leftover") || exists(filepath.Join(temp, "leftover")) || exists(g.Turns.pending()) || quieted != 2 {
358 t.Fatalf("pending cleanup not finished first (quieted %d): %+v", quieted, res)
359 }
360 // A record that cannot be read, or written: nothing runs.
361 if err := os.WriteFile(g.Turns.pending(), []byte("{"), 0600); err != nil {
362 t.Fatal(err)
363 }
364 if res, _ := run(g, dir, "checks-p-3", time.Minute, `touch `+quote(ran)); res.Reason != "checks_unavailable" || exists(ran) || !g.Turns.Pending() {
365 t.Fatalf("ran past an unreadable record: %+v", res)
366 }
367 if err := os.Remove(g.Turns.pending()); err != nil {
368 t.Fatal(err)
369 }
370 if err := os.Mkdir(g.Turns.pending()+".new", 0700); err != nil {
371 t.Fatal(err)
372 }
373 if res, _ := run(g, dir, "checks-p-4", time.Minute, `touch `+quote(ran)); res.Reason != "checks_unavailable" || exists(ran) {
374 t.Fatalf("ran without its cleanup on record: %+v", res)
375 }
376}
377