ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-MCP/t/16_vim_auth.t
Revision: 1.8
Committed: Wed Oct 14 05:21:30 2026 UTC (7 weeks, 2 days ago) by root
Content type: application/x-troff
Branch: MAIN
Changes since 1.7: +55 -4 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 use common::sense;
2     use Test::More;
3     use JSON::XS ();
4     use IO::Socket::INET ();
5     use IO::Select ();
6     use Protocol::WebSocket::Frame ();
7     use IPC::Open3 ();
8     use POSIX qw(WNOHANG);
9     use Time::HiRes ();
10     use File::Temp ();
11     use File::Path ();
12     use Symbol ();
13    
14     my $dir = File::Temp::tempdir (CLEANUP => 1);
15     File::Path::mkpath (["$dir/home", "$dir/config"], 0, 0700);
16     local $ENV{HOME} = "$dir/home";
17     local $ENV{XDG_CONFIG_HOME} = "$dir/config";
18    
19     my $listener = IO::Socket::INET->new (
20     LocalAddr => "127.0.0.1", LocalPort => 0, Proto => "tcp", Listen => 1,
21     ) or die "allocate TCP test port: $!";
22     my $port = $listener->sockport;
23     close $listener;
24    
25     my $err = Symbol::gensym;
26 root 1.2 local $ENV{PERL_ANYEVENT_VERBOSE} = 6; # include notice-level rejection logs
27 root 1.1 my $pid = IPC::Open3::open3 (my $in, my $out, $err, $^X, "-Ilib",
28     "bin/mcp-vim", "--stdio", "--bind", "127.0.0.1:$port",
29     "--token", "primary", "--token", "secondary");
30     my $old = select $in;
31     $| = 1;
32     select $old;
33    
34     sub tcp {
35     IO::Socket::INET->new (
36     PeerAddr => "127.0.0.1", PeerPort => $port,
37     Proto => "tcp", Timeout => 1,
38     )
39     }
40    
41     my $ready;
42     for (1 .. 60) {
43     $ready = tcp ();
44     last if $ready;
45     Time::HiRes::sleep (0.03);
46     }
47     ok $ready, "mcp-vim listens on TCP with two static tokens";
48 root 1.7 # leave this connection silent while the other protocols are exercised.
49 root 1.1
50     sub rpc {
51     my ($id, $method, $params) = @_;
52     print {$in} JSON::XS::encode_json ({
53     jsonrpc => "2.0", id => $id, method => $method, params => $params,
54     }), "\n" or die "send JSONL request: $!";
55     IO::Select->new ($out)->can_read (3) or die "MCP stdio response timed out";
56     my $line = <$out> // die "unexpected MCP stdio EOF";
57     JSON::XS::decode_json $line
58     }
59    
60     sub target_names {
61     my $r = rpc (++$main::request_id, "tools/call",
62 root 1.3 { name => "targets", arguments => {} });
63 root 1.1 return [] unless $r->{result}{content}[0]{text};
64     JSON::XS::decode_json $r->{result}{content}[0]{text}
65     }
66    
67     sub vim_connect {
68     my ($token, $target) = @_;
69     my $sock = tcp () or die "connect private Vim TCP: $!";
70     my $hello = JSON::XS::encode_json ([0, [
71     "mcp-vim-connect", 1, 0, $token, $target, "test-$target",
72     ]]);
73     print {$sock} $hello or die "send private Vim hello: $!";
74     $sock
75     }
76    
77     sub upgrade {
78 root 1.2 my ($token, $path) = @_;
79 root 1.1 my $sock = tcp () or die "connect browser WS TCP: $!";
80     $sock->autoflush (1);
81 root 1.2 $path //= "/$token/http://page.example:818";
82     my $req = "GET $path HTTP/1.1\r\n"
83 root 1.1 . "Host: 127.0.0.1:$port\r\n"
84     . "Upgrade: websocket\r\nConnection: Upgrade\r\n"
85     . "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
86     . "Sec-WebSocket-Version: 13\r\n"
87     . "Origin: http://page.example:818\r\n\r\n";
88     print {$sock} $req or die "send WebSocket upgrade: $!";
89    
90     my $bytes = "";
91     my $deadline = Time::HiRes::time () + 2;
92     while ($bytes !~ /\r\n\r\n/ && Time::HiRes::time () < $deadline) {
93     last unless IO::Select->new ($sock)->can_read (0.2);
94     my $n = sysread $sock, my $chunk, 4096;
95     last unless $n;
96     $bytes .= $chunk;
97     }
98    
99     my ($headers, $frames) = split /\r\n\r\n/, $bytes, 2;
100     ($sock, $headers // "", $frames // "")
101     }
102    
103     sub ws_close_code {
104     my ($sock, $initial) = @_;
105     my $frame = Protocol::WebSocket::Frame->new;
106     $frame->append ($initial) if length $initial;
107     my $deadline = Time::HiRes::time () + 3;
108     while (Time::HiRes::time () < $deadline) {
109     while (defined (my $payload = $frame->next_bytes)) {
110     return unpack ("n", $payload) if $frame->opcode == 8 && length ($payload) >= 2;
111     }
112     next unless IO::Select->new ($sock)->can_read (0.2);
113     my $n = sysread $sock, my $bytes, 8192;
114     last unless $n;
115     $frame->append ($bytes);
116     }
117     undef
118     }
119    
120     my $init = rpc (1, "initialize", {
121     protocolVersion => "2025-11-25", capabilities => {},
122     clientInfo => { name => "auth-test", version => "0" },
123     });
124     ok !$init->{error} && $init->{result}{serverInfo},
125 root 1.7 "stdio control channel initializes while a TCP peer sends no first byte";
126 root 1.4 is $init->{result}{serverInfo}{name}, "mcp-vim", "stdio reports mcp-vim as its identity";
127     like $init->{result}{instructions}, qr/live Vim editors and buffers/,
128     "stdio gives MCP clients live-buffer guidance";
129     unlike JSON::XS::encode_json ($init->{result}), qr/xpcse/i,
130     "stdio initialization does not expose the legacy browser name";
131    
132     my $discover = rpc (2, "server/discover", {});
133     is $discover->{result}{instructions}, $init->{result}{instructions},
134     "discovery gives the same Vim instructions as initialize";
135    
136     {
137     my $http = tcp () or die "connect MCP HTTP: $!";
138     my $body = JSON::XS::encode_json ({
139     jsonrpc => "2.0", id => 3, method => "initialize",
140     params => {
141     protocolVersion => "2025-11-25", capabilities => {},
142     clientInfo => { name => "auth-test", version => "0" },
143     },
144     });
145     print {$http} "POST / HTTP/1.1\r\n",
146     "Host: 127.0.0.1:$port\r\n",
147     "Authorization: Bearer primary\r\n",
148     "Content-Type: application/json\r\n",
149     "Content-Length: ", length $body, "\r\n\r\n", $body
150     or die "send MCP HTTP request: $!";
151     local $/;
152     my $response = <$http> // "";
153     close $http;
154     my ($headers, $json) = split /\r\n\r\n/, $response, 2;
155     like $headers, qr{\AHTTP/1\.1 200\b}, "HTTP initialization succeeds";
156     my $result = eval { JSON::XS::decode_json $json };
157     is $result->{result}{serverInfo}{name}, "mcp-vim", "HTTP reports mcp-vim as its identity";
158     is $result->{result}{instructions}, $init->{result}{instructions},
159     "HTTP gives the same Vim instructions as stdio";
160     }
161 root 1.1
162 root 1.8 my $empty_state = rpc (4, "tools/call", { name => "state", arguments => {} });
163     is_deeply JSON::XS::decode_json ($empty_state->{result}{content}[0]{text}), {},
164     "state with no connected editors completes immediately with an empty object";
165    
166 root 1.1 my $bad = vim_connect ("unknown", "bad-vim");
167     my $before = target_names ();
168     ok !grep ($_ eq "bad-vim", @$before), "unknown private Vim token cannot register a target";
169     close $bad;
170    
171     my $valid = vim_connect ("secondary", "secondary-vim");
172     my $visible;
173     for (1 .. 35) {
174     my $names = target_names ();
175     $visible = grep $_ eq "secondary-vim", @$names;
176     last if $visible;
177     Time::HiRes::sleep (0.03);
178     }
179     ok $visible, "secondary token authenticates private Vim handshake";
180    
181 root 1.6 # A private Vim RPC supplying disjoint ranges must yield a separate
182     # [range=...] metadata text entry and an unchanged lines text entry for each.
183 root 1.5 print {$in} JSON::XS::encode_json ({
184     jsonrpc => "2.0", id => 180, method => "tools/call",
185     params => { name => "read-lines", arguments => {
186     target => "secondary-vim", buffer => 1, ranges => ["727,728", "985,986"],
187     } },
188     }), "\n" or die "send Vim read-lines request: $!";
189    
190     my $wire = "";
191     my $vim_call;
192     for (1 .. 15) {
193     IO::Select->new ($valid)->can_read (0.3)
194     or next;
195     my $n = sysread $valid, my $fragment, 8192;
196     last unless $n;
197     $wire .= $fragment;
198     $vim_call = eval { JSON::XS::decode_json $wire };
199     last if $vim_call;
200     }
201     ok $vim_call && $vim_call->[1][0] eq "call"
202     && $vim_call->[1][2] eq "read_lines",
203     "read-lines delegates disjoint ranges to the private Vim RPC";
204     if ($vim_call) {
205     $valid->autoflush (1);
206     print {$valid} JSON::XS::encode_json ([0, [
207     reply => $vim_call->[1][1], 1, {
208     changedtick => 7,
209     ranges => [
210     { range => "727,728", start => 727, end => 728, lines => ["function alpha () {", " return a;"] },
211     { range => "985,986", start => 985, end => 986, lines => ["function beta () {", " return b;"] },
212     ],
213     },
214     ]]) or die "send mock Vim RPC reply: $!";
215     }
216     IO::Select->new ($out)->can_read (5) or die "read-lines MCP reply timeout";
217     my $lines_reply = JSON::XS::decode_json (scalar <$out>);
218     my $blocks = $lines_reply->{result}{content} || [];
219 root 1.6 is @{$blocks}, 5, "Vim returns initial metadata plus two text entries per requested range";
220     is_deeply [map $_->{type}, @$blocks], [("text") x 5],
221     "all Vim metadata and source blocks remain MCP text entries";
222 root 1.5 is_deeply JSON::XS::decode_json ($blocks->[0]{text}), {
223     changedtick => 7,
224     ranges => [
225     { range => "727,728", start => 727, end => 728 },
226     { range => "985,986", start => 985, end => 986 },
227     ],
228     }, "Vim changedtick and resolved range metadata remain available";
229 root 1.6 is_deeply [map $_->{text}, @{$blocks}[1..4]], [
230     "[range=727,728]",
231     "function alpha () {\n return a;\n",
232     "[range=985,986]",
233     "function beta () {\n return b;\n",
234     ], "each Vim range has visible standalone metadata and unchanged newline-terminated source";
235 root 1.5
236    
237 root 1.7 sub send_tool {
238     my ($id, $name, $args) = @_;
239     print {$in} JSON::XS::encode_json ({
240     jsonrpc => "2.0", id => $id, method => "tools/call",
241     params => { name => $name, arguments => $args },
242     }), "\n" or die "send tool request: $!";
243     }
244    
245     sub vim_call {
246 root 1.8 my $socket = $_[0] || $valid;
247 root 1.7 my $wire = "";
248     for (1 .. 20) {
249 root 1.8 next unless IO::Select->new ($socket)->can_read (0.25);
250     my $n = sysread $socket, my $fragment, 8192;
251 root 1.7 last unless $n;
252     $wire .= $fragment;
253     my $packet = eval { JSON::XS::decode_json $wire };
254     return $packet if $packet;
255     }
256     die "private Vim RPC timeout\n";
257     }
258    
259     sub vim_reply {
260 root 1.8 my ($call, $success, $result, $socket) = @_;
261     $socket ||= $valid;
262     print {$socket} JSON::XS::encode_json ([0, [
263 root 1.7 reply => $call->[1][1], $success, $result,
264     ]]) or die "send Vim RPC reply: $!";
265     }
266    
267     sub mcp_reply {
268     IO::Select->new ($out)->can_read (5) or die "MCP reply timeout\n";
269     JSON::XS::decode_json (scalar <$out>)
270     }
271    
272 root 1.8 my $other = vim_connect ("secondary", "parallel-vim");
273     $other->autoflush (1);
274     my $other_visible;
275     for (1 .. 35) {
276     $other_visible = grep $_ eq "parallel-vim", @{target_names ()};
277     last if $other_visible;
278     Time::HiRes::sleep (0.03);
279     }
280     ok $other_visible, "second mock editor connected for parallel state collection";
281    
282     send_tool 181, "state", {};
283     my $first_state_call = vim_call;
284     my $second_state_call = vim_call $other;
285     is_deeply [$first_state_call->[1][2], $second_state_call->[1][2]], ["state", "state"],
286     "state sends both editor requests before waiting for either reply";
287     my $first_state = { cwd => "/first", buffers => [] };
288     my $second_state = { cwd => "/second", buffers => [] };
289     vim_reply $second_state_call, 1, $second_state, $other;
290     vim_reply $first_state_call, 1, $first_state;
291     my $states = mcp_reply;
292     is $states->{id}, 181, "parallel state completes the original request";
293     is_deeply JSON::XS::decode_json ($states->{result}{content}[0]{text}), {
294     "secondary-vim" => $first_state,
295     "parallel-vim" => $second_state,
296     }, "state collects both editor replies under their target names";
297    
298     send_tool 182, "state", {};
299     my $failed_state_call = vim_call;
300     my $late_state_call = vim_call $other;
301     vim_reply $failed_state_call, 0, "mock state error";
302     my $state_error = mcp_reply;
303     ok $state_error->{id} == 182 && $state_error->{result}{isError}
304     && $state_error->{result}{content}[0]{text} =~ /mock state error/,
305     "state fails without waiting for the other editor";
306     vim_reply $late_state_call, 1, $second_state, $other;
307    
308     send_tool 183, "state", { target => "secondary-vim" };
309     my $selected_state_call = vim_call;
310     vim_reply $selected_state_call, 1, $first_state;
311     my $selected_state = mcp_reply;
312     is $selected_state->{id}, 183, "late state reply does not complete a failed request again";
313     is_deeply JSON::XS::decode_json ($selected_state->{result}{content}[0]{text}),
314     { "secondary-vim" => $first_state }, "state can select one editor";
315     close $other;
316    
317 root 1.7 my $tool_id = 190;
318     for my $case (
319     ["grep", {
320     target => "secondary-vim", buffers => [1], pattern => "alpha",
321     mode => "word", max_results => 2,
322     }, "grep", [[1], "alpha", "word", 2]],
323     ["apply-diff", {
324     target => "secondary-vim", buffer => 1,
325     diff => "@@ -1 @@\n-old\n+new\n", expected_changedtick => 7,
326     }, "apply_patch", [1, "@@ -1,1 +1,1 @@\n-old\n+new\n", [0], 7]],
327     ["substitute", {
328     target => "secondary-vim", buffer => 1, range => "%",
329     pattern => "alpha", replacement => "beta", flags => "g",
330     expected_changedtick => 7,
331     }, "substitute", [1, "%", "alpha", "beta", "g", 7]],
332     ["set-cursor", {
333     target => "secondary-vim", buffer => 1, line => 2, column => 3,
334     expected_changedtick => 7,
335     }, "set_cursor", [1, 2, 3, 7]],
336     ["set-cursor", {
337     target => "secondary-vim", buffer => 1, line => 2, column => 3,
338     }, "set_cursor", [1, 2, 3]],
339     ) {
340     my ($name, $args, $command, $rpc_args) = @$case;
341     send_tool ++$tool_id, $name, $args;
342     my $call = vim_call;
343     is_deeply [@{$call->[1]}[2 .. $#{$call->[1]}]], [$command, @$rpc_args],
344     "$name forwards its arguments and guards through callback RPC";
345     my $result = { changedtick => 8, tool => $name };
346     vim_reply $call, 1, $result;
347     my $reply = mcp_reply;
348     is $reply->{id}, $tool_id, "$name completes the original MCP request";
349     is_deeply JSON::XS::decode_json ($reply->{result}{content}[0]{text}), $result,
350     "$name preserves the JSON tool result";
351     }
352    
353     my $grep_args = {
354     target => "secondary-vim", buffers => [1], pattern => "alpha",
355     mode => "word", max_results => 2,
356     };
357     send_tool 196, "grep", $grep_args;
358     my $failed_call = vim_call;
359     vim_reply $failed_call, 0, "mock Vim error";
360     my $failed_reply = mcp_reply;
361     ok $failed_reply->{id} == 196 && $failed_reply->{result}{isError}
362     && $failed_reply->{result}{content}[0]{text} =~ /mock Vim error/,
363     "failed Vim RPC becomes an MCP tool error";
364    
365     send_tool 197, "grep", $grep_args;
366     my $cancelled_call = vim_call;
367     print {$in} JSON::XS::encode_json ({
368     jsonrpc => "2.0", method => "notifications/cancelled",
369     params => { requestId => 197 },
370     }), "\n" or die "cancel tool request: $!";
371     is rpc (198, "ping", {})->{id}, 198, "cancellation processed before the late Vim reply";
372     send_tool 199, "grep", $grep_args;
373     my $next_call = vim_call;
374     vim_reply $cancelled_call, 1, { cancelled => 1 };
375     vim_reply $next_call, 1, { after_cancel => 1 };
376     my $after_cancel = mcp_reply;
377     ok $after_cancel->{id} == 199 && !$after_cancel->{result}{isError}
378     && JSON::XS::decode_json ($after_cancel->{result}{content}[0]{text})->{after_cancel},
379     "late cancelled reply is ignored and the next tool call completes";
380    
381 root 1.2 my ($invalid_ws, $invalid_headers) = upgrade ("secret-do-not-log-XYZ");
382 root 1.1 unlike $invalid_headers, qr{\AHTTP/1\.[01] 101\b},
383     "unknown WebSocket URL token does not upgrade";
384     close $invalid_ws;
385    
386 root 1.2 my ($malformed_ws, $malformed_headers) = upgrade ("secondary", "/secondary/");
387     unlike $malformed_headers, qr{\AHTTP/1\.[01] 101\b},
388     "malformed WebSocket URL rejected even when it contains a valid token";
389     close $malformed_ws;
390    
391 root 1.1 for my $kind (qw(xpcse-client ypcse-client)) {
392     my ($sock, $headers, $pending) = upgrade ("secondary");
393     like $headers, qr{\AHTTP/1\.1 101\b},
394     "secondary token authenticates $kind WebSocket handshake";
395     if ($headers =~ /\AHTTP\/1\.1 101\b/) {
396     my $payload = JSON::XS::encode_json ([$kind, 99]);
397     my $frame = Protocol::WebSocket::Frame->new (
398     type => "text", masked => 1, buffer => $payload,
399     );
400     print {$sock} $frame->to_bytes or die "send $kind mismatch: $!";
401     is ws_close_code ($sock, $pending), 1002,
402     "$kind version mismatch triggers protocol-error close";
403     } else {
404     fail "$kind version mismatch closes connection";
405     }
406     close $sock;
407     }
408    
409 root 1.7 send_tool 200, "grep", $grep_args;
410     my $disconnected_call = vim_call;
411 root 1.1 close $valid;
412 root 1.7 my $disconnected_reply = mcp_reply;
413     ok $disconnected_reply->{id} == 200 && $disconnected_reply->{result}{isError}
414     && $disconnected_reply->{result}{content}[0]{text} =~ /vim disconnected/,
415     "disconnect fails an outstanding callback RPC";
416     close $ready if $ready;
417 root 1.1 close $in;
418     my $exit;
419     for (1 .. 120) {
420     my $w = waitpid ($pid, WNOHANG);
421     if ($w == $pid) {
422     $exit = $? >> 8;
423     last;
424     }
425     Time::HiRes::sleep (0.025);
426     }
427     if (!defined $exit) {
428     kill TERM => $pid;
429     waitpid ($pid, 0);
430     $exit = -1;
431     }
432     is $exit, 0, "broker exits after stdio EOF";
433     close $out;
434 root 1.2 local $/;
435     my $log = <$err> // "";
436     like $log, qr/illegal websocket connect from 127\.0\.0\.1:\d+/,
437     "rejected websocket handshake logs the numeric TCP peer and port";
438     unlike $log, qr/secret-do-not-log-XYZ|\/secondary\//,
439     "rejected URL never exposes supplied credentials in the log";
440 root 1.1 close $err;
441    
442     done_testing;