oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package headless
2
3import (
4 "bytes"
5 "context"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "strings"
10 "sync"
11 "testing"
12 "time"
13
14 "amadan.net/oficina/equipo/internal/runner/containment"
15 "amadan.net/oficina/equipo/internal/runner/provider"
16 "amadan.net/oficina/equipo/internal/testci"
17)
18
19// The sign-in's `claude setup-token` (the fake) in the real namespace,
20// as the runner starts it (provider.BuildSignInPolicy, StartTerminal):
21// on a terminal; another account's home and the runner's state are not
22// there to read; it writes only to its home and /tmp, both its own
23// memory (nothing reaches the host), not to the workspace, /etc or
24// /usr; a CONNECT to a host off its list
25// is refused by the egress proxy and counted. A child the CLI starts
26// that ignores a hangup dies with the namespace when the CLI exits, and
27// the namespace's scratch, where a code typed in could have been
28// written, is gone once its exit is proven.
29func TestHeadlessSignInContained(t *testing.T) {
30 testci.Tools(t, "bwrap")
31 if _, err := exec.LookPath("/usr/bin/bwrap"); err != nil {
32 t.Skip("bubblewrap is required")
33 }
34 root := private(t, filepath.Join(t.TempDir(), "root"))
35 bin := private(t, filepath.Join(root, "bin"))
36 copyExecutable(t, filepath.Join(bin, "claude"))
37 other := private(t, filepath.Join(root, "accounts", "claude-1"))
38 state := private(t, filepath.Join(root, "state"))
39 canaries := []string{filepath.Join(other, ".credentials.json"), filepath.Join(other, ".oauth-token"), filepath.Join(state, "thin.db"), filepath.Join(bin, "claude")}
40 for _, f := range canaries[:3] {
41 if err := os.WriteFile(f, []byte("CANARY-NOT-FOR-THE-SIGN-IN"), 0600); err != nil {
42 t.Fatal(err)
43 }
44 }
45 scratch := private(t, filepath.Join(root, "scratch"))
46 self, _ := os.Executable()
47 m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: self, ScratchRoot: scratch, ProviderNetworks: []provider.NetworkContract{{Provider: "claude"}}})
48 if err != nil {
49 t.Fatal(err)
50 }
51 policy, err := provider.BuildSignInPolicy(provider.SignInPolicyInputs{Binary: filepath.Join(bin, "claude"), Bwrap: "/usr/bin/bwrap"})
52 if err != nil {
53 t.Fatal(err)
54 }
55 var mu sync.Mutex
56 var record containment.Record
57 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
58 defer cancel()
59 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 {
60 mu.Lock()
61 record = r
62 mu.Unlock()
63 return nil
64 })
65 if err != nil {
66 t.Fatal(err)
67 }
68 var out bytes.Buffer
69 read := make(chan struct{})
70 go func() {
71 defer close(read)
72 buf := make([]byte, 4096)
73 for {
74 n, err := proc.Stdout().Read(buf)
75 mu.Lock()
76 out.Write(buf[:n])
77 mu.Unlock()
78 if err != nil {
79 return
80 }
81 }
82 }()
83 seen := func(what string) string {
84 t.Helper()
85 deadline := time.Now().Add(time.Minute)
86 for time.Now().Before(deadline) {
87 mu.Lock()
88 s := out.String()
89 mu.Unlock()
90 if strings.Contains(s, what) {
91 return s
92 }
93 time.Sleep(50 * time.Millisecond)
94 }
95 t.Fatalf("no %q in %q", what, out.String())
96 return ""
97 }
98 seen("Paste code here if prompted >")
99 if _, err = proc.Stdin().Write([]byte("probe:" + strings.Join(canaries, ",") + "\r")); err != nil {
100 t.Fatal(err)
101 }
102 screen := seen("probe done")
103 for _, f := range canaries {
104 if !strings.Contains(screen, "probe read "+f+" absent") {
105 t.Errorf("%s is there to read in the namespace", f)
106 }
107 }
108 // /opt is in bubblewrap's own root, in memory, as for every launch:
109 // a write there reaches no host disk and ends with the namespace.
110 for path, word := range map[string]string{"/home/runner/w": "ok", "/tmp/w": "ok", "/workspace/w": "denied", "/etc/w": "denied", "/usr/w": "denied"} {
111 if !strings.Contains(screen, "probe write "+path+" "+word) {
112 t.Errorf("write to %s is not %s", path, word)
113 }
114 }
115 // Those writes are the namespace's memory: nothing on the host.
116 _ = filepath.WalkDir(scratch, func(path string, d os.DirEntry, err error) error {
117 if err == nil && d.Name() == "w" {
118 t.Errorf("a write in the namespace reached the host: %s", path)
119 }
120 return nil
121 })
122 if !strings.Contains(screen, "probe connect example.net HTTP/1.1_403_Forbidden") {
123 t.Errorf("a host off the list was not refused: %q", screen)
124 }
125 if d, ok := proc.(interface{ EgressDenials() uint64 }); !ok || d.EgressDenials() == 0 {
126 t.Error("the refusal was not counted")
127 }
128 if strings.Contains(screen, "CANARY") {
129 t.Fatal("the namespace read a canary")
130 }
131
132 // The CLI leaves a child that ignores a hangup, and exits: the
133 // namespace ends with it, the child too, and its scratch goes.
134 if _, err = proc.Stdin().Write([]byte("orphan-child\r")); err != nil {
135 t.Fatal(err)
136 }
137 if _, err = proc.Wait(ctx); err != nil {
138 t.Fatal(err)
139 }
140 <-read
141 mu.Lock()
142 ns := record.NamespaceID
143 id := record.ID
144 mu.Unlock()
145 if ns == "" {
146 t.Fatal("no namespace recorded")
147 }
148 entries, _ := os.ReadDir("/proc")
149 for _, e := range entries {
150 if link, err := os.Readlink(filepath.Join("/proc", e.Name(), "ns", "pid")); err == nil && link == ns {
151 t.Fatalf("process %s outlived the namespace", e.Name())
152 }
153 }
154 if children() != 0 {
155 t.Fatal("the CLI's child outlived it")
156 }
157 if _, err = os.Stat(filepath.Join(scratch, "attempt-"+id)); !os.IsNotExist(err) {
158 t.Fatalf("the namespace's scratch stayed: %v", err)
159 }
160 records, _ := m.Records(ctx)
161 for _, r := range records {
162 if err = m.Forget(ctx, r); err != nil {
163 t.Fatal(err)
164 }
165 }
166}
167