| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "net" |
| 7 | "strings" |
| 8 | "sync/atomic" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 13 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 14 | ) |
| 15 | |
| 16 | // Accelerate any idle deadline installed by the production reader. |
| 17 | type shortDeadlineConn struct{ net.Conn } |
| 18 | |
| 19 | func (c shortDeadlineConn) SetReadDeadline(d time.Time) error { |
| 20 | if !d.IsZero() { |
| 21 | d = time.Now().Add(20 * time.Millisecond) |
| 22 | } |
| 23 | return c.Conn.SetReadDeadline(d) |
| 24 | } |
| 25 | func TestToolProxyIdleConnection(t *testing.T) { |
| 26 | b := directToolFixture(t) |
| 27 | p, e := OpenToolProxy(context.Background(), b) |
| 28 | mustJournal(t, e) |
| 29 | defer p.Close() |
| 30 | server, client := net.Pipe() |
| 31 | defer client.Close() |
| 32 | done := make(chan error, 1) |
| 33 | go func() { |
| 34 | defer server.Close() |
| 35 | done <- serveTools(context.Background(), &proxyReader{conn: shortDeadlineConn{server}}, server, |
| 36 | func() (toolCapability, error) { return p.broker.capability, nil }, |
| 37 | func(q toolRequest) (any, error) { |
| 38 | return nil, p.submit(context.Background(), q.Name, q.RequestID, q.Arguments) |
| 39 | }, nil) |
| 40 | }() |
| 41 | defer func() { client.Close(); <-done }() |
| 42 | mustJournal(t, client.SetDeadline(time.Now().Add(2*time.Second))) |
| 43 | enc, dec := json.NewEncoder(client), json.NewDecoder(client) |
| 44 | rpc := func(raw string) { |
| 45 | t.Helper() |
| 46 | mustJournal(t, enc.Encode(json.RawMessage(raw))) |
| 47 | var reply mcpResponse |
| 48 | mustJournal(t, dec.Decode(&reply)) |
| 49 | if reply.Error != nil { |
| 50 | t.Fatal(reply.Error) |
| 51 | } |
| 52 | } |
| 53 | rpc(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{}}}`) |
| 54 | time.Sleep(80 * time.Millisecond) |
| 55 | rpc(`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"submit_candidate","arguments":{"request_id":"idle","commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}}`) |
| 56 | rows, e := b.Journal.ToolSubmissions(context.Background(), 10) |
| 57 | mustJournal(t, e) |
| 58 | if len(rows) != 1 { |
| 59 | t.Fatal("idle call not recorded", rows) |
| 60 | } |
| 61 | } |
| 62 | func TestToolProxyIdleAuthority(t *testing.T) { |
| 63 | b := directToolFixture(t) |
| 64 | var calls atomic.Int32 |
| 65 | b.Current = func(context.Context) error { calls.Add(1); return nil } |
| 66 | p, e := OpenToolProxy(context.Background(), b) |
| 67 | mustJournal(t, e) |
| 68 | defer p.Close() |
| 69 | before := calls.Load() |
| 70 | time.Sleep(350 * time.Millisecond) |
| 71 | if got := calls.Load() - before; got != 0 { |
| 72 | t.Fatalf("idle ticker made %d authority calls", got) |
| 73 | } |
| 74 | } |
| 75 | func TestToolProxyAuthorityLock(t *testing.T) { |
| 76 | for _, change := range []string{"unchanged", "invalidated", "turn", "session", "agent", "expired", "cancelled"} { |
| 77 | t.Run(change, func(t *testing.T) { |
| 78 | b := directToolFixture(t) |
| 79 | entered, release := make(chan struct{}), make(chan struct{}) |
| 80 | var calls atomic.Int32 |
| 81 | b.Current = func(context.Context) error { |
| 82 | if calls.Add(1) == 2 { |
| 83 | close(entered) |
| 84 | <-release |
| 85 | } |
| 86 | return nil |
| 87 | } |
| 88 | p, e := OpenToolProxy(context.Background(), b) |
| 89 | mustJournal(t, e) |
| 90 | defer p.Close() |
| 91 | done := make(chan error, 1) |
| 92 | ctx, cancel := context.WithCancel(context.Background()) |
| 93 | defer cancel() |
| 94 | go func() { |
| 95 | if change == "unchanged" { |
| 96 | done <- p.submit(ctx, "ask_person", "r", json.RawMessage(`{"question":"Which?"}`)) |
| 97 | return |
| 98 | } |
| 99 | p.broker.mu.Lock() |
| 100 | err := p.broker.authorityLocked(ctx) |
| 101 | p.broker.mu.Unlock() |
| 102 | done <- err |
| 103 | }() |
| 104 | defer func() { |
| 105 | close(release) |
| 106 | err := <-done |
| 107 | if change == "unchanged" && err != nil { |
| 108 | t.Error(err) |
| 109 | } |
| 110 | if change != "unchanged" && err == nil { |
| 111 | t.Error("changed binding accepted after authority check") |
| 112 | } |
| 113 | }() |
| 114 | select { |
| 115 | case <-entered: |
| 116 | case <-time.After(time.Second): |
| 117 | t.Fatal("authority did not start") |
| 118 | } |
| 119 | // A second tool call must acquire the lock even while the first waits remotely. |
| 120 | concurrent := make(chan error, 1) |
| 121 | go func() { concurrent <- p.submit(context.Background(), "publish", "bad", json.RawMessage(`{}`)) }() |
| 122 | select { |
| 123 | case err := <-concurrent: |
| 124 | if err == nil { |
| 125 | t.Fatal("unscoped tool accepted") |
| 126 | } |
| 127 | case <-time.After(300 * time.Millisecond): |
| 128 | t.Fatal("remote authority holds broker lock") |
| 129 | } |
| 130 | p.broker.mu.Lock() |
| 131 | switch change { |
| 132 | case "invalidated": |
| 133 | p.broker.invalidateLocked() |
| 134 | case "turn": |
| 135 | p.broker.binding.TurnID = "replacement" |
| 136 | case "session": |
| 137 | p.broker.binding.Session.ID = "replacement" |
| 138 | case "agent": |
| 139 | p.broker.binding.Agent.AgentID = "replacement" |
| 140 | case "cancelled": |
| 141 | cancel() |
| 142 | case "expired": |
| 143 | p.broker.binding.LeaseDeadline = time.Now().Add(-time.Second) |
| 144 | } |
| 145 | p.broker.mu.Unlock() |
| 146 | }) |
| 147 | } |
| 148 | } |
| 149 | func TestCodexApprovalResponseInvalidRelay(t *testing.T) { |
| 150 | for _, change := range []string{"fence", "attempt", "tool", "arguments", "stale", "stale-after-check", "revoked-after-check"} { |
| 151 | t.Run(change, func(t *testing.T) { |
| 152 | b := directToolFixture(t) |
| 153 | p, e := OpenToolProxy(context.Background(), b) |
| 154 | mustJournal(t, e) |
| 155 | defer p.Close() |
| 156 | relayBinding := b |
| 157 | tool, args := "submit_candidate", `{"request_id":"r","commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}` |
| 158 | switch change { |
| 159 | case "fence": |
| 160 | relayBinding.Fence++ |
| 161 | case "attempt": |
| 162 | relayBinding.Attempt++ |
| 163 | case "tool": |
| 164 | tool = "publish" |
| 165 | case "stale-after-check", "revoked-after-check": |
| 166 | var checks int |
| 167 | relayBinding.Current = func(ctx context.Context) error { |
| 168 | checks++ |
| 169 | if checks == 2 { |
| 170 | if change == "revoked-after-check" { |
| 171 | return runnerproto.ErrInvalid |
| 172 | } |
| 173 | return b.Journal.interruptDirect(ctx, b.Session.AttemptKey, false) |
| 174 | } |
| 175 | return nil |
| 176 | } |
| 177 | args = `{"request_id":"r","commit":"bad"}` |
| 178 | case "arguments": |
| 179 | args = `{"request_id":"r","commit":"bad"}` |
| 180 | case "stale": |
| 181 | mustJournal(t, b.Journal.interruptDirect(context.Background(), b.Session.AttemptKey, false)) |
| 182 | } |
| 183 | payload, _ := json.Marshal(map[string]any{"id": 7, "method": "mcpServer/elicitation/request", "params": map[string]any{"threadId": b.Session.ID, "turnId": "provider-turn", "tool": tool, "arguments": json.RawMessage(args)}}) |
| 184 | ev := pinnedRunnerMCP(provider.Event{Kind: "request", SessionID: b.Session.ID, TurnID: b.TurnID, RequestID: "7", Payload: payload}) |
| 185 | l := &directAnswerLauncher{} |
| 186 | r := DirectQuestionRelay{Binding: relayBinding, Proxy: p, Launcher: l} |
| 187 | err := r.Handle(context.Background(), ev, nil) |
| 188 | if strings.Contains(change, "after-check") || change == "stale" { |
| 189 | if err == nil || len(l.answers) != 0 { |
| 190 | t.Fatal("stale request answered") |
| 191 | } |
| 192 | return |
| 193 | } |
| 194 | if err != nil || len(l.answers) != 1 || l.answers[0].Behavior != "deny" || l.answers[0].RequestID != "7" { |
| 195 | t.Fatalf("invalid %s approval was not declined: %v %+v", change, err, l.answers) |
| 196 | } |
| 197 | }) |
| 198 | } |
| 199 | } |
| 200 | func TestClaudePermissionResponseToolUseIDRelay(t *testing.T) { |
| 201 | b := directToolFixture(t) |
| 202 | b.Session.Provider = "claude" |
| 203 | ev := provider.Event{Kind: "request", SessionID: b.Session.ID, TurnID: b.TurnID, RequestID: "permission:r", Payload: json.RawMessage(`{"tool_name":"Write","input":{"file_path":"/workspace/a","content":"hi"},"tool_use_id":"toolu_fixture"}`)} |
| 204 | q, e := DirectQuestionFromEvent(ev, b) |
| 205 | mustJournal(t, e) |
| 206 | if !strings.Contains(string(q.RawRequest), "toolu_fixture") { |
| 207 | t.Fatal("original request lost") |
| 208 | } |
| 209 | ev.Payload = json.RawMessage(`{"tool_name":"Write","input":{},"tool_use_id":"toolu_fixture","permissions":{}}`) |
| 210 | if _, e = DirectQuestionFromEvent(ev, b); e == nil { |
| 211 | t.Fatal("unknown permission field accepted") |
| 212 | } |
| 213 | } |
| 214 | func TestClaudePermissionResponseAdvertisedSchema(t *testing.T) { |
| 215 | var out strings.Builder |
| 216 | in := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}` + "\n" + `{"jsonrpc":"2.0","id":2,"method":"tools/list"}` + "\n" |
| 217 | e := serveTools(context.Background(), strings.NewReader(in), &out, func() (toolCapability, error) { return toolCapability{}, nil }, nil, func(context.Context, json.RawMessage) (json.RawMessage, error) { return nil, runnerproto.ErrInvalid }) |
| 218 | mustJournal(t, e) |
| 219 | var reply struct { |
| 220 | Result struct { |
| 221 | Tools []struct { |
| 222 | Name string |
| 223 | InputSchema struct { |
| 224 | Properties map[string]json.RawMessage |
| 225 | AdditionalProperties bool |
| 226 | } |
| 227 | } |
| 228 | } |
| 229 | } |
| 230 | mustJournal(t, json.Unmarshal([]byte(strings.Split(strings.TrimSpace(out.String()), "\n")[1]), &reply)) |
| 231 | for _, tool := range reply.Result.Tools { |
| 232 | if tool.Name == "permission" { |
| 233 | if string(tool.InputSchema.Properties["tool_use_id"]) != `{"type":"string"}` || len(tool.InputSchema.Properties) != 3 || tool.InputSchema.AdditionalProperties { |
| 234 | t.Fatal("permission schema differs from pinned input", tool) |
| 235 | } |
| 236 | return |
| 237 | } |
| 238 | } |
| 239 | t.Fatal("permission schema missing") |
| 240 | } |
| 241 | |