oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package claude
2
3import (
4 "context"
5 "crypto/sha256"
6 "encoding/hex"
7 "encoding/json"
8 "errors"
9 "io"
10 "io/fs"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "runtime"
15 "strings"
16 "testing"
17 "time"
18
19 "amadan.net/oficina/equipo/internal/runner/provider"
20 "amadan.net/oficina/equipo/internal/testci"
21)
22
23// Only the transport and capture are test code; policy, Open and the
24// no-input dependency probe use the production launcher. There is no egress.
25type offlineClaudeHost struct {
26 t *testing.T
27 home string
28}
29
30func (h *offlineClaudeHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) {
31 if _, err := provider.AttestLaunch(l, argv); err != nil {
32 return nil, err
33 }
34 home := l.Binding.Home
35 if h.home != "" {
36 home = h.home
37 }
38 args := []string{"--unshare-all", "--die-with-parent", "--new-session", "--ro-bind", "/usr", "/usr", "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--bind", home, "/home/runner", "--bind", l.Workspace, "/workspace"}
39 for _, m := range l.Policy.Mounts {
40 if m.Target == provider.SettingsPath {
41 raw, e := os.ReadFile(m.Source)
42 if e != nil || !sameJSON(raw, l.Policy.Settings) {
43 h.t.Fatal("mounted settings differ from policy", e)
44 }
45 var settings map[string]any
46 if json.Unmarshal(raw, &settings) != nil {
47 h.t.Fatal("invalid mounted settings")
48 }
49 plugins, ok := settings["enabledPlugins"].(map[string]any)
50 if !ok || plugins["agents-md@builtin"] != false || plugins["plugin-authoring@builtin"] != false || settings["autoMemoryEnabled"] != false || settings["autoDreamEnabled"] != false {
51 h.t.Fatal("startup settings readback failed")
52 }
53 }
54 args = append(args, "--ro-bind", m.Source, m.Target)
55 }
56 args = append(args, "--chdir", "/workspace", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin:/opt", "--setenv", "HOME", "/home/runner", "--setenv", "TMPDIR", "/tmp")
57 for k, v := range l.Policy.Env {
58 args = append(args, "--setenv", k, v)
59 }
60 args = append(args, argv...)
61 cmd := exec.CommandContext(ctx, "bwrap", args...)
62 in, err := cmd.StdinPipe()
63 if err != nil {
64 return nil, err
65 }
66 out, outWrite, err := os.Pipe()
67 if err != nil {
68 in.Close()
69 return nil, err
70 }
71 cmd.Stdout = outWrite
72 p := &fakeProcess{cmd: cmd, in: in, out: out, err: io.NopCloser(strings.NewReader("")), done: make(chan struct{})}
73 if err = cmd.Start(); err != nil {
74 in.Close()
75 out.Close()
76 outWrite.Close()
77 return nil, err
78 }
79 go func() { _ = cmd.Wait(); outWrite.Close(); p.exit.Code = cmd.ProcessState.ExitCode(); close(p.done) }()
80 h.t.Cleanup(func() { _ = cmd.Process.Kill(); <-p.done; in.Close(); out.Close() })
81 return p, nil
82}
83
84type offlineClaudeCapture struct{ loggedOut bool }
85
86func (c *offlineClaudeCapture) Open(ctx context.Context, p provider.Process, _ provider.Launch) (*provider.Capture, error) {
87 frames, done := make(chan provider.Frame), make(chan error, 1)
88 go func() {
89 defer close(done)
90 defer close(frames)
91 decoder := json.NewDecoder(io.LimitReader(p.Stdout(), MaxFrameBytes+1))
92 for seq := int64(1); ; seq++ {
93 var raw json.RawMessage
94 err := decoder.Decode(&raw)
95 if err == io.EOF {
96 done <- nil
97 return
98 }
99 if err != nil {
100 done <- err
101 return
102 }
103 var status struct {
104 LoggedIn *bool `json:"loggedIn"`
105 }
106 if json.Unmarshal(raw, &status) == nil && status.LoggedIn != nil && !*status.LoggedIn {
107 c.loggedOut = true
108 }
109 select {
110 case frames <- provider.Frame{Sequence: seq, Bytes: raw}:
111 case <-ctx.Done():
112 done <- ctx.Err()
113 return
114 }
115 }
116 }()
117 return &provider.Capture{Input: p.Stdin(), Frames: frames, Done: done}, nil
118}
119
120func TestClaudeEmptyHomeReplay(t *testing.T) {
121 testci.Tools(t, "try-bin", "bwrap", "python3")
122 home, err := os.UserHomeDir()
123 if err != nil {
124 t.Fatal(err)
125 }
126 binary := filepath.Join(home, ".local/share/equipo/try/bin/claude")
127 file, err := os.Open(binary)
128 if os.IsNotExist(err) {
129 testci.Absent(t, "pinned Claude 2.1.312 binary absent; empty-home replay requires the local pinned installation")
130 }
131 if err != nil {
132 t.Fatal(err)
133 }
134 sum := sha256.New()
135 _, err = io.Copy(sum, file)
136 file.Close()
137 // The official build for this machine: the certified pin on amd64.
138 pin, ok := ReleasePin(runtime.GOARCH)
139 if !ok {
140 t.Fatalf("no pinned Claude 2.1.312 build for %s", runtime.GOARCH)
141 }
142 if err != nil || hex.EncodeToString(sum.Sum(nil)) != pin {
143 t.Fatal("pinned Claude digest differs")
144 }
145 for _, role := range []string{"Engineering", "Coordinator"} {
146 t.Run(role, func(t *testing.T) {
147 f := fixtureFor(t, role)
148 var settings map[string]any
149 json.Unmarshal(f.inputs.Settings, &settings)
150 if settings["enabledPlugins"].(map[string]any)["agents-md@builtin"] != false || settings["enabledPlugins"].(map[string]any)["plugin-authoring@builtin"] != false || settings["autoMemoryEnabled"] != false || settings["autoDreamEnabled"] != false {
151 t.Error("plugins, memory or dreaming not disabled")
152 }
153 source := filepath.Join(filepath.Dir(f.interactive), "dedicated")
154 for _, name := range []string{".credentials.json", ".claude.json"} {
155 if err = os.WriteFile(filepath.Join(source, name), []byte(`{}`), 0600); err != nil {
156 t.Fatal(err)
157 }
158 }
159 f.lease.Close()
160 id := f.lease.Identity()
161 f.lease, err = provider.OpenAccount(context.Background(), provider.Binding{ID: "binding", Home: source, AccountID: id.AccountID, Provider: "claude", Expected: id, RuntimeRoot: filepath.Join(filepath.Dir(source), "empty-homes")})
162 if err != nil {
163 t.Fatal(err)
164 }
165 t.Cleanup(func() { f.lease.Close() })
166 f.launch.Binding = f.lease.Binding()
167 in := f.inputs
168 in.RuntimeFiles[0].Source = binary
169 in.DeniedPaths = []string{"/private/state", "/alias/login"}
170 in.Action = "implement"
171 if role == "Coordinator" {
172 in.Action = "coordinate"
173 }
174 profile, _ := provider.Profile(in.Action)
175 in.Tools = profile.MCPTools()
176 in, err = PolicyInputs(f.lease.Binding(), in, role, f.launch.Selection.Model)
177 if err != nil {
178 t.Fatal(err)
179 }
180 f.launch.Policy, err = provider.BuildPolicy(f.lease.Binding(), in)
181 if err != nil {
182 t.Fatal(err)
183 }
184 host := &offlineClaudeHost{t: t}
185 capture := &offlineClaudeCapture{}
186 launcher, err := New(host, capture)
187 if err != nil {
188 t.Fatal(err)
189 }
190 launcher.digest = pin
191 ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
192 defer cancel()
193 _, err = launcher.Open(ctx, f.launch)
194 if !errors.Is(err, errFailed) || errors.Is(err, provider.ErrContainment) || !capture.loggedOut {
195 t.Fatalf("expected unauthenticated auth exit from Open, got %v", err)
196 }
197 t.Logf("real Open: %v", err)
198 // Auth exits before the no-input -p probe. Exercise that exact probe
199 // separately, first with a completely empty config directory.
200 for _, empty := range []bool{true, false} {
201 root := f.lease.Binding().Home
202 if empty {
203 root = t.TempDir()
204 host.home = root
205 } else {
206 host.home = ""
207 }
208 var probeErr error
209 err = f.lease.Preflight(ctx, func(ctx context.Context, b provider.Binding) (provider.Identity, error) {
210 _, probeErr = launcher.probe(ctx, b, in, append(append([]string{}, in.Argv...), "--session-id", uuid()))
211 return provider.Identity{}, provider.ErrIdentity
212 })
213 if !errors.Is(err, provider.ErrIdentity) {
214 t.Fatal(err)
215 }
216 err = probeErr
217 t.Logf("full preflight empty=%v: %v", empty, err)
218 if err != nil {
219 t.Fatalf("probe did not complete: %v", err)
220 }
221 for _, name := range []string{"plugins", "skills", "agents", "commands", "shell-snapshots", "session-env"} {
222 if _, e := os.Lstat(filepath.Join(root, name)); !os.IsNotExist(e) {
223 t.Fatalf("policy entry created: %s: %v", name, e)
224 }
225 }
226 if err = filepath.WalkDir(root, func(path string, d fs.DirEntry, e error) error {
227 if e != nil {
228 return e
229 }
230 if path == root {
231 return nil
232 }
233 info, e := d.Info()
234 if e != nil {
235 return e
236 }
237 rel, _ := filepath.Rel(root, path)
238 t.Logf("runtime empty=%v: %s %s %04o", empty, rel, info.Mode().Type(), info.Mode().Perm())
239 return nil
240 }); err != nil {
241 t.Fatal(err)
242 }
243 }
244 // No real CLI runs with this synthetic identity. It only enables the
245 // final runtime-policy check after every subprocess has exited.
246 if err = f.lease.Preflight(ctx, func(context.Context, provider.Binding) (provider.Identity, error) { return f.lease.Identity(), nil }); err != nil {
247 t.Fatal(err)
248 }
249 if err = f.lease.ValidatePolicy(ctx); err != nil {
250 t.Fatalf("real runtime tree rejected: %v", err)
251 }
252 })
253 }
254}
255