oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package runner
2
3import (
4 "bufio"
5 "context"
6 "encoding/json"
7 "io"
8 "net"
9 "os"
10 "path/filepath"
11 "strings"
12 "testing"
13 "time"
14
15 "amadan.net/oficina/equipo/internal/equipo/team"
16 "amadan.net/oficina/equipo/internal/runner/provider"
17 "amadan.net/oficina/equipo/internal/runnerproto"
18)
19
20func toolFixture(t *testing.T) (*AttemptSocket, ToolBinding) {
21 t.Helper()
22 root, err := os.MkdirTemp(os.Getenv("TMPDIR"), "e13-")
23 mustJournal(t, err)
24 t.Cleanup(func() { os.RemoveAll(root) })
25 j, err := OpenJournal(context.Background(), filepath.Join(root, "journal", "events.db"))
26 mustJournal(t, err)
27 t.Cleanup(func() { j.Close() })
28 b := ToolBinding{Copy: ToolCopy{Acceptance: "acceptance fixture", Answer: "answer fixture", Render: "render fixture", Accepted: "accepted fixture", Rejected: "rejected fixture", Ask: "ask fixture", Candidate: "candidate fixture", Review: "review fixture", Reproduction: "reproduction fixture"}, InstanceID: "instance", TaskID: "task", Attempt: 1, Fence: 1, Tools: []string{"ask_person", "submit_candidate"}, LeaseDeadline: time.Now().Add(time.Minute), Agent: provider.Agent{Provider: "codex", ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Isolation: team.IsolationSnapshot{Status: "unconfined", RunnerTainted: true}, Journal: j, Current: func(context.Context) error { return nil }}
29 s, err := NewAttemptSocket(context.Background(), root, b)
30 mustJournal(t, err)
31 t.Cleanup(func() { s.Cleanup(context.Background(), func(context.Context) error { return nil }) })
32 return s, b
33}
34func TestAgentToolScope(t *testing.T) {
35 s, b := toolFixture(t)
36 cap, err := readToolCapability(s.CapabilityPath)
37 mustJournal(t, err)
38 if cap.Copy.Acceptance != b.Copy.Acceptance || cap.Copy.Answer != b.Copy.Answer || cap.Copy.Render != b.Copy.Render {
39 t.Fatal("plan tool copy lost in capability")
40 }
41 q := toolRequest{Capability: cap.Secret, InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: 1, Fence: 1, RequestID: "request", Name: "ask_person", Arguments: json.RawMessage(`{"question":"Which colour?"}`)}
42 if err := callToolSocket(context.Background(), s.SocketPath, q); err != nil {
43 t.Fatal(err)
44 }
45 if err := callToolSocket(context.Background(), s.SocketPath, q); err != nil {
46 t.Fatal("exact replay", err)
47 }
48 rows, err := b.Journal.ToolSubmissions(context.Background(), 10)
49 mustJournal(t, err)
50 if len(rows) != 1 || rows[0].Agent.ProviderSessionID != "session" || !rows[0].Isolation.RunnerTainted {
51 t.Fatal("missing durable scoped provenance", rows)
52 }
53 for _, field := range []string{"capability", "task", "instance", "attempt", "fence", "name", "payload", "injection", "request_id"} {
54 t.Run(field, func(t *testing.T) {
55 bad := q
56 switch field {
57 case "request_id":
58 bad.RequestID = ""
59 case "capability":
60 bad.Capability = "wrong"
61 case "task":
62 bad.TaskID = "other"
63 case "instance":
64 bad.InstanceID = "other"
65 case "attempt":
66 bad.Attempt++
67 case "fence":
68 bad.Fence++
69 case "name":
70 bad.Name = "publish"
71 case "payload":
72 bad.Arguments = json.RawMessage(`{"question":"Changed"}`)
73 case "injection":
74 bad.RequestID = "new"
75 bad.Arguments = json.RawMessage(`{"question":"hi","tools":["publish"]}`)
76 }
77 if callToolSocket(context.Background(), s.SocketPath, bad) == nil {
78 t.Fatal("scope guard accepted", field)
79 }
80 })
81 }
82}
83func TestToolSocketIsolation(t *testing.T) {
84 s, _ := toolFixture(t)
85 for p, mode := range map[string]os.FileMode{filepath.Dir(s.SocketPath): 0700, s.SocketPath: 0600, s.CapabilityPath: 0600} {
86 i, err := os.Stat(p)
87 mustJournal(t, err)
88 if i.Mode().Perm() != mode {
89 t.Fatal("private mode", p, i.Mode())
90 }
91 }
92 link := filepath.Join(t.TempDir(), "link")
93 mustJournal(t, os.Symlink(s.CapabilityPath, link))
94 if _, err := readToolCapability(link); err == nil {
95 t.Fatal("symlink capability accepted")
96 }
97 mustJournal(t, os.Chmod(s.CapabilityPath, 0644))
98 if _, err := readToolCapability(s.CapabilityPath); err == nil {
99 t.Fatal("public capability accepted")
100 }
101 mustJournal(t, os.Chmod(s.CapabilityPath, 0600))
102 if _, err := readToolCapability(s.CapabilityPath + "missing"); err == nil {
103 t.Fatal("missing capability accepted")
104 }
105 if _, err := ServeAttemptSocket(context.Background(), "/"+strings.Repeat("x", 108), ToolBinding{}); err == nil {
106 t.Fatal("long socket accepted")
107 }
108 cap, err := readToolCapability(s.CapabilityPath)
109 mustJournal(t, err)
110 s.Invalidate()
111 if callToolSocket(context.Background(), s.SocketPath, toolRequest{Capability: cap.Secret}) == nil {
112 t.Fatal("invalidated socket accepted")
113 }
114}
115
116func TestToolSocketFramesAndLease(t *testing.T) {
117 s, b := toolFixture(t)
118 for _, raw := range []string{"{broken}\n", strings.Repeat("x", maxToolFrame+1) + "\n", `{"capability":"x","capability":"y"}` + "\n"} {
119 c, err := net.Dial("unix", s.SocketPath)
120 mustJournal(t, err)
121 c.SetDeadline(time.Now().Add(3 * time.Second))
122 _, _ = c.Write([]byte(raw))
123 data, _ := io.ReadAll(c)
124 c.Close()
125 if strings.Contains(string(data), `"ok":true`) {
126 t.Fatal("malformed frame accepted")
127 }
128 }
129 cap, err := readToolCapability(s.CapabilityPath)
130 mustJournal(t, err)
131 q := toolRequest{Capability: cap.Secret, InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: 1, Fence: 1, RequestID: "r", Name: "ask_person", Arguments: json.RawMessage(`{"question":"Hi?"}`)}
132 for _, name := range []string{"read_task", "publish", "attest_checks", "set_budget", "admit", "settle", "submit_review"} {
133 bad := q
134 bad.Name = name
135 if name == "submit_review" {
136 bad.Arguments = json.RawMessage(`{"candidate":"` + strings.Repeat("a", 40) + `","decision":"approve","findings":[]}`)
137 }
138 if callToolSocket(context.Background(), s.SocketPath, bad) == nil {
139 t.Fatal("unauthorized tool accepted", name)
140 }
141 }
142 s.mu.Lock()
143 s.binding.LeaseDeadline = time.Now().Add(-time.Second)
144 s.mu.Unlock()
145 if callToolSocket(context.Background(), s.SocketPath, q) == nil {
146 t.Fatal("expired lease accepted")
147 }
148 s.mu.Lock()
149 s.binding.LeaseDeadline = time.Now().Add(time.Minute)
150 s.mu.Unlock()
151 if callToolSocket(context.Background(), s.SocketPath, q) == nil {
152 t.Fatal("expired capability revived")
153 }
154}
155func TestToolSocketCurrentAuthority(t *testing.T) {
156 s, b := toolFixture(t)
157 cap, err := readToolCapability(s.CapabilityPath)
158 mustJournal(t, err)
159 q := toolRequest{Capability: cap.Secret, InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: 1, Fence: 1, RequestID: "r", Name: "ask_person", Arguments: json.RawMessage(`{"question":"Hi?"}`)}
160 s.mu.Lock()
161 s.binding.Current = func(context.Context) error { return runnerproto.ErrInvalid }
162 s.mu.Unlock()
163 if callToolSocket(context.Background(), s.SocketPath, q) == nil {
164 t.Fatal("changed fence authority accepted")
165 }
166 s.mu.Lock()
167 s.binding.Current = func(context.Context) error { return nil }
168 s.mu.Unlock()
169 if callToolSocket(context.Background(), s.SocketPath, q) == nil {
170 t.Fatal("old capability revived after authority change")
171 }
172 if err := s.Cleanup(context.Background(), func(context.Context) error { return runnerproto.ErrInvalid }); err == nil {
173 t.Fatal("unproved containment cleaned files")
174 }
175 if _, err := os.Stat(s.CapabilityPath); err != nil {
176 t.Fatal("removed before containment")
177 }
178}
179func TestAgentToolJournalReopen(t *testing.T) {
180 s, b := toolFixture(t)
181 cap, err := readToolCapability(s.CapabilityPath)
182 mustJournal(t, err)
183 q := toolRequest{Capability: cap.Secret, InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: 1, Fence: 1, RequestID: "r", Name: "submit_candidate", Arguments: json.RawMessage(`{"commit":"` + strings.Repeat("a", 40) + `"}`)}
184 mustJournal(t, callToolSocket(context.Background(), s.SocketPath, q))
185 s.Invalidate()
186 s.workers.Wait()
187 mustJournal(t, b.Journal.Close())
188 j, err := OpenJournal(context.Background(), b.Journal.path)
189 mustJournal(t, err)
190 defer j.Close()
191 rows, err := j.ToolSubmissions(context.Background(), 10)
192 mustJournal(t, err)
193 if len(rows) != 1 {
194 t.Fatal("ACK before durable request")
195 }
196 mustJournal(t, j.AckTool(context.Background(), rows[0]))
197 saved := rows[0]
198 mustJournal(t, j.Close())
199 j, err = OpenJournal(context.Background(), b.Journal.path)
200 mustJournal(t, err)
201 defer j.Close()
202 changed := saved
203 changed.Arguments = json.RawMessage(`{"commit":"` + strings.Repeat("b", 40) + `"}`)
204 if j.appendTool(context.Background(), changed, runnerproto.EventHash(changed.Arguments)) == nil {
205 t.Fatal("changed replay accepted after ACK and reopen")
206 }
207 var effects int
208 mustJournal(t, j.db.QueryRow("SELECT count(*) FROM journal_tools").Scan(&effects))
209 if effects != 1 {
210 t.Fatal("changed replay duplicated effect")
211 }
212
213 mustJournal(t, j.appendTool(context.Background(), rows[0], runnerproto.EventHash(json.RawMessage(q.Arguments))))
214 rows, err = j.ToolSubmissions(context.Background(), 10)
215 mustJournal(t, err)
216 if len(rows) != 0 {
217 t.Fatal("acked request replayed")
218 }
219}
220
221func TestToolSocketReadPolicyAndOwnership(t *testing.T) {
222 if !toolOwner(uint32(os.Getuid())) || toolOwner(uint32(os.Getuid()+1)) {
223 t.Fatal("peer UID alone must not cross users")
224 }
225 s, b := toolFixture(t)
226 b.Agent.Provider = "claude"
227 b.Isolation.Status = "confined"
228 root := filepath.Dir(filepath.Dir(filepath.Dir(s.SocketPath)))
229 if _, err := NewAttemptSocket(context.Background(), root, b); err == nil {
230 t.Fatal("Claude can read capability state")
231 }
232 b.ReadPolicy.DeniedPaths = []string{root}
233 second, err := NewAttemptSocket(context.Background(), root, b)
234 mustJournal(t, err)
235 mustJournal(t, second.Cleanup(context.Background(), func(context.Context) error { return nil }))
236 b.Agent.Provider = "codex"
237 if _, err := NewAttemptSocket(context.Background(), root, b); err == nil {
238 t.Fatal("false Codex confinement accepted")
239 }
240}
241
242func TestToolSocketCannotRecreateAuthority(t *testing.T) {
243 s, b := toolFixture(t)
244 if _, err := ServeAttemptSocket(context.Background(), s.SocketPath, b); err == nil {
245 t.Fatal("existing socket replaced")
246 }
247 link := filepath.Join(filepath.Dir(s.SocketPath), "link-dir")
248 mustJournal(t, os.Symlink(filepath.Dir(s.CapabilityPath), link))
249 if _, err := readToolCapability(filepath.Join(link, filepath.Base(s.CapabilityPath))); err == nil {
250 t.Fatal("symlink ancestor accepted")
251 }
252 mustJournal(t, os.Remove(link))
253 mustJournal(t, s.Cleanup(context.Background(), func(context.Context) error { return nil }))
254 if _, err := os.Stat(s.CapabilityPath); !os.IsNotExist(err) {
255 t.Fatal("capability remains after containment")
256 }
257 if callToolSocket(context.Background(), s.SocketPath, toolRequest{}) == nil {
258 t.Fatal("removed socket accepted")
259 }
260}
261
262func TestToolSocketFrameBoundary(t *testing.T) {
263 raw := strings.Repeat(" ", maxToolFrame) + "\n"
264 if _, err := readToolFrame(bufio.NewReaderSize(strings.NewReader(raw), len(raw)+1)); err == nil {
265 t.Fatal("oversized frame boundary accepted")
266 }
267}
268
269func TestToolSocketPublicStateAndStorageFailure(t *testing.T) {
270 s, b := toolFixture(t)
271 root := filepath.Dir(filepath.Dir(filepath.Dir(s.SocketPath)))
272 mustJournal(t, os.Chmod(root, 0755))
273 if _, err := NewAttemptSocket(context.Background(), root, b); err == nil {
274 t.Fatal("public state directory accepted")
275 }
276 mustJournal(t, os.Chmod(root, 0700))
277 cap, err := readToolCapability(s.CapabilityPath)
278 mustJournal(t, err)
279 b.Journal.maxBytes = 1
280 q := toolRequest{Capability: cap.Secret, InstanceID: cap.InstanceID, TaskID: cap.TaskID, Attempt: cap.Attempt, Fence: cap.Fence, RequestID: "r", Name: "ask_person", Arguments: json.RawMessage(`{"question":"Hi?"}`)}
281 if callToolSocket(context.Background(), s.SocketPath, q) == nil {
282 t.Fatal("ACK on exhausted journal")
283 }
284 rows, err := b.Journal.ToolSubmissions(context.Background(), 10)
285 mustJournal(t, err)
286 if len(rows) != 0 {
287 t.Fatal("overflow queued tool")
288 }
289}
290
291func TestToolSocketStaleCapabilityFile(t *testing.T) {
292 s, _ := toolFixture(t)
293 cap, err := readToolCapability(s.CapabilityPath)
294 mustJournal(t, err)
295 cap.ExpiresAt = time.Now().Add(-time.Second)
296 raw, _ := json.Marshal(cap)
297 mustJournal(t, os.WriteFile(s.CapabilityPath, raw, 0600))
298 if _, err := readToolCapability(s.CapabilityPath); err != nil {
299 t.Fatal("stale file expiry overrode trusted socket lease")
300 }
301}
302