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 "bytes"
6 "context"
7 "crypto/rand"
8 "crypto/subtle"
9 "encoding/json"
10 "io"
11 "net"
12 "os"
13 "path/filepath"
14 "slices"
15 "strings"
16 "sync"
17 "time"
18
19 "amadan.net/oficina/equipo/internal/equipo/team"
20
21 "amadan.net/oficina/equipo/internal/runner/provider"
22 "amadan.net/oficina/equipo/internal/runnerproto"
23 "golang.org/x/sys/unix"
24)
25
26const maxToolFrame = 64 << 10
27
28type ToolBinding struct {
29 // Ask returns only an authenticated answer to the bound scoped question.
30 Ask func(context.Context, ToolBinding, string, json.RawMessage) (json.RawMessage, error)
31
32 Session provider.Session
33 TurnID string
34 // Permission is the trusted adapter's MCP permission handler, never model code.
35 Permission func(context.Context, json.RawMessage) (json.RawMessage, error)
36
37 ReadPolicy provider.ReadPolicy
38 Copy ToolCopy
39 InstanceID, TaskID string
40 Attempt, Fence int64
41 Tools []string
42 LeaseDeadline time.Time
43 Agent provider.Agent
44 Isolation team.IsolationSnapshot
45 Journal *Journal
46 // Current must revalidate the current lease, fence, agent/session and trusted
47 // read policy. Failure permanently invalidates this socket, even if renewed.
48 Current func(context.Context) error
49}
50type toolCapability struct {
51 Coordinator bool `json:"coordinator,omitempty"`
52 Copy ToolCopy `json:"copy"`
53 Secret string `json:"secret"`
54 InstanceID string `json:"instance_id"`
55 TaskID string `json:"task_id"`
56 Attempt int64 `json:"attempt"`
57 Fence int64 `json:"fence"`
58 Tools []string `json:"tools"`
59 ExpiresAt time.Time `json:"expires_at"`
60}
61type toolRequest struct {
62 Capability string `json:"capability"`
63 InstanceID string `json:"instance_id"`
64 TaskID string `json:"task_id"`
65 Attempt int64 `json:"attempt"`
66 Fence int64 `json:"fence"`
67 RequestID string `json:"request_id"`
68 Name string `json:"name"`
69 Arguments json.RawMessage `json:"arguments"`
70}
71type AttemptSocket struct {
72 SocketPath, CapabilityPath string
73 listener *net.UnixListener
74 binding ToolBinding
75 capability toolCapability
76 mu sync.Mutex
77 invalid bool
78 pending bool
79 done chan struct{}
80 renewed chan struct{}
81 workers sync.WaitGroup
82}
83
84func NewAttemptSocket(ctx context.Context, stateDir string, b ToolBinding) (*AttemptSocket, error) {
85 return newAttemptSocket(ctx, stateDir, b, false)
86}
87func newAttemptSocket(ctx context.Context, stateDir string, b ToolBinding, pending bool) (*AttemptSocket, error) {
88 if !filepath.IsAbs(stateDir) || filepath.Clean(stateDir) != stateDir {
89 return nil, runnerproto.ErrInvalid
90 }
91 // Check the longest resulting address before creating any filesystem entry.
92 root := filepath.Join(stateDir, "attempts")
93 dir := filepath.Join(root, rand.Text())
94 if len(filepath.Join(dir, "tool.sock")) > 107 {
95 return nil, runnerproto.ErrInvalid
96 }
97 f, err := openPrivateDir(stateDir)
98 if err != nil {
99 return nil, err
100 }
101 f.Close()
102 if err := os.Mkdir(root, 0700); err != nil && !os.IsExist(err) {
103 return nil, runnerproto.ErrInvalid
104 }
105 f, err = openPrivateDir(root)
106 if err != nil {
107 return nil, err
108 }
109 f.Close()
110 if err := os.Mkdir(dir, 0700); err != nil {
111 return nil, runnerproto.ErrInvalid
112 }
113 s, err := serveAttemptSocket(ctx, filepath.Join(dir, "tool.sock"), b, pending)
114 if err != nil {
115 _ = os.Remove(dir)
116 }
117 return s, err
118}
119func ServeAttemptSocket(ctx context.Context, path string, b ToolBinding) (*AttemptSocket, error) {
120 return serveAttemptSocket(ctx, path, b, false)
121}
122func serveAttemptSocket(ctx context.Context, path string, b ToolBinding, pending bool) (*AttemptSocket, error) {
123 if len(path) > 107 || !filepath.IsAbs(path) || filepath.Clean(path) != path || b.Journal == nil || b.Current == nil || b.InstanceID == "" || b.TaskID == "" || b.Attempt <= 0 || b.Fence <= 0 || !time.Now().Before(b.LeaseDeadline) || b.Agent.ServerID == "" || b.Agent.AgentID == "" || b.Agent.ProviderSessionID == "" || len(b.Tools) == 0 || (b.Isolation.Status != "confined" && b.Isolation.Status != "unconfined") {
124 return nil, runnerproto.ErrInvalid
125 }
126 for _, name := range b.Tools {
127 if !slices.Contains([]string{"submit_reproduction", "submit_candidate", "submit_review", "submit_acceptance", "submit_answer", "submit_render", "ask_person"}, name) {
128 return nil, runnerproto.ErrInvalid
129 }
130 }
131 if b.Copy.Accepted == "" || b.Copy.Rejected == "" {
132 return nil, runnerproto.ErrInvalid
133 }
134 if b.Agent.Provider == "claude" {
135 denied := false
136 for _, p := range b.ReadPolicy.DeniedPaths {
137 if filepath.IsAbs(p) && filepath.Clean(p) == p && (filepath.Dir(path) == p || strings.HasPrefix(filepath.Dir(path), p+string(filepath.Separator))) {
138 denied = true
139 }
140 }
141 if !denied || b.Isolation.Status != "confined" {
142 return nil, provider.ErrIsolation
143 }
144 } else if b.Agent.Provider != "codex" || b.Isolation.Status != "unconfined" {
145 return nil, provider.ErrIsolation
146 }
147 if err := b.Current(ctx); err != nil {
148 return nil, err
149 }
150 if err := b.Journal.AdmissionAllowed(ctx); err != nil {
151 return nil, err
152 }
153 parent, err := openPrivateDir(filepath.Dir(path))
154 if err != nil {
155 return nil, err
156 }
157 defer parent.Close()
158 b.Tools = slices.Clone(b.Tools)
159 s := &AttemptSocket{pending: pending, SocketPath: path, CapabilityPath: filepath.Join(filepath.Dir(path), "capability.json"), binding: b, done: make(chan struct{}), renewed: make(chan struct{}, 1)}
160 s.capability = toolCapability{Copy: b.Copy, Secret: rand.Text() + rand.Text(), InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, Tools: b.Tools, ExpiresAt: b.LeaseDeadline}
161 // Never overwrite an old socket or capability: restart needs a fresh directory.
162 if _, err := os.Lstat(path); !os.IsNotExist(err) {
163 return nil, runnerproto.ErrInvalid
164 }
165 if _, err := os.Lstat(s.CapabilityPath); !os.IsNotExist(err) {
166 return nil, runnerproto.ErrInvalid
167 }
168 listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"})
169 if err != nil {
170 return nil, runnerproto.ErrInvalid
171 }
172 listener.SetUnlinkOnClose(false)
173 s.listener = listener
174 fail := func() (*AttemptSocket, error) { listener.Close(); os.Remove(path); return nil, runnerproto.ErrInvalid }
175 if err := os.Chmod(path, 0600); err != nil {
176 return fail()
177 }
178 temp, err := os.CreateTemp(filepath.Dir(path), ".capability-")
179 if err != nil {
180 return fail()
181 }
182 tempPath := temp.Name()
183 defer os.Remove(tempPath)
184 raw, err := json.Marshal(s.capability)
185 if err != nil {
186 temp.Close()
187 return fail()
188 }
189 if _, err = temp.Write(raw); err != nil {
190 temp.Close()
191 return fail()
192 }
193 if err = temp.Sync(); err != nil {
194 temp.Close()
195 return fail()
196 }
197 if err = temp.Close(); err != nil {
198 return fail()
199 }
200 // Link publishes a complete 0600 file atomically without replacing a name.
201 if err = os.Link(tempPath, s.CapabilityPath); err != nil {
202 return fail()
203 }
204 if err = parent.Sync(); err != nil {
205 os.Remove(s.CapabilityPath)
206 return fail()
207 }
208 s.workers.Add(2)
209 go s.accept(ctx)
210 go func() {
211 defer s.workers.Done()
212 timer := time.NewTimer(time.Until(b.LeaseDeadline))
213 defer timer.Stop()
214 for {
215 select {
216 case <-ctx.Done():
217 s.Invalidate()
218 return
219 case <-s.done:
220 return
221 case <-timer.C:
222 case <-s.renewed:
223 }
224 s.mu.Lock()
225 remaining := time.Until(s.binding.LeaseDeadline)
226 if remaining <= 0 {
227 s.invalidateLocked()
228 }
229 invalid := s.invalid
230 s.mu.Unlock()
231 if invalid {
232 return
233 }
234 timer.Reset(remaining)
235 }
236 }()
237 return s, nil
238}
239
240// RenewLease accepts a trusted supervisor's renewed monotonic deadline.
241// It cannot revive a lost lease or change the attempt, fence or capability.
242func (s *AttemptSocket) RenewLease(ctx context.Context, deadline time.Time) error {
243 s.mu.Lock()
244 defer s.mu.Unlock()
245 if s.invalid || !time.Now().Before(s.binding.LeaseDeadline) {
246 s.invalidateLocked()
247 return runnerproto.ErrInvalid
248 }
249 if deadline.IsZero() || !time.Now().Before(deadline) {
250 return runnerproto.ErrInvalid
251 }
252 if deadline.After(s.binding.LeaseDeadline) {
253 s.binding.LeaseDeadline = deadline
254 select {
255 case s.renewed <- struct{}{}:
256 default:
257 }
258 }
259 return nil
260}
261
262func (s *AttemptSocket) Invalidate() { s.mu.Lock(); defer s.mu.Unlock(); s.invalidateLocked() }
263func (s *AttemptSocket) invalidateLocked() {
264 if !s.invalid {
265 s.invalid = true
266 close(s.done)
267 if s.listener != nil {
268 s.listener.Close()
269 }
270 }
271}
272
273// Cleanup removes authority files only after the trusted supervisor proves containment.
274func (s *AttemptSocket) Cleanup(ctx context.Context, contained func(context.Context) error) error {
275 s.Invalidate()
276 if contained == nil {
277 return runnerproto.ErrInvalid
278 }
279 if err := contained(ctx); err != nil {
280 return err
281 }
282 s.workers.Wait()
283 for _, p := range []string{s.SocketPath, s.CapabilityPath} {
284 if err := os.Remove(p); err != nil && !os.IsNotExist(err) {
285 return err
286 }
287 }
288 return os.Remove(filepath.Dir(s.SocketPath))
289}
290func (s *AttemptSocket) accept(ctx context.Context) {
291 defer s.workers.Done()
292 for {
293 conn, err := s.listener.AcceptUnix()
294 if err != nil {
295 return
296 }
297 s.workers.Add(1)
298 go func() {
299 defer s.workers.Done()
300 defer conn.Close()
301 _ = conn.SetDeadline(time.Now().Add(2 * time.Second))
302 if !toolPeer(conn) {
303 return
304 }
305 raw, err := readToolFrame(bufio.NewReaderSize(conn, maxToolFrame+1))
306 if err != nil {
307 return
308 }
309 var q toolRequest
310 if runnerproto.DecodeLimit(bytes.NewReader(raw), &q, maxToolFrame) != nil {
311 return
312 }
313 err = s.submit(ctx, q)
314 _ = json.NewEncoder(conn).Encode(struct {
315 OK bool `json:"ok"`
316 }{err == nil})
317 }()
318 }
319}
320func toolPeer(c *net.UnixConn) bool {
321 raw, err := c.SyscallConn()
322 if err != nil {
323 return false
324 }
325 ok := false
326 if raw.Control(func(fd uintptr) {
327 uid, err := peerUID(int(fd))
328 ok = err == nil && toolOwner(uid)
329 }) != nil {
330 return false
331 }
332 return ok
333}
334func (s *AttemptSocket) submit(ctx context.Context, q toolRequest) error {
335 s.mu.Lock()
336 defer s.mu.Unlock()
337 b := s.binding
338 if subtle.ConstantTimeCompare([]byte(q.Capability), []byte(s.capability.Secret)) != 1 || q.InstanceID != b.InstanceID || q.TaskID != b.TaskID || q.Attempt != b.Attempt || q.Fence != b.Fence || !slices.Contains(b.Tools, q.Name) || q.RequestID == "" || len(q.RequestID) > 256 {
339 return runnerproto.ErrInvalid
340 }
341 if s.pending {
342 if s.listener != nil {
343 s.invalidateLocked()
344 }
345 return runnerproto.ErrInvalid
346 }
347 if s.invalid || !time.Now().Before(b.LeaseDeadline) {
348 s.invalidateLocked()
349 return runnerproto.ErrInvalid
350 }
351 if err := s.current(ctx); err != nil {
352 return err
353 }
354
355 if err := validateToolArguments(q.Name, q.Arguments); err != nil {
356 return err
357 }
358 if err := b.Journal.AdmissionAllowed(ctx); err != nil {
359 s.invalidateLocked()
360 return err
361 }
362 if err := b.Journal.toolSlot(ctx, b, q.RequestID, q.Name, q.Arguments); err != nil {
363 return err
364 }
365 value := ToolSubmission{InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, RequestID: q.RequestID, Name: q.Name, Arguments: RedactJSON(q.Arguments, []string{s.capability.Secret}), Agent: b.Agent, Isolation: b.Isolation}
366 if err := b.Journal.appendTool(ctx, value, runnerproto.EventHash(json.RawMessage(q.Arguments))); err != nil {
367 return err
368 }
369 return nil
370}
371func readToolFrame(r *bufio.Reader) ([]byte, error) {
372 raw, err := r.ReadSlice('\n')
373 if err != nil || len(raw) > maxToolFrame {
374 return nil, runnerproto.ErrInvalid
375 }
376 return bytes.TrimSuffix(raw, []byte{'\n'}), nil
377}
378func callToolSocket(ctx context.Context, path string, q toolRequest) error {
379 conn, err := (&net.Dialer{Timeout: 2 * time.Second}).DialContext(ctx, "unix", path)
380 if err != nil {
381 return runnerproto.ErrInvalid
382 }
383 defer conn.Close()
384 _ = conn.SetDeadline(time.Now().Add(3 * time.Second))
385 raw, err := json.Marshal(q)
386 if err != nil || len(raw)+1 > maxToolFrame {
387 return runnerproto.ErrInvalid
388 }
389 if _, err = conn.Write(append(raw, '\n')); err != nil {
390 return runnerproto.ErrInvalid
391 }
392 raw, err = readToolFrame(bufio.NewReaderSize(conn, maxToolFrame+1))
393 if err != nil {
394 return err
395 }
396 var reply struct {
397 OK bool `json:"ok"`
398 }
399 if runnerproto.DecodeLimit(bytes.NewReader(raw), &reply, 1024) != nil || !reply.OK {
400 return runnerproto.ErrInvalid
401 }
402 return nil
403}
404
405// openNoLinks walks every component using directory-relative no-follow opens.
406func openNoLinks(path string, flags int) (*os.File, error) {
407 if !filepath.IsAbs(path) || filepath.Clean(path) != path {
408 return nil, runnerproto.ErrInvalid
409 }
410 fd, err := unix.Open("/", walkFlags|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
411 if err != nil {
412 return nil, runnerproto.ErrInvalid
413 }
414 parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
415 for i, p := range parts {
416 f := walkFlags | unix.O_DIRECTORY
417 if i == len(parts)-1 {
418 f = flags
419 }
420 next, e := unix.Openat(fd, p, f|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
421 unix.Close(fd)
422 if e != nil {
423 return nil, runnerproto.ErrInvalid
424 }
425 fd = next
426 }
427 return os.NewFile(uintptr(fd), path), nil
428}
429func privateInfo(f *os.File, mode os.FileMode, dir bool) bool {
430 var st unix.Stat_t
431 if unix.Fstat(int(f.Fd()), &st) != nil || !toolOwner(st.Uid) {
432 return false
433 }
434 info, err := f.Stat()
435 return err == nil && info.Mode().Perm() == mode && ((dir && info.IsDir()) || (!dir && info.Mode().IsRegular()))
436}
437func openPrivateDir(path string) (*os.File, error) {
438 f, err := openNoLinks(path, unix.O_RDONLY|unix.O_DIRECTORY)
439 if err != nil {
440 return nil, err
441 }
442 if !privateInfo(f, 0700, true) {
443 f.Close()
444 return nil, runnerproto.ErrInvalid
445 }
446 return f, nil
447}
448func readToolCapability(path string) (toolCapability, error) {
449 var cap toolCapability
450 f, err := openNoLinks(path, unix.O_RDONLY|unix.O_NONBLOCK)
451 if err != nil {
452 return cap, err
453 }
454 defer f.Close()
455 if !privateInfo(f, 0600, false) {
456 return cap, runnerproto.ErrInvalid
457 }
458 if runnerproto.DecodeLimit(io.LimitReader(f, 8193), &cap, 8192) != nil || len(cap.Secret) < 32 {
459 return toolCapability{}, runnerproto.ErrInvalid
460 }
461 return cap, nil
462}
463func (s *AttemptSocket) MCPConfig(executable string) (provider.MCPServer, error) {
464 if !filepath.IsAbs(executable) || filepath.Clean(executable) != executable {
465 return provider.MCPServer{}, runnerproto.ErrInvalid
466 }
467 return provider.MCPServer{Type: "stdio", Command: executable, Args: []string{"tool"}, Env: map[string]string{"EQUIPO_TOOL_SOCKET": s.SocketPath, "EQUIPO_TOOL_CAPABILITY_FILE": s.CapabilityPath, "EQUIPO_ATTEMPT": filepath.Base(filepath.Dir(s.SocketPath))}}, nil
468}
469
470func toolOwner(uid uint32) bool { return uid == uint32(os.Getuid()) }
471
472// NewPendingAttemptSocket reserves the MCP address before agent creation. No
473// request is accepted until the returned observed identity is bound.
474func NewPendingAttemptSocket(ctx context.Context, stateDir string, b ToolBinding) (*AttemptSocket, error) {
475 providerName := b.Agent.Provider
476 b.Agent.ServerID = "pending"
477 b.Agent.AgentID = "pending"
478 b.Agent.ProviderSessionID = "pending"
479 s, err := newAttemptSocket(ctx, stateDir, b, true)
480 if err != nil {
481 return nil, err
482 }
483 s.mu.Lock()
484 s.pending = true
485 s.binding.Agent = provider.Agent{Provider: providerName}
486 s.mu.Unlock()
487 return s, nil
488}
489func (s *AttemptSocket) BindAgent(a provider.Agent) error {
490 s.mu.Lock()
491 defer s.mu.Unlock()
492 if !s.pending || s.invalid || a.ServerID == "" || a.AgentID == "" || a.ProviderSessionID == "" || a.Provider != s.binding.Agent.Provider {
493 return provider.ErrIdentity
494 }
495 s.binding.Agent = a
496 s.pending = false
497 return nil
498}
499