| 1 | package mac |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "crypto/sha256" |
| 7 | "embed" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "io/fs" |
| 13 | "net" |
| 14 | "os" |
| 15 | "path" |
| 16 | "path/filepath" |
| 17 | "regexp" |
| 18 | "sort" |
| 19 | "strconv" |
| 20 | "strings" |
| 21 | "sync" |
| 22 | "sync/atomic" |
| 23 | "time" |
| 24 | |
| 25 | "amadan.net/oficina/equipo/internal/wire" |
| 26 | ) |
| 27 | |
| 28 | // The hostile fixture of probe P2 (and the waiting test of P6) ships |
| 29 | // with the runner as test data. |
| 30 | // |
| 31 | //go:embed all:fixtures/hostile |
| 32 | var fixtures embed.FS |
| 33 | |
| 34 | // ProbeHost is what the probes reach on the Mac. Every effect goes |
| 35 | // through it, so the probes run on Linux against recorded outputs. |
| 36 | type ProbeHost struct { |
| 37 | Exec Exec |
| 38 | Tools Tools |
| 39 | Paths Paths |
| 40 | // Scratch holds the fixture copies (never the state dir, which the |
| 41 | // checks profile denies); Runner is the runner's binary (its reader). |
| 42 | Scratch, Runner string |
| 43 | UID int |
| 44 | Version string |
| 45 | // Gate is the gate the fixture runs under: sandboxed, srt with the |
| 46 | // checks profile; or bare. |
| 47 | Gate func(sandboxed bool) *Gate |
| 48 | // Turns is the Mac's turns: the whole run is one turn (OpProbe), and |
| 49 | // its gates run in it. nil takes none (tests). |
| 50 | Turns *Turns |
| 51 | // Resolve and Exposed are the same attempts made outside the |
| 52 | // sandbox, so a denial can be told from a failure; Listen opens a |
| 53 | // loopback port whose accepts are ground truth for "tcp". |
| 54 | Resolve func(ctx context.Context, name string) bool |
| 55 | Exposed func(path string) bool |
| 56 | Listen func() (net.Listener, error) |
| 57 | // Wait bounds P6's wait for its test to start (8 minutes). |
| 58 | Wait time.Duration |
| 59 | // Limit bounds the whole run (ProbeLimit). |
| 60 | Limit time.Duration |
| 61 | // Warn hears why P2's srt run did not fully succeed, once per run, |
| 62 | // redacted (runner.log); nil says nothing. |
| 63 | Warn func(msg string, args ...any) |
| 64 | // late notes the queries that did not answer in time (RunProbes). |
| 65 | late *queries |
| 66 | } |
| 67 | |
| 68 | // QueryLimit bounds each query the probes and the capability report |
| 69 | // make (simctl list, xcodebuild -version, launchctl, pmset, a tool's |
| 70 | // version): a command that has not answered by then is killed and taken |
| 71 | // as unavailable. Only the gates the probes run (a real build and test) |
| 72 | // and srt's own start take longer, each with a bound of its own. |
| 73 | var QueryLimit = 30 * time.Second |
| 74 | |
| 75 | // ProbeLimit bounds a whole probe run, whatever hangs inside it. It is |
| 76 | // above the bounds of the probes' own gates (P2's 20 minutes, P6's 8), |
| 77 | // so it never cuts a slow but healthy first build short: it is the |
| 78 | // backstop for a wait nothing else bounds. |
| 79 | const ProbeLimit = 30 * time.Minute |
| 80 | |
| 81 | // Report is what the probes found, kept in the state dir and sent in the |
| 82 | // capability report. |
| 83 | type Report struct { |
| 84 | Version string `json:"version"` |
| 85 | Profile string `json:"profile"` |
| 86 | At time.Time `json:"at"` |
| 87 | Probes []wire.Probe `json:"probes"` |
| 88 | // SRTRanXcode: the fixture built and tested under srt with the checks |
| 89 | // profile, so srt can confine checks even when P2 is not denied. |
| 90 | SRTRanXcode bool `json:"srt_ran_xcode"` |
| 91 | // SRT fingerprints the srt, Node and ripgrep the probes ran with |
| 92 | // (set by the worker that made the report). |
| 93 | SRT string `json:"srt"` |
| 94 | // Unfinished are the probes the run's limit cut short: each says |
| 95 | // not proven. |
| 96 | Unfinished []string `json:"unfinished,omitempty"` |
| 97 | } |
| 98 | |
| 99 | // Probe is the result of one probe ("" verdict when it did not run). |
| 100 | func (r Report) Probe(id string) wire.Probe { |
| 101 | for _, p := range r.Probes { |
| 102 | if p.ID == id { |
| 103 | return p |
| 104 | } |
| 105 | } |
| 106 | return wire.Probe{ID: id} |
| 107 | } |
| 108 | |
| 109 | // Sandboxed: P2 denied every attempt, so checks run in the sandbox and |
| 110 | // say so (seatbelt). |
| 111 | func (r Report) Sandboxed() bool { return r.Probe("P2").Verdict == wire.ProbeDenied } |
| 112 | |
| 113 | // digestInput is the checks profile over fixed paths that |
| 114 | // ProfileDigest names (TestProfileDigest: ChecksSettings accepts it). |
| 115 | func digestInput() ChecksInput { |
| 116 | return ChecksInput{Paths: Paths{Home: "/Users/u", StateDir: "/Users/u/s", AccountsRoot: "/Users/u/a", SessionRoot: "/Users/u/n", InstallDir: "/Users/u/i", OtherHomes: []string{"/Users/o"}, UserTemp: UserTempPrefix + "/u/T"}, Tree: "/Users/u/t/tree", Attempt: "/Users/u/t/attempt", Mach: CheckMachServices} |
| 117 | } |
| 118 | |
| 119 | // ProfileDigest names the checks profile the probes judged: the |
| 120 | // settings over fixed paths, the Mach list and the fixture. A profile |
| 121 | // that cannot be made is named so, never as no profile. |
| 122 | func ProfileDigest() string { |
| 123 | raw, err := ChecksSettings(digestInput()) |
| 124 | if err != nil { |
| 125 | raw = []byte("unmade: " + err.Error()) |
| 126 | } |
| 127 | h := sha256.New() |
| 128 | h.Write(raw) |
| 129 | _ = fs.WalkDir(fixtures, "fixtures", func(p string, d fs.DirEntry, err error) error { |
| 130 | if err == nil && !d.IsDir() { |
| 131 | b, _ := fixtures.ReadFile(p) |
| 132 | fmt.Fprintf(h, "%s %d\n", p, len(b)) |
| 133 | h.Write(b) |
| 134 | } |
| 135 | return nil |
| 136 | }) |
| 137 | return hex.EncodeToString(h.Sum(nil))[:16] |
| 138 | } |
| 139 | |
| 140 | // RunProbes runs P1 to P7 (spec §6) and reports each. None needs a |
| 141 | // person: P3 and P5 say what they could not do and why. Every command |
| 142 | // is bounded (QueryLimit, or a gate's own limit) and so is the run |
| 143 | // (h.Limit): when that passes the run ends with what it has, the |
| 144 | // probes it did not finish not proven and listed in Unfinished. |
| 145 | func RunProbes(ctx context.Context, h ProbeHost) Report { |
| 146 | limit := h.Limit |
| 147 | if limit <= 0 { |
| 148 | limit = ProbeLimit |
| 149 | } |
| 150 | run, cancel := context.WithTimeout(ctx, limit) |
| 151 | defer cancel() |
| 152 | r := Report{Version: h.Version, Profile: ProfileDigest(), At: time.Now().UTC()} |
| 153 | // One turn for the run's life: no check, Engineering or token |
| 154 | // operation runs between its gates. |
| 155 | run, give, err := h.Turns.Hold(run, OpProbe) |
| 156 | if err != nil { |
| 157 | for _, id := range wire.ProbeIDs { |
| 158 | r.Probes = append(r.Probes, wire.Probe{ID: id, Verdict: wire.ProbeUnavailable, Detail: wire.ProbeDetailTurnBusy}) |
| 159 | r.Unfinished = append(r.Unfinished, id) |
| 160 | } |
| 161 | return r |
| 162 | } |
| 163 | h.late = &queries{run: run, exec: h.Exec, late: map[string]bool{}} |
| 164 | h.Exec = h.late.do |
| 165 | var mu sync.Mutex |
| 166 | got := map[string]wire.Probe{} |
| 167 | srtRan := false |
| 168 | // A result that comes once the run's limit has passed is left out: |
| 169 | // the cancellation, not the Mac, may have decided it. |
| 170 | put := func(p wire.Probe, ran ...bool) { |
| 171 | mu.Lock() |
| 172 | defer mu.Unlock() |
| 173 | if run.Err() == nil { |
| 174 | got[p.ID] = p |
| 175 | if len(ran) > 0 { |
| 176 | srtRan = ran[0] |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | done := make(chan struct{}) |
| 181 | go func() { |
| 182 | defer close(done) |
| 183 | caps := Capabilities(run, h.Exec, h.Tools) |
| 184 | put(probeP1(run, h, caps)) |
| 185 | p2, ran, keychain := probeP2(run, h, caps) |
| 186 | put(p2, ran) |
| 187 | put(wire.Probe{ID: "P3", Verdict: wire.ProbeSkipped, Detail: wire.ProbeDetail(keychain)}) |
| 188 | put(probeP4(run, h)) |
| 189 | put(wire.Probe{ID: "P5", Verdict: wire.ProbeSkipped, Detail: wire.ProbeDetail("p5_parked")}) |
| 190 | put(probeP6(run, h, caps, ran)) |
| 191 | put(probeP7(run, h)) |
| 192 | }() |
| 193 | // Past the limit the report is made with what there is, but the turn |
| 194 | // is held until the run has ended (its context is cancelled, so its |
| 195 | // gates stop and prove their end and clean up): nothing else runs |
| 196 | // beside a probe still stopping. |
| 197 | select { |
| 198 | case <-done: |
| 199 | give() |
| 200 | case <-run.Done(): |
| 201 | go func() { <-done; give() }() |
| 202 | } |
| 203 | mu.Lock() |
| 204 | defer mu.Unlock() |
| 205 | r.SRTRanXcode = srtRan |
| 206 | for _, id := range wire.ProbeIDs { |
| 207 | p, ok := got[id] |
| 208 | if !ok { |
| 209 | p = wire.Probe{ID: id, Verdict: wire.ProbeUnavailable, Detail: wire.ProbeDetail("probe_limit", limit.String())} |
| 210 | r.Unfinished = append(r.Unfinished, id) |
| 211 | } |
| 212 | r.Probes = append(r.Probes, p) |
| 213 | } |
| 214 | return r |
| 215 | } |
| 216 | |
| 217 | // queries runs the probes' commands and notes each that did not answer |
| 218 | // in time: its own deadline passed while the run's had not. |
| 219 | type queries struct { |
| 220 | run context.Context |
| 221 | exec Exec |
| 222 | mu sync.Mutex |
| 223 | late map[string]bool |
| 224 | } |
| 225 | |
| 226 | func (q *queries) do(ctx context.Context, name string, args ...string) (string, error) { |
| 227 | out, err := q.exec(ctx, name, args...) |
| 228 | if errors.Is(ctx.Err(), context.DeadlineExceeded) && q.run.Err() == nil { |
| 229 | q.mu.Lock() |
| 230 | q.late[queryKey(name, args)] = true |
| 231 | q.mu.Unlock() |
| 232 | } |
| 233 | return out, err |
| 234 | } |
| 235 | |
| 236 | // queryKey names a command by its program, or xcrun's by its tool |
| 237 | // ("simctl"). |
| 238 | func queryKey(name string, args []string) string { |
| 239 | if path.Base(name) == "xcrun" && len(args) > 0 { |
| 240 | return args[0] |
| 241 | } |
| 242 | return path.Base(name) |
| 243 | } |
| 244 | |
| 245 | // noXcode and noSimulator are the detail of a probe that needs Xcode or |
| 246 | // a simulator and cannot run: a query that did not answer in time |
| 247 | // (QueryLimit), or none found ("" for a simulator that answered). |
| 248 | func (h ProbeHost) noXcode() string { |
| 249 | return h.gone("xcodebuild", "xcode_unavailable", wire.ProbeDetail("no_xcode")) |
| 250 | } |
| 251 | func (h ProbeHost) noSimulator() string { return h.gone("simctl", "simulator_unavailable", "") } |
| 252 | |
| 253 | func (h ProbeHost) gone(tool, code, otherwise string) string { |
| 254 | if h.late != nil && h.late.was(tool) { |
| 255 | return wire.ProbeDetail(code, QueryLimit.String()) |
| 256 | } |
| 257 | return otherwise |
| 258 | } |
| 259 | |
| 260 | func (q *queries) was(tool string) bool { q.mu.Lock(); defer q.mu.Unlock(); return q.late[tool] } |
| 261 | |
| 262 | // query runs one probe command bounded by limit. |
| 263 | func (h ProbeHost) query(ctx context.Context, limit time.Duration, name string, args ...string) (string, error) { |
| 264 | c, cancel := context.WithTimeout(ctx, limit) |
| 265 | defer cancel() |
| 266 | return h.Exec(c, name, args...) |
| 267 | } |
| 268 | |
| 269 | func probeP1(ctx context.Context, h ProbeHost, caps wire.Capabilities) wire.Probe { |
| 270 | name := ComputerName(ctx, h.Exec) |
| 271 | ios := 0 |
| 272 | for _, s := range caps.Simulators { |
| 273 | if strings.HasPrefix(s.Runtime, "iOS ") { |
| 274 | ios++ |
| 275 | } |
| 276 | } |
| 277 | computer := map[bool]string{true: wire.ProbeDetail("computer", name)}[name != ""] |
| 278 | if caps.Xcode.Version == "" { |
| 279 | return wire.Probe{ID: "P1", Verdict: wire.ProbeFailed, Detail: wire.ProbeDetails(h.noXcode(), computer)} |
| 280 | } |
| 281 | sims := firstNonEmpty(h.noSimulator(), wire.ProbeDetail("ios_simulators", strconv.Itoa(ios))) |
| 282 | detail := wire.ProbeDetails(wire.ProbeDetail("xcode", caps.Xcode.Version, caps.Xcode.Build), sims, computer) |
| 283 | if ios == 0 { |
| 284 | return wire.Probe{ID: "P1", Verdict: wire.ProbeFailed, Detail: detail} |
| 285 | } |
| 286 | return wire.Probe{ID: "P1", Verdict: wire.ProbePassed, Detail: detail} |
| 287 | } |
| 288 | |
| 289 | // ComputerName is the Mac's name as people see it ("Tito Studio"). |
| 290 | func ComputerName(ctx context.Context, x Exec) string { |
| 291 | ctx, cancel := context.WithTimeout(ctx, QueryLimit) |
| 292 | defer cancel() |
| 293 | out, err := x(ctx, "/usr/sbin/scutil", "--get", "ComputerName") |
| 294 | if err != nil { |
| 295 | return "" |
| 296 | } |
| 297 | return strings.TrimSpace(out) |
| 298 | } |
| 299 | |
| 300 | // The places and attempts of the hostile fixture. |
| 301 | var ( |
| 302 | probePlaces = []string{"script", "plugin", "test"} |
| 303 | probeAttempts = []string{"state", "home", "tcp", "dns", "keychain", "tokenfile", "tokenlink", "tokenenv", "tokenargs", "tokenlaunchd", "tokenfd"} |
| 304 | attemptLine = regexp.MustCompile(`EQUIPO-PROBE (script|plugin|test) (state|home|tcp|dns|keychain|token(?:file|link|env|args|launchd|fd)) (allowed|denied|failed)\b`) |
| 305 | ) |
| 306 | |
| 307 | // ParseAttempts reads the fixture's report lines: "place.attempt" to |
| 308 | // allowed or denied. The first line for an attempt counts. |
| 309 | func ParseAttempts(out string) map[string]string { |
| 310 | got := map[string]string{} |
| 311 | for _, m := range attemptLine.FindAllStringSubmatch(out, -1) { |
| 312 | k := m[1] + "." + m[2] |
| 313 | if _, seen := got[k]; !seen { |
| 314 | got[k] = m[3] |
| 315 | } |
| 316 | } |
| 317 | return got |
| 318 | } |
| 319 | |
| 320 | // P2Facts are what the probe knows outside the sandbox. |
| 321 | type P2Facts struct { |
| 322 | // Home: another home was tried; HomeUnix: the runner user cannot |
| 323 | // list it even outside the sandbox (Unix permissions deny it). |
| 324 | Home, HomeUnix bool |
| 325 | // DNS resolves outside; the Keychain item and the sentinel token exist. |
| 326 | DNS, Keychain, Token bool |
| 327 | // Accepted: places whose loopback port took a connection. |
| 328 | Accepted map[string]bool |
| 329 | } |
| 330 | |
| 331 | // JudgeP2 turns the attempts into P2's verdict: denied only when every |
| 332 | // attempt of every place says denied and nothing contradicts it. A |
| 333 | // missing line, a failed control (DNS outside, the Keychain item, the |
| 334 | // token planted) or an accepted connection is not a denial. |
| 335 | func JudgeP2(got map[string]string, f P2Facts) (verdict string, groups map[string][]string) { |
| 336 | groups = map[string][]string{} |
| 337 | verdict = wire.ProbeDenied |
| 338 | for _, place := range probePlaces { |
| 339 | for _, what := range probeAttempts { |
| 340 | if what == "home" && !f.Home { |
| 341 | continue |
| 342 | } |
| 343 | k := place + "." + what |
| 344 | r := got[k] |
| 345 | switch { |
| 346 | case what == "tcp" && f.Accepted[place]: |
| 347 | r = "allowed" |
| 348 | case r == "": |
| 349 | r = "unknown" |
| 350 | case r == "denied" && what == "dns" && !f.DNS, r == "denied" && what == "keychain" && !f.Keychain, r == "denied" && strings.HasPrefix(what, "token") && !f.Token: |
| 351 | r = "unknown" |
| 352 | case r == "denied" && what == "home" && f.HomeUnix: |
| 353 | r = "unix" |
| 354 | } |
| 355 | if r != "denied" { |
| 356 | groups[r] = append(groups[r], k) |
| 357 | } |
| 358 | if r != "denied" && r != "unix" { |
| 359 | verdict = wire.ProbeFailed |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 | return verdict, groups |
| 364 | } |
| 365 | |
| 366 | // p2Detail says what P2 found (a place all of whose attempts are alike as |
| 367 | // place.*) and whether the run's end was proven; why, the steps of a |
| 368 | // failed srt run, is last, so the capability string's limit cuts it |
| 369 | // first. |
| 370 | func p2Detail(groups map[string][]string, total int, srtRan, ended bool, why string) string { |
| 371 | var parts []string |
| 372 | for _, g := range []struct{ key, code string }{{"allowed", "allowed"}, {"failed", "not_collected"}, {"unknown", "not_shown_denied"}, {"unix", "unix_only"}} { |
| 373 | if len(groups[g.key]) > 0 { |
| 374 | list := " " + strings.Join(groups[g.key], " ") + " " |
| 375 | for _, p := range probePlaces { |
| 376 | list = strings.Replace(list, " "+p+"."+strings.Join(probeAttempts, " "+p+".")+" ", " "+p+".* ", 1) |
| 377 | } |
| 378 | parts = append(parts, wire.ProbeDetail(g.code, strings.TrimSpace(list))) |
| 379 | } |
| 380 | } |
| 381 | if len(parts) == 0 { |
| 382 | parts = append(parts, wire.ProbeDetail("all_denied", strconv.Itoa(total))) |
| 383 | } |
| 384 | if !ended { |
| 385 | parts = append(parts, wire.ProbeDetail("end_unproven")) |
| 386 | } |
| 387 | switch { |
| 388 | case srtRan: |
| 389 | parts = append(parts, wire.ProbeDetail("srt_ran_xcode")) |
| 390 | case why != "": |
| 391 | parts = append(parts, wire.ProbeDetail("srt_failed", why)) |
| 392 | default: |
| 393 | parts = append(parts, wire.ProbeDetail("srt_not_run")) |
| 394 | } |
| 395 | return wire.ProbeDetails(parts...) |
| 396 | } |
| 397 | |
| 398 | // P2Script is P2's run under srt, one step at a time, each reporting |
| 399 | // its exit (EQUIPO-PHASE <step> <exit>) so a failure names its step: the |
| 400 | // hostile script phase's build, then the package's resolve, test build, |
| 401 | // the simulator's boot and the hostile test on it. Every xcodebuild |
| 402 | // writes only into the attempt's scratch (XcodeWrites), as checks do; |
| 403 | // the script phase's target is built through its shared scheme because |
| 404 | // xcodebuild takes -derivedDataPath only for a scheme, and SYMROOT and |
| 405 | // OBJROOT stay in scratch too should a build fall back to them. Each |
| 406 | // action has its own result bundle there (XcodeResult). |
| 407 | func P2Script(xb, xcrun, udid string) string { |
| 408 | dest := quote("platform=iOS Simulator,id=" + udid) |
| 409 | pkg := func(step string) string { |
| 410 | return ` -scheme "$s" ` + XcodeWrites + ` ` + XcodeResult(step) + ` -skipPackagePluginValidation` |
| 411 | } |
| 412 | return `phase() { p=$1; shift; "$@"; c=$?; echo "EQUIPO-PHASE $p $c"; return $c; } |
| 413 | (cd project && phase script-build ` + xb + ` -project Hostile.xcodeproj -scheme HostileScript -configuration Debug build ` + XcodeWrites + ` ` + XcodeResult("script-build") + ` SYMROOT="$TMPDIR/sym" OBJROOT="$TMPDIR/obj"); a=$? |
| 414 | cd package || exit 1 |
| 415 | s=Hostile-Package; ` + xb + ` -list ` + XcodeWrites + ` 2>/dev/null | grep -q Hostile-Package || s=Hostile |
| 416 | phase package-resolve ` + xb + ` -resolvePackageDependencies` + pkg("package-resolve") + ` && |
| 417 | phase test-build ` + xb + ` build-for-testing -destination ` + dest + pkg("test-build") + ` && |
| 418 | phase simulator-boot ` + xcrun + ` simctl bootstatus ` + quote(udid) + ` -b && |
| 419 | phase test-run ` + xb + ` test-without-building -destination ` + dest + ` -only-testing:HostileTests/HostileTests/testHostile` + pkg("test-run") + ` |
| 420 | b=$? |
| 421 | [ "$a" = 0 ] && [ "$b" = 0 ]` |
| 422 | } |
| 423 | |
| 424 | // probeP2 runs the hostile fixture under the checks profile. |
| 425 | func probeP2(ctx context.Context, h ProbeHost, caps wire.Capabilities) (wire.Probe, bool, string) { |
| 426 | fail := func(verdict, why string) (wire.Probe, bool, string) { |
| 427 | return wire.Probe{ID: "P2", Verdict: verdict, Detail: why}, false, "p3_keychain_unprobed" |
| 428 | } |
| 429 | if h.Tools.SRT == "" { |
| 430 | return fail(wire.ProbeUnavailable, wire.ProbeDetail("srt_missing")) |
| 431 | } |
| 432 | // No checks profile without the user's T (ChecksSettings refuses): |
| 433 | // say why, and checks wait for the sandbox. |
| 434 | if h.Paths.UserTemp == "" { |
| 435 | return fail(wire.ProbeUnavailable, wire.ProbeDetail("user_temp_refused")) |
| 436 | } |
| 437 | if caps.Xcode.Version == "" { |
| 438 | return fail(wire.ProbeUnavailable, h.noXcode()) |
| 439 | } |
| 440 | if why := h.noSimulator(); why != "" { |
| 441 | return fail(wire.ProbeUnavailable, why) |
| 442 | } |
| 443 | // The hostile test runs where production checks run: on an iOS |
| 444 | // simulator, through CoreSimulator and the test services. |
| 445 | sim, ok := NewestIPhone(caps.Simulators) |
| 446 | if !ok { |
| 447 | return fail(wire.ProbeUnavailable, wire.ProbeDetail("no_simulator")) |
| 448 | } |
| 449 | root, err := CopyFixture(h.Scratch) |
| 450 | if err != nil { |
| 451 | return fail(wire.ProbeUnavailable, wire.ProbeDetail("fixture_uncopied")) |
| 452 | } |
| 453 | defer os.RemoveAll(filepath.Dir(root)) |
| 454 | facts := P2Facts{Accepted: map[string]bool{}} |
| 455 | targets := []string{} |
| 456 | // A sentinel in the state dir: what a step must never read. |
| 457 | secret := token() |
| 458 | sentinel := filepath.Join(h.Paths.StateDir, "probe-sentinel-"+secret[:8]) |
| 459 | if err := os.WriteFile(sentinel, []byte(secret), 0600); err != nil { |
| 460 | return fail(wire.ProbeUnavailable, "no sentinel in the state dir") |
| 461 | } |
| 462 | defer os.Remove(sentinel) |
| 463 | // A sentinel token where connections keep theirs (F3's sources, slice F). |
| 464 | tok := filepath.Join(h.Paths.AccountsRoot, "probe-"+secret[:8]) |
| 465 | if filepath.IsAbs(tok) { |
| 466 | defer os.RemoveAll(tok) |
| 467 | facts.Token = os.MkdirAll(tok, 0700) == nil && os.WriteFile(filepath.Join(tok, ".oauth-token"), []byte("sk-ant-oat01-probe-"+secret), 0600) == nil |
| 468 | } |
| 469 | targets = append(targets, "state="+sentinel, "token=sk-ant-oat01-probe-"+secret, "token_file="+filepath.Join(tok, ".oauth-token"), "helper="+h.Runner) |
| 470 | if home := otherHome(h.Paths.OtherHomes); home != "" { |
| 471 | facts.Home, facts.HomeUnix = true, !h.Exposed(home) |
| 472 | targets = append(targets, "home="+home) |
| 473 | } |
| 474 | var mu sync.Mutex |
| 475 | for _, place := range probePlaces { |
| 476 | l, err := h.Listen() |
| 477 | if err != nil { |
| 478 | return fail(wire.ProbeUnavailable, "no loopback port") |
| 479 | } |
| 480 | defer l.Close() |
| 481 | go func(place string, l net.Listener) { |
| 482 | for { |
| 483 | c, err := l.Accept() |
| 484 | if err != nil { |
| 485 | return |
| 486 | } |
| 487 | c.Close() |
| 488 | mu.Lock() |
| 489 | facts.Accepted[place] = true |
| 490 | mu.Unlock() |
| 491 | } |
| 492 | }(place, l) |
| 493 | targets = append(targets, "port_"+place+"="+strconv.Itoa(l.Addr().(*net.TCPAddr).Port)) |
| 494 | } |
| 495 | resolve, cancel := context.WithTimeout(ctx, QueryLimit) |
| 496 | facts.DNS = h.Resolve(resolve, "example.com") |
| 497 | cancel() |
| 498 | targets = append(targets, "dns=example.com") |
| 499 | service := "io.amadan.equipo.probe." + secret[:12] |
| 500 | if _, err := h.query(ctx, QueryLimit, "/usr/bin/security", "add-generic-password", "-a", "equipo-probe", "-s", service, "-w", secret, "-A", "-U"); err == nil { |
| 501 | facts.Keychain = true |
| 502 | defer func() { |
| 503 | _, _ = h.query(context.WithoutCancel(ctx), QueryLimit, "/usr/bin/security", "delete-generic-password", "-a", "equipo-probe", "-s", service) |
| 504 | }() |
| 505 | } |
| 506 | // On a simulator the Keychain API is the simulator's own: the test |
| 507 | // there tries the runner user's login keychain file instead. |
| 508 | targets = append(targets, "keychain="+service, "keychain_file="+filepath.Join(h.Paths.Home, "Library", "Keychains", "login.keychain-db")) |
| 509 | if err := os.WriteFile(filepath.Join(root, "equipo-targets.txt"), []byte(strings.Join(targets, "\n")+"\n"), 0600); err != nil { |
| 510 | return fail(wire.ProbeUnavailable, wire.ProbeDetail("fixture_unprepared")) |
| 511 | } |
| 512 | script := P2Script(quote(h.Tools.Xcodebuild), quote(h.Tools.Xcrun), sim.UDID) |
| 513 | g, watch := h.Gate(true), newP2Watch() |
| 514 | g.Watch = watch.line |
| 515 | res := g.Run(ctx, "probe-p2-"+secret[:8], root, []string{"/bin/bash", "-c", script}, 20*time.Minute, func(string) error { return nil }) |
| 516 | mu.Lock() |
| 517 | defer mu.Unlock() |
| 518 | srtRan := watch.ran(res) |
| 519 | verdict, groups := JudgeP2(ParseAttempts(watch.attemptsSeen()), facts) |
| 520 | why := "" |
| 521 | if !srtRan { |
| 522 | // Never the secret, the service, the targets file's contents or a |
| 523 | // path under a home. |
| 524 | secrets := []string{service, secret, secret[:12], secret[:8]} |
| 525 | for _, t := range targets { |
| 526 | _, v, _ := strings.Cut(t, "=") |
| 527 | secrets = append(secrets, t, v) |
| 528 | } |
| 529 | red := newRedactor(secrets, append([]string{h.Paths.Home, h.Paths.StateDir, h.Scratch}, h.Paths.OtherHomes...)) |
| 530 | f := watch.failure(res, red) |
| 531 | why, _, _ = strings.Cut(f.short(), ": ") |
| 532 | if h.Warn != nil { |
| 533 | h.Warn("p2 srt run failed", "phase", f.Phase, "failed", strings.Join(f.Failed, ", "), "unfinished", f.Unfinished, "exit", f.Exit, "timed_out", f.TimedOut, "gate_reason", res.Reason, "excerpt", f.Excerpt) |
| 534 | } |
| 535 | } |
| 536 | // Denied counts only for a run that did everything and was proven |
| 537 | // to end: the hostile build and test completed under srt, and nothing |
| 538 | // of them is left. |
| 539 | if !srtRan || !res.Terminated { |
| 540 | verdict = wire.ProbeFailed |
| 541 | } |
| 542 | keychain := "p3_keychain_denied" |
| 543 | for _, list := range groups { |
| 544 | if strings.Contains(" "+strings.Join(list, " ")+" ", ".keychain ") { |
| 545 | keychain = "p3_keychain_unshown" |
| 546 | } |
| 547 | } |
| 548 | total := len(probePlaces) * len(probeAttempts) |
| 549 | if !facts.Home { |
| 550 | total -= len(probePlaces) |
| 551 | } |
| 552 | detail := p2Detail(groups, total, srtRan, res.Terminated, why) |
| 553 | return wire.Probe{ID: "P2", Verdict: verdict, Detail: detail}, srtRan, keychain |
| 554 | } |
| 555 | |
| 556 | // otherHome is the home P2 tries: a person's, not /Users/Shared. |
| 557 | func otherHome(homes []string) string { |
| 558 | list := append([]string{}, homes...) |
| 559 | sort.Strings(list) |
| 560 | for _, h := range list { |
| 561 | if path.Base(h) != "Shared" { |
| 562 | return h |
| 563 | } |
| 564 | } |
| 565 | return "" |
| 566 | } |
| 567 | |
| 568 | func probeP4(ctx context.Context, h ProbeHost) wire.Probe { |
| 569 | var readable []string |
| 570 | for _, home := range ExposedHomes(h.Paths.OtherHomes, h.Exposed) { |
| 571 | readable = append(readable, path.Base(home)) |
| 572 | } |
| 573 | _, err := h.query(ctx, QueryLimit, "/bin/launchctl", "print", "gui/"+strconv.Itoa(h.UID)+"/"+AgentLabel) |
| 574 | loaded := err == nil |
| 575 | pm, _ := h.query(ctx, QueryLimit, "/usr/bin/pmset", "-g", "custom") |
| 576 | sleep, known := ACSleep(pm) |
| 577 | var parts []string |
| 578 | switch { |
| 579 | case h.Paths.HomesUnknown: |
| 580 | parts = append(parts, wire.ProbeDetail("homes_unchecked")) |
| 581 | case len(readable) > 0: |
| 582 | parts = append(parts, wire.ProbeDetail("homes_readable", strings.Join(readable, " "))) |
| 583 | default: |
| 584 | parts = append(parts, wire.ProbeDetail("homes_closed")) |
| 585 | } |
| 586 | parts = append(parts, wire.ProbeDetail(map[bool]string{true: "agent_loaded", false: "agent_not_loaded"}[loaded])) |
| 587 | switch { |
| 588 | case !known: |
| 589 | parts = append(parts, wire.ProbeDetail("sleep_unknown")) |
| 590 | case sleep == 0: |
| 591 | parts = append(parts, wire.ProbeDetail("sleep_off")) |
| 592 | default: |
| 593 | parts = append(parts, wire.ProbeDetail("sleep_after", strconv.Itoa(sleep))) |
| 594 | } |
| 595 | verdict := wire.ProbePassed |
| 596 | if h.Paths.HomesUnknown || len(readable) > 0 || !loaded || !known || sleep != 0 { |
| 597 | verdict = wire.ProbeFailed |
| 598 | } |
| 599 | return wire.Probe{ID: "P4", Verdict: verdict, Detail: wire.ProbeDetails(parts...)} |
| 600 | } |
| 601 | |
| 602 | // ACSleep reads `pmset -g custom`: the system sleep minutes under "AC |
| 603 | // Power" (0 is never). A desktop Mac may list one unnamed set of |
| 604 | // settings; its sleep line counts when there is no section at all. |
| 605 | func ACSleep(out string) (int, bool) { |
| 606 | ac := true |
| 607 | for _, line := range strings.Split(out, "\n") { |
| 608 | t := strings.TrimSpace(line) |
| 609 | if strings.HasSuffix(t, ":") { |
| 610 | ac = strings.HasPrefix(t, "AC Power") |
| 611 | continue |
| 612 | } |
| 613 | f := strings.Fields(t) |
| 614 | if ac && len(f) >= 2 && f[0] == "sleep" { |
| 615 | n, err := strconv.Atoi(f[1]) |
| 616 | return n, err == nil |
| 617 | } |
| 618 | } |
| 619 | return 0, false |
| 620 | } |
| 621 | |
| 622 | // probeP6 starts the fixture's waiting test and kills its group: how long |
| 623 | // the end takes to prove, what is left, and whether the tree goes. |
| 624 | func probeP6(ctx context.Context, h ProbeHost, caps wire.Capabilities, srtRan bool) wire.Probe { |
| 625 | if caps.Xcode.Version == "" { |
| 626 | return wire.Probe{ID: "P6", Verdict: wire.ProbeUnavailable, Detail: h.noXcode()} |
| 627 | } |
| 628 | // A simctl that does not answer means CoreSimulator is stuck, and |
| 629 | // xcodebuild test asks it for destinations even for macOS: the probe |
| 630 | // would only wait out its whole limit. |
| 631 | if why := h.noSimulator(); why != "" { |
| 632 | return wire.Probe{ID: "P6", Verdict: wire.ProbeUnavailable, Detail: why} |
| 633 | } |
| 634 | root, err := CopyFixture(h.Scratch) |
| 635 | if err != nil { |
| 636 | return wire.Probe{ID: "P6", Verdict: wire.ProbeUnavailable, Detail: wire.ProbeDetail("fixture_uncopied")} |
| 637 | } |
| 638 | defer os.RemoveAll(filepath.Dir(root)) |
| 639 | destination := "platform=macOS" |
| 640 | if sim, ok := NewestIPhone(caps.Simulators); ok { |
| 641 | destination = "platform=iOS Simulator,id=" + sim.UDID |
| 642 | } |
| 643 | g := *h.Gate(srtRan && h.Tools.SRT != "") |
| 644 | run, cancel := context.WithCancel(ctx) |
| 645 | defer cancel() |
| 646 | var once sync.Once |
| 647 | var mu sync.Mutex |
| 648 | var stopped time.Time |
| 649 | g.Watch = func(line string) { |
| 650 | if strings.Contains(line, "EQUIPO-PROBE wait started") { |
| 651 | once.Do(func() { |
| 652 | time.AfterFunc(2*time.Second, func() { |
| 653 | mu.Lock() |
| 654 | stopped = time.Now() |
| 655 | mu.Unlock() |
| 656 | cancel() |
| 657 | }) |
| 658 | }) |
| 659 | } |
| 660 | } |
| 661 | var shut atomic.Int32 |
| 662 | if inner := g.Shutdown; inner != nil { |
| 663 | g.Shutdown = func(c context.Context, u string) { shut.Add(1); inner(c, u) } |
| 664 | } |
| 665 | before := processNames(ctx, h.Exec) |
| 666 | attempt := "probe-p6-" + token()[:8] |
| 667 | wait := h.Wait |
| 668 | if wait <= 0 { |
| 669 | wait = 8 * time.Minute |
| 670 | } |
| 671 | script := p6Script(quote(h.Tools.Xcodebuild), destination) |
| 672 | res := g.Run(run, attempt, root, []string{"/bin/bash", "-c", script}, wait, func(string) error { return nil }) |
| 673 | mu.Lock() |
| 674 | defer mu.Unlock() |
| 675 | took := time.Since(stopped).Round(time.Second) |
| 676 | left, _ := Marked(attempt) |
| 677 | after := processNames(context.WithoutCancel(ctx), h.Exec) |
| 678 | removed := os.RemoveAll(root) == nil |
| 679 | if stopped.IsZero() { |
| 680 | return wire.Probe{ID: "P6", Verdict: wire.ProbeFailed, Detail: wire.ProbeDetail("test_not_started", firstNonEmpty(res.Reason, "exit "+strconv.Itoa(res.Code)))} |
| 681 | } |
| 682 | var parts []string |
| 683 | if res.Terminated { |
| 684 | parts = append(parts, wire.ProbeDetail("group_gone", took.String())) |
| 685 | } else { |
| 686 | parts = append(parts, wire.ProbeDetail("group_unproven")) |
| 687 | } |
| 688 | parts = append(parts, wire.ProbeDetail("marked_left", strconv.Itoa(len(left)))) |
| 689 | if n := newNames(before, after); n > 0 { |
| 690 | // How many, never their names (a path, or what a process chose). |
| 691 | parts = append(parts, wire.ProbeDetail("still_running", strconv.Itoa(n))) |
| 692 | } |
| 693 | parts = append(parts, wire.ProbeDetail("simulators_shut", strconv.Itoa(int(shut.Load())))) |
| 694 | parts = append(parts, wire.ProbeDetail(map[bool]string{true: "tree_removed", false: "tree_not_removable"}[removed])) |
| 695 | verdict := wire.ProbePassed |
| 696 | if !res.Terminated || len(left) > 0 || !removed { |
| 697 | verdict = wire.ProbeFailed |
| 698 | } |
| 699 | return wire.Probe{ID: "P6", Verdict: verdict, Detail: wire.ProbeDetails(parts...)} |
| 700 | } |
| 701 | |
| 702 | // p6Script starts the fixture's waiting test, its writes in the |
| 703 | // attempt's scratch as P2's and the checks' are. |
| 704 | func p6Script(xb, destination string) string { |
| 705 | return `cd package && s=Hostile-Package; ` + xb + ` -list ` + XcodeWrites + ` 2>/dev/null | grep -q Hostile-Package || s=Hostile |
| 706 | exec ` + xb + ` test -scheme "$s" -destination ` + quote(destination) + ` -only-testing:HostileTests/HostileTests/testWait ` + XcodeWrites + ` ` + XcodeResult("wait") + ` -skipPackagePluginValidation` |
| 707 | } |
| 708 | |
| 709 | // processNames are this user's processes by name (basename), counted. |
| 710 | func processNames(ctx context.Context, x Exec) map[string]int { |
| 711 | ctx, cancel := context.WithTimeout(ctx, QueryLimit) |
| 712 | defer cancel() |
| 713 | out, err := x(ctx, "/bin/ps", "-x", "-o", "comm=") |
| 714 | names := map[string]int{} |
| 715 | if err != nil { |
| 716 | return names |
| 717 | } |
| 718 | for _, l := range strings.Split(out, "\n") { |
| 719 | if l = strings.TrimSpace(l); l != "" { |
| 720 | names[path.Base(l)]++ |
| 721 | } |
| 722 | } |
| 723 | return names |
| 724 | } |
| 725 | |
| 726 | // newNames is how many process names are new or more numerous after. |
| 727 | func newNames(before, after map[string]int) (n int) { |
| 728 | for name, c := range after { |
| 729 | if c > before[name] { |
| 730 | n++ |
| 731 | } |
| 732 | } |
| 733 | return n |
| 734 | } |
| 735 | |
| 736 | func probeP7(ctx context.Context, h ProbeHost) wire.Probe { |
| 737 | ask := func(tool string, args ...string) string { |
| 738 | if tool == "" { |
| 739 | return "" |
| 740 | } |
| 741 | out, err := h.query(ctx, QueryLimit, tool, args...) |
| 742 | if err != nil { |
| 743 | return "" |
| 744 | } |
| 745 | return out |
| 746 | } |
| 747 | srt := word(plainVersion, ask(h.Tools.SRT, "--version")) |
| 748 | node := word(nodeVersion, ask(h.Tools.Node, "--version")) |
| 749 | rg := word(plainVersion, ask(h.Tools.RG, "--version")) |
| 750 | var parts []string |
| 751 | ok := true |
| 752 | for _, t := range []struct{ name, version string }{{"srt", srt}, {"node", node}, {"rg", rg}} { |
| 753 | if t.version == "" { |
| 754 | parts, ok = append(parts, wire.ProbeDetail("tool_missing", t.name)), false |
| 755 | } else { |
| 756 | parts = append(parts, wire.ProbeDetail("tool_version", t.name, t.version)) |
| 757 | } |
| 758 | } |
| 759 | if node != "" && !NodeSupported(node) { |
| 760 | parts, ok = append(parts, wire.ProbeDetail("node_old")), false |
| 761 | } |
| 762 | if ok { |
| 763 | // srt itself: the smallest profile around /usr/bin/true. |
| 764 | file := filepath.Join(h.Scratch, "probe-p7-"+token()[:8]+".json") |
| 765 | raw, _ := json.Marshal(Settings{Network: Network{AllowedDomains: []string{}, DeniedDomains: []string{}, AllowMachLookup: []string{}}, Filesystem: Filesystem{DenyRead: []string{}, AllowRead: []string{}, AllowWrite: []string{}, DenyWrite: []string{}}}) |
| 766 | if os.WriteFile(file, raw, 0600) != nil { |
| 767 | ok = false |
| 768 | } else { |
| 769 | defer os.Remove(file) |
| 770 | // srt starts its own runtime before the command: a minute, not a query's 30 s. |
| 771 | if _, err := h.query(ctx, time.Minute, h.Tools.SRT, "--settings", file, "--", "/usr/bin/true"); err != nil { |
| 772 | parts, ok = append(parts, wire.ProbeDetail("srt_cannot_run")), false |
| 773 | } |
| 774 | } |
| 775 | } |
| 776 | verdict := wire.ProbePassed |
| 777 | if !ok { |
| 778 | verdict = wire.ProbeFailed |
| 779 | } |
| 780 | return wire.Probe{ID: "P7", Verdict: verdict, Detail: wire.ProbeDetails(parts...)} |
| 781 | } |
| 782 | |
| 783 | // NodeSupported: srt needs Node 22.12 or later. |
| 784 | func NodeSupported(v string) bool { |
| 785 | var n [3]int |
| 786 | if _, err := fmt.Sscanf(v, "v%d.%d.%d", &n[0], &n[1], &n[2]); err != nil { |
| 787 | return false |
| 788 | } |
| 789 | return compareVersions(n[:], []int{22, 12, 0}) >= 0 |
| 790 | } |
| 791 | |
| 792 | // CopyFixture writes the hostile fixture into a fresh directory under |
| 793 | // scratch and returns its root. |
| 794 | func CopyFixture(scratch string) (string, error) { |
| 795 | if err := os.MkdirAll(scratch, 0700); err != nil { |
| 796 | return "", err |
| 797 | } |
| 798 | dir, err := os.MkdirTemp(scratch, "probe-") |
| 799 | if err != nil { |
| 800 | return "", err |
| 801 | } |
| 802 | root := filepath.Join(dir, "hostile") |
| 803 | err = fs.WalkDir(fixtures, "fixtures/hostile", func(p string, d fs.DirEntry, err error) error { |
| 804 | if err != nil { |
| 805 | return err |
| 806 | } |
| 807 | dst := filepath.Join(root, strings.TrimPrefix(p, "fixtures/hostile")) |
| 808 | if d.IsDir() { |
| 809 | return os.MkdirAll(dst, 0700) |
| 810 | } |
| 811 | raw, err := fixtures.ReadFile(p) |
| 812 | if err != nil { |
| 813 | return err |
| 814 | } |
| 815 | mode := os.FileMode(0600) |
| 816 | if strings.HasSuffix(p, ".sh") { |
| 817 | mode = 0700 |
| 818 | } |
| 819 | return os.WriteFile(dst, raw, mode) |
| 820 | }) |
| 821 | if err != nil { |
| 822 | os.RemoveAll(dir) |
| 823 | return "", err |
| 824 | } |
| 825 | return root, nil |
| 826 | } |
| 827 | |
| 828 | func token() string { |
| 829 | b := make([]byte, 16) |
| 830 | _, _ = rand.Read(b) |
| 831 | return hex.EncodeToString(b) |
| 832 | } |
| 833 | |
| 834 | func firstNonEmpty(s ...string) string { |
| 835 | for _, x := range s { |
| 836 | if x != "" { |
| 837 | return x |
| 838 | } |
| 839 | } |
| 840 | return "" |
| 841 | } |
| 842 | |