package runner import ( "bufio" "context" "encoding/json" "io" "net" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) func toolFixture(t *testing.T) (*AttemptSocket, ToolBinding) { t.Helper() root, err := os.MkdirTemp(os.Getenv("TMPDIR"), "e13-") mustJournal(t, err) t.Cleanup(func() { os.RemoveAll(root) }) j, err := OpenJournal(context.Background(), filepath.Join(root, "journal", "events.db")) mustJournal(t, err) t.Cleanup(func() { j.Close() }) 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 }} s, err := NewAttemptSocket(context.Background(), root, b) mustJournal(t, err) t.Cleanup(func() { s.Cleanup(context.Background(), func(context.Context) error { return nil }) }) return s, b } func TestAgentToolScope(t *testing.T) { s, b := toolFixture(t) cap, err := readToolCapability(s.CapabilityPath) mustJournal(t, err) if cap.Copy.Acceptance != b.Copy.Acceptance || cap.Copy.Answer != b.Copy.Answer || cap.Copy.Render != b.Copy.Render { t.Fatal("plan tool copy lost in capability") } 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?"}`)} if err := callToolSocket(context.Background(), s.SocketPath, q); err != nil { t.Fatal(err) } if err := callToolSocket(context.Background(), s.SocketPath, q); err != nil { t.Fatal("exact replay", err) } rows, err := b.Journal.ToolSubmissions(context.Background(), 10) mustJournal(t, err) if len(rows) != 1 || rows[0].Agent.ProviderSessionID != "session" || !rows[0].Isolation.RunnerTainted { t.Fatal("missing durable scoped provenance", rows) } for _, field := range []string{"capability", "task", "instance", "attempt", "fence", "name", "payload", "injection", "request_id"} { t.Run(field, func(t *testing.T) { bad := q switch field { case "request_id": bad.RequestID = "" case "capability": bad.Capability = "wrong" case "task": bad.TaskID = "other" case "instance": bad.InstanceID = "other" case "attempt": bad.Attempt++ case "fence": bad.Fence++ case "name": bad.Name = "publish" case "payload": bad.Arguments = json.RawMessage(`{"question":"Changed"}`) case "injection": bad.RequestID = "new" bad.Arguments = json.RawMessage(`{"question":"hi","tools":["publish"]}`) } if callToolSocket(context.Background(), s.SocketPath, bad) == nil { t.Fatal("scope guard accepted", field) } }) } } func TestToolSocketIsolation(t *testing.T) { s, _ := toolFixture(t) for p, mode := range map[string]os.FileMode{filepath.Dir(s.SocketPath): 0700, s.SocketPath: 0600, s.CapabilityPath: 0600} { i, err := os.Stat(p) mustJournal(t, err) if i.Mode().Perm() != mode { t.Fatal("private mode", p, i.Mode()) } } link := filepath.Join(t.TempDir(), "link") mustJournal(t, os.Symlink(s.CapabilityPath, link)) if _, err := readToolCapability(link); err == nil { t.Fatal("symlink capability accepted") } mustJournal(t, os.Chmod(s.CapabilityPath, 0644)) if _, err := readToolCapability(s.CapabilityPath); err == nil { t.Fatal("public capability accepted") } mustJournal(t, os.Chmod(s.CapabilityPath, 0600)) if _, err := readToolCapability(s.CapabilityPath + "missing"); err == nil { t.Fatal("missing capability accepted") } if _, err := ServeAttemptSocket(context.Background(), "/"+strings.Repeat("x", 108), ToolBinding{}); err == nil { t.Fatal("long socket accepted") } cap, err := readToolCapability(s.CapabilityPath) mustJournal(t, err) s.Invalidate() if callToolSocket(context.Background(), s.SocketPath, toolRequest{Capability: cap.Secret}) == nil { t.Fatal("invalidated socket accepted") } } func TestToolSocketFramesAndLease(t *testing.T) { s, b := toolFixture(t) for _, raw := range []string{"{broken}\n", strings.Repeat("x", maxToolFrame+1) + "\n", `{"capability":"x","capability":"y"}` + "\n"} { c, err := net.Dial("unix", s.SocketPath) mustJournal(t, err) c.SetDeadline(time.Now().Add(3 * time.Second)) _, _ = c.Write([]byte(raw)) data, _ := io.ReadAll(c) c.Close() if strings.Contains(string(data), `"ok":true`) { t.Fatal("malformed frame accepted") } } cap, err := readToolCapability(s.CapabilityPath) mustJournal(t, err) 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?"}`)} for _, name := range []string{"read_task", "publish", "attest_checks", "set_budget", "admit", "settle", "submit_review"} { bad := q bad.Name = name if name == "submit_review" { bad.Arguments = json.RawMessage(`{"candidate":"` + strings.Repeat("a", 40) + `","decision":"approve","findings":[]}`) } if callToolSocket(context.Background(), s.SocketPath, bad) == nil { t.Fatal("unauthorized tool accepted", name) } } s.mu.Lock() s.binding.LeaseDeadline = time.Now().Add(-time.Second) s.mu.Unlock() if callToolSocket(context.Background(), s.SocketPath, q) == nil { t.Fatal("expired lease accepted") } s.mu.Lock() s.binding.LeaseDeadline = time.Now().Add(time.Minute) s.mu.Unlock() if callToolSocket(context.Background(), s.SocketPath, q) == nil { t.Fatal("expired capability revived") } } func TestToolSocketCurrentAuthority(t *testing.T) { s, b := toolFixture(t) cap, err := readToolCapability(s.CapabilityPath) mustJournal(t, err) 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?"}`)} s.mu.Lock() s.binding.Current = func(context.Context) error { return runnerproto.ErrInvalid } s.mu.Unlock() if callToolSocket(context.Background(), s.SocketPath, q) == nil { t.Fatal("changed fence authority accepted") } s.mu.Lock() s.binding.Current = func(context.Context) error { return nil } s.mu.Unlock() if callToolSocket(context.Background(), s.SocketPath, q) == nil { t.Fatal("old capability revived after authority change") } if err := s.Cleanup(context.Background(), func(context.Context) error { return runnerproto.ErrInvalid }); err == nil { t.Fatal("unproved containment cleaned files") } if _, err := os.Stat(s.CapabilityPath); err != nil { t.Fatal("removed before containment") } } func TestAgentToolJournalReopen(t *testing.T) { s, b := toolFixture(t) cap, err := readToolCapability(s.CapabilityPath) mustJournal(t, err) 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) + `"}`)} mustJournal(t, callToolSocket(context.Background(), s.SocketPath, q)) s.Invalidate() s.workers.Wait() mustJournal(t, b.Journal.Close()) j, err := OpenJournal(context.Background(), b.Journal.path) mustJournal(t, err) defer j.Close() rows, err := j.ToolSubmissions(context.Background(), 10) mustJournal(t, err) if len(rows) != 1 { t.Fatal("ACK before durable request") } mustJournal(t, j.AckTool(context.Background(), rows[0])) saved := rows[0] mustJournal(t, j.Close()) j, err = OpenJournal(context.Background(), b.Journal.path) mustJournal(t, err) defer j.Close() changed := saved changed.Arguments = json.RawMessage(`{"commit":"` + strings.Repeat("b", 40) + `"}`) if j.appendTool(context.Background(), changed, runnerproto.EventHash(changed.Arguments)) == nil { t.Fatal("changed replay accepted after ACK and reopen") } var effects int mustJournal(t, j.db.QueryRow("SELECT count(*) FROM journal_tools").Scan(&effects)) if effects != 1 { t.Fatal("changed replay duplicated effect") } mustJournal(t, j.appendTool(context.Background(), rows[0], runnerproto.EventHash(json.RawMessage(q.Arguments)))) rows, err = j.ToolSubmissions(context.Background(), 10) mustJournal(t, err) if len(rows) != 0 { t.Fatal("acked request replayed") } } func TestToolSocketReadPolicyAndOwnership(t *testing.T) { if !toolOwner(uint32(os.Getuid())) || toolOwner(uint32(os.Getuid()+1)) { t.Fatal("peer UID alone must not cross users") } s, b := toolFixture(t) b.Agent.Provider = "claude" b.Isolation.Status = "confined" root := filepath.Dir(filepath.Dir(filepath.Dir(s.SocketPath))) if _, err := NewAttemptSocket(context.Background(), root, b); err == nil { t.Fatal("Claude can read capability state") } b.ReadPolicy.DeniedPaths = []string{root} second, err := NewAttemptSocket(context.Background(), root, b) mustJournal(t, err) mustJournal(t, second.Cleanup(context.Background(), func(context.Context) error { return nil })) b.Agent.Provider = "codex" if _, err := NewAttemptSocket(context.Background(), root, b); err == nil { t.Fatal("false Codex confinement accepted") } } func TestToolSocketCannotRecreateAuthority(t *testing.T) { s, b := toolFixture(t) if _, err := ServeAttemptSocket(context.Background(), s.SocketPath, b); err == nil { t.Fatal("existing socket replaced") } link := filepath.Join(filepath.Dir(s.SocketPath), "link-dir") mustJournal(t, os.Symlink(filepath.Dir(s.CapabilityPath), link)) if _, err := readToolCapability(filepath.Join(link, filepath.Base(s.CapabilityPath))); err == nil { t.Fatal("symlink ancestor accepted") } mustJournal(t, os.Remove(link)) mustJournal(t, s.Cleanup(context.Background(), func(context.Context) error { return nil })) if _, err := os.Stat(s.CapabilityPath); !os.IsNotExist(err) { t.Fatal("capability remains after containment") } if callToolSocket(context.Background(), s.SocketPath, toolRequest{}) == nil { t.Fatal("removed socket accepted") } } func TestToolSocketFrameBoundary(t *testing.T) { raw := strings.Repeat(" ", maxToolFrame) + "\n" if _, err := readToolFrame(bufio.NewReaderSize(strings.NewReader(raw), len(raw)+1)); err == nil { t.Fatal("oversized frame boundary accepted") } } func TestToolSocketPublicStateAndStorageFailure(t *testing.T) { s, b := toolFixture(t) root := filepath.Dir(filepath.Dir(filepath.Dir(s.SocketPath))) mustJournal(t, os.Chmod(root, 0755)) if _, err := NewAttemptSocket(context.Background(), root, b); err == nil { t.Fatal("public state directory accepted") } mustJournal(t, os.Chmod(root, 0700)) cap, err := readToolCapability(s.CapabilityPath) mustJournal(t, err) b.Journal.maxBytes = 1 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?"}`)} if callToolSocket(context.Background(), s.SocketPath, q) == nil { t.Fatal("ACK on exhausted journal") } rows, err := b.Journal.ToolSubmissions(context.Background(), 10) mustJournal(t, err) if len(rows) != 0 { t.Fatal("overflow queued tool") } } func TestToolSocketStaleCapabilityFile(t *testing.T) { s, _ := toolFixture(t) cap, err := readToolCapability(s.CapabilityPath) mustJournal(t, err) cap.ExpiresAt = time.Now().Add(-time.Second) raw, _ := json.Marshal(cap) mustJournal(t, os.WriteFile(s.CapabilityPath, raw, 0600)) if _, err := readToolCapability(s.CapabilityPath); err != nil { t.Fatal("stale file expiry overrode trusted socket lease") } }