package headless import ( "bytes" "context" "os" "os/exec" "path/filepath" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/testci" ) // The sign-in's `claude setup-token` (the fake) in the real namespace, // as the runner starts it (provider.BuildSignInPolicy, StartTerminal): // on a terminal; another account's home and the runner's state are not // there to read; it writes only to its home and /tmp, both its own // memory (nothing reaches the host), not to the workspace, /etc or // /usr; a CONNECT to a host off its list // is refused by the egress proxy and counted. A child the CLI starts // that ignores a hangup dies with the namespace when the CLI exits, and // the namespace's scratch, where a code typed in could have been // written, is gone once its exit is proven. func TestHeadlessSignInContained(t *testing.T) { testci.Tools(t, "bwrap") if _, err := exec.LookPath("/usr/bin/bwrap"); err != nil { t.Skip("bubblewrap is required") } root := private(t, filepath.Join(t.TempDir(), "root")) bin := private(t, filepath.Join(root, "bin")) copyExecutable(t, filepath.Join(bin, "claude")) other := private(t, filepath.Join(root, "accounts", "claude-1")) state := private(t, filepath.Join(root, "state")) canaries := []string{filepath.Join(other, ".credentials.json"), filepath.Join(other, ".oauth-token"), filepath.Join(state, "thin.db"), filepath.Join(bin, "claude")} for _, f := range canaries[:3] { if err := os.WriteFile(f, []byte("CANARY-NOT-FOR-THE-SIGN-IN"), 0600); err != nil { t.Fatal(err) } } scratch := private(t, filepath.Join(root, "scratch")) self, _ := os.Executable() m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: self, ScratchRoot: scratch, ProviderNetworks: []provider.NetworkContract{{Provider: "claude"}}}) if err != nil { t.Fatal(err) } policy, err := provider.BuildSignInPolicy(provider.SignInPolicyInputs{Binary: filepath.Join(bin, "claude"), Bwrap: "/usr/bin/bwrap"}) if err != nil { t.Fatal(err) } var mu sync.Mutex var record containment.Record ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() proc, err := m.StartTerminal(ctx, provider.Launch{AttemptKey: "signin/contained", Selection: provider.Selection{Provider: "claude"}, Policy: policy}, provider.SignInArgv, func(_ context.Context, r containment.Record) error { mu.Lock() record = r mu.Unlock() return nil }) if err != nil { t.Fatal(err) } var out bytes.Buffer read := make(chan struct{}) go func() { defer close(read) buf := make([]byte, 4096) for { n, err := proc.Stdout().Read(buf) mu.Lock() out.Write(buf[:n]) mu.Unlock() if err != nil { return } } }() seen := func(what string) string { t.Helper() deadline := time.Now().Add(time.Minute) for time.Now().Before(deadline) { mu.Lock() s := out.String() mu.Unlock() if strings.Contains(s, what) { return s } time.Sleep(50 * time.Millisecond) } t.Fatalf("no %q in %q", what, out.String()) return "" } seen("Paste code here if prompted >") if _, err = proc.Stdin().Write([]byte("probe:" + strings.Join(canaries, ",") + "\r")); err != nil { t.Fatal(err) } screen := seen("probe done") for _, f := range canaries { if !strings.Contains(screen, "probe read "+f+" absent") { t.Errorf("%s is there to read in the namespace", f) } } // /opt is in bubblewrap's own root, in memory, as for every launch: // a write there reaches no host disk and ends with the namespace. for path, word := range map[string]string{"/home/runner/w": "ok", "/tmp/w": "ok", "/workspace/w": "denied", "/etc/w": "denied", "/usr/w": "denied"} { if !strings.Contains(screen, "probe write "+path+" "+word) { t.Errorf("write to %s is not %s", path, word) } } // Those writes are the namespace's memory: nothing on the host. _ = filepath.WalkDir(scratch, func(path string, d os.DirEntry, err error) error { if err == nil && d.Name() == "w" { t.Errorf("a write in the namespace reached the host: %s", path) } return nil }) if !strings.Contains(screen, "probe connect example.net HTTP/1.1_403_Forbidden") { t.Errorf("a host off the list was not refused: %q", screen) } if d, ok := proc.(interface{ EgressDenials() uint64 }); !ok || d.EgressDenials() == 0 { t.Error("the refusal was not counted") } if strings.Contains(screen, "CANARY") { t.Fatal("the namespace read a canary") } // The CLI leaves a child that ignores a hangup, and exits: the // namespace ends with it, the child too, and its scratch goes. if _, err = proc.Stdin().Write([]byte("orphan-child\r")); err != nil { t.Fatal(err) } if _, err = proc.Wait(ctx); err != nil { t.Fatal(err) } <-read mu.Lock() ns := record.NamespaceID id := record.ID mu.Unlock() if ns == "" { t.Fatal("no namespace recorded") } entries, _ := os.ReadDir("/proc") for _, e := range entries { if link, err := os.Readlink(filepath.Join("/proc", e.Name(), "ns", "pid")); err == nil && link == ns { t.Fatalf("process %s outlived the namespace", e.Name()) } } if children() != 0 { t.Fatal("the CLI's child outlived it") } if _, err = os.Stat(filepath.Join(scratch, "attempt-"+id)); !os.IsNotExist(err) { t.Fatalf("the namespace's scratch stayed: %v", err) } records, _ := m.Records(ctx) for _, r := range records { if err = m.Forget(ctx, r); err != nil { t.Fatal(err) } } }