ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/AnyEvent-MCP/t/16_vim_auth.t
Revision: 1.16
Committed: Thu Oct 15 01:26:06 2026 UTC (4 days, 13 hours ago) by root
Content type: application/x-troff
Branch: MAIN
Changes since 1.15: +145 -138 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 root 1.14 my $policy = "$dir/config/anyevent-mcp/rules/vim-default.ini";
20     File::Path::mkpath (["$dir/config/anyevent-mcp/rules"], 0, 0700);
21 root 1.12
22     sub permission_rules {
23     open my $fh, ">", $policy or die "$policy: $!";
24     chmod 0600, $policy or die "$policy: $!";
25     print {$fh} join "", map {
26     my ($decision, $action, $subject) = @$_;
27     "[rule]\ndecision=$decision\naction=$action\n"
28     . (defined $subject ? "subject=$subject\n" : "")
29     . ($decision eq "allow" ? "sandbox-grants=\n" : "") . "\n"
30     } @_;
31     close $fh or die "$policy: $!";
32     }
33    
34     permission_rules (["allow", "read"], ["allow", "write"]);
35    
36 root 1.1 my $listener = IO::Socket::INET->new (
37     LocalAddr => "127.0.0.1", LocalPort => 0, Proto => "tcp", Listen => 1,
38     ) or die "allocate TCP test port: $!";
39     my $port = $listener->sockport;
40     close $listener;
41    
42     my $err = Symbol::gensym;
43 root 1.2 local $ENV{PERL_ANYEVENT_VERBOSE} = 6; # include notice-level rejection logs
44 root 1.1 my $pid = IPC::Open3::open3 (my $in, my $out, $err, $^X, "-Ilib",
45 root 1.9 "-e", 'unshift @INC, sub { die "Coro must not be loaded\\n" if $_[1] =~ m{^Coro(?:/|\\.pm)}; return }; do shift @ARGV; die $@ if $@;',
46 root 1.14 "./bin/mcp-vim", "--name", "default", "--stdio", "--bind", "127.0.0.1:$port",
47 root 1.12 "--token", "primary", "--token", "secondary", "--ask", "mcp");
48 root 1.1 my $old = select $in;
49     $| = 1;
50     select $old;
51    
52     sub tcp {
53     IO::Socket::INET->new (
54     PeerAddr => "127.0.0.1", PeerPort => $port,
55     Proto => "tcp", Timeout => 1,
56     )
57     }
58    
59     my $ready;
60 root 1.16 for (1 .. 1000) {
61 root 1.1 $ready = tcp ();
62     last if $ready;
63     Time::HiRes::sleep (0.03);
64     }
65     ok $ready, "mcp-vim listens on TCP with two static tokens";
66 root 1.7 # leave this connection silent while the other protocols are exercised.
67 root 1.1
68     sub rpc {
69     my ($id, $method, $params) = @_;
70     print {$in} JSON::XS::encode_json ({
71     jsonrpc => "2.0", id => $id, method => $method, params => $params,
72     }), "\n" or die "send JSONL request: $!";
73 root 1.16 IO::Select->new ($out)->can_read (30) or die "MCP stdio response timed out";
74 root 1.1 my $line = <$out> // die "unexpected MCP stdio EOF";
75     JSON::XS::decode_json $line
76     }
77    
78     sub target_names {
79     my $r = rpc (++$main::request_id, "tools/call",
80 root 1.3 { name => "targets", arguments => {} });
81 root 1.1 return [] unless $r->{result}{content}[0]{text};
82     JSON::XS::decode_json $r->{result}{content}[0]{text}
83     }
84    
85     sub vim_connect {
86     my ($token, $target) = @_;
87     my $sock = tcp () or die "connect private Vim TCP: $!";
88     my $hello = JSON::XS::encode_json ([0, [
89     "mcp-vim-connect", 1, 0, $token, $target, "test-$target",
90     ]]);
91     print {$sock} $hello or die "send private Vim hello: $!";
92     $sock
93     }
94    
95     sub upgrade {
96 root 1.2 my ($token, $path) = @_;
97 root 1.1 my $sock = tcp () or die "connect browser WS TCP: $!";
98     $sock->autoflush (1);
99 root 1.2 $path //= "/$token/http://page.example:818";
100     my $req = "GET $path HTTP/1.1\r\n"
101 root 1.1 . "Host: 127.0.0.1:$port\r\n"
102     . "Upgrade: websocket\r\nConnection: Upgrade\r\n"
103     . "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
104     . "Sec-WebSocket-Version: 13\r\n"
105     . "Origin: http://page.example:818\r\n\r\n";
106     print {$sock} $req or die "send WebSocket upgrade: $!";
107    
108     my $bytes = "";
109     my $deadline = Time::HiRes::time () + 2;
110     while ($bytes !~ /\r\n\r\n/ && Time::HiRes::time () < $deadline) {
111     last unless IO::Select->new ($sock)->can_read (0.2);
112     my $n = sysread $sock, my $chunk, 4096;
113     last unless $n;
114     $bytes .= $chunk;
115     }
116    
117     my ($headers, $frames) = split /\r\n\r\n/, $bytes, 2;
118     ($sock, $headers // "", $frames // "")
119     }
120    
121     sub ws_close_code {
122     my ($sock, $initial) = @_;
123     my $frame = Protocol::WebSocket::Frame->new;
124     $frame->append ($initial) if length $initial;
125     my $deadline = Time::HiRes::time () + 3;
126     while (Time::HiRes::time () < $deadline) {
127     while (defined (my $payload = $frame->next_bytes)) {
128     return unpack ("n", $payload) if $frame->opcode == 8 && length ($payload) >= 2;
129     }
130     next unless IO::Select->new ($sock)->can_read (0.2);
131     my $n = sysread $sock, my $bytes, 8192;
132     last unless $n;
133     $frame->append ($bytes);
134     }
135     undef
136     }
137    
138     my $init = rpc (1, "initialize", {
139     protocolVersion => "2025-11-25", capabilities => {},
140     clientInfo => { name => "auth-test", version => "0" },
141     });
142     ok !$init->{error} && $init->{result}{serverInfo},
143 root 1.7 "stdio control channel initializes while a TCP peer sends no first byte";
144 root 1.4 is $init->{result}{serverInfo}{name}, "mcp-vim", "stdio reports mcp-vim as its identity";
145     like $init->{result}{instructions}, qr/live Vim editors and buffers/,
146     "stdio gives MCP clients live-buffer guidance";
147     unlike JSON::XS::encode_json ($init->{result}), qr/xpcse/i,
148     "stdio initialization does not expose the legacy browser name";
149    
150     my $discover = rpc (2, "server/discover", {});
151     is $discover->{result}{instructions}, $init->{result}{instructions},
152     "discovery gives the same Vim instructions as initialize";
153    
154     {
155     my $http = tcp () or die "connect MCP HTTP: $!";
156     my $body = JSON::XS::encode_json ({
157     jsonrpc => "2.0", id => 3, method => "initialize",
158     params => {
159     protocolVersion => "2025-11-25", capabilities => {},
160     clientInfo => { name => "auth-test", version => "0" },
161     },
162     });
163     print {$http} "POST / HTTP/1.1\r\n",
164     "Host: 127.0.0.1:$port\r\n",
165     "Authorization: Bearer primary\r\n",
166     "Content-Type: application/json\r\n",
167     "Content-Length: ", length $body, "\r\n\r\n", $body
168     or die "send MCP HTTP request: $!";
169     local $/;
170     my $response = <$http> // "";
171     close $http;
172     my ($headers, $json) = split /\r\n\r\n/, $response, 2;
173     like $headers, qr{\AHTTP/1\.1 200\b}, "HTTP initialization succeeds";
174     my $result = eval { JSON::XS::decode_json $json };
175     is $result->{result}{serverInfo}{name}, "mcp-vim", "HTTP reports mcp-vim as its identity";
176     is $result->{result}{instructions}, $init->{result}{instructions},
177     "HTTP gives the same Vim instructions as stdio";
178     }
179 root 1.1
180 root 1.8 my $empty_state = rpc (4, "tools/call", { name => "state", arguments => {} });
181     is_deeply JSON::XS::decode_json ($empty_state->{result}{content}[0]{text}), {},
182     "state with no connected editors completes immediately with an empty object";
183    
184 root 1.1 my $bad = vim_connect ("unknown", "bad-vim");
185     my $before = target_names ();
186     ok !grep ($_ eq "bad-vim", @$before), "unknown private Vim token cannot register a target";
187     close $bad;
188    
189     my $valid = vim_connect ("secondary", "secondary-vim");
190     my $visible;
191 root 1.16 for (1 .. 1000) {
192 root 1.1 my $names = target_names ();
193     $visible = grep $_ eq "secondary-vim", @$names;
194     last if $visible;
195     Time::HiRes::sleep (0.03);
196     }
197     ok $visible, "secondary token authenticates private Vim handshake";
198    
199 root 1.6 # A private Vim RPC supplying disjoint ranges must yield a separate
200     # [range=...] metadata text entry and an unchanged lines text entry for each.
201 root 1.5 print {$in} JSON::XS::encode_json ({
202     jsonrpc => "2.0", id => 180, method => "tools/call",
203     params => { name => "read-lines", arguments => {
204     target => "secondary-vim", buffer => 1, ranges => ["727,728", "985,986"],
205     } },
206     }), "\n" or die "send Vim read-lines request: $!";
207    
208     my $wire = "";
209     my $vim_call;
210 root 1.16 for (1 .. 100) {
211 root 1.5 IO::Select->new ($valid)->can_read (0.3)
212     or next;
213     my $n = sysread $valid, my $fragment, 8192;
214     last unless $n;
215     $wire .= $fragment;
216     $vim_call = eval { JSON::XS::decode_json $wire };
217     last if $vim_call;
218     }
219     ok $vim_call && $vim_call->[1][0] eq "call"
220     && $vim_call->[1][2] eq "read_lines",
221     "read-lines delegates disjoint ranges to the private Vim RPC";
222     if ($vim_call) {
223     $valid->autoflush (1);
224     print {$valid} JSON::XS::encode_json ([0, [
225     reply => $vim_call->[1][1], 1, {
226     changedtick => 7,
227     ranges => [
228     { range => "727,728", start => 727, end => 728, lines => ["function alpha () {", " return a;"] },
229     { range => "985,986", start => 985, end => 986, lines => ["function beta () {", " return b;"] },
230     ],
231     },
232     ]]) or die "send mock Vim RPC reply: $!";
233     }
234 root 1.16 IO::Select->new ($out)->can_read (30) or die "read-lines MCP reply timeout";
235 root 1.5 my $lines_reply = JSON::XS::decode_json (scalar <$out>);
236     my $blocks = $lines_reply->{result}{content} || [];
237 root 1.6 is @{$blocks}, 5, "Vim returns initial metadata plus two text entries per requested range";
238     is_deeply [map $_->{type}, @$blocks], [("text") x 5],
239     "all Vim metadata and source blocks remain MCP text entries";
240 root 1.5 is_deeply JSON::XS::decode_json ($blocks->[0]{text}), {
241     changedtick => 7,
242     ranges => [
243     { range => "727,728", start => 727, end => 728 },
244     { range => "985,986", start => 985, end => 986 },
245     ],
246     }, "Vim changedtick and resolved range metadata remain available";
247 root 1.6 is_deeply [map $_->{text}, @{$blocks}[1..4]], [
248     "[range=727,728]",
249     "function alpha () {\n return a;\n",
250     "[range=985,986]",
251     "function beta () {\n return b;\n",
252     ], "each Vim range has visible standalone metadata and unchanged newline-terminated source";
253 root 1.5
254    
255 root 1.7 sub send_tool {
256     my ($id, $name, $args) = @_;
257     print {$in} JSON::XS::encode_json ({
258     jsonrpc => "2.0", id => $id, method => "tools/call",
259     params => { name => $name, arguments => $args },
260     }), "\n" or die "send tool request: $!";
261     }
262    
263 root 1.9 my %vim_parser;
264    
265 root 1.7 sub vim_call {
266 root 1.8 my $socket = $_[0] || $valid;
267 root 1.9 my $parser = $vim_parser{fileno $socket} ||= JSON::XS->new->utf8;
268 root 1.16 for (1 .. 120) {
269 root 1.9 my $packet = $parser->incr_parse;
270     return $packet if $packet;
271 root 1.8 next unless IO::Select->new ($socket)->can_read (0.25);
272     my $n = sysread $socket, my $fragment, 8192;
273 root 1.7 last unless $n;
274 root 1.9 $parser->incr_parse ($fragment); # void context: leave complete packets for the next iteration
275 root 1.7 }
276 root 1.9 die "private Vim message timeout\n";
277 root 1.7 }
278    
279     sub vim_reply {
280 root 1.8 my ($call, $success, $result, $socket) = @_;
281     $socket ||= $valid;
282     print {$socket} JSON::XS::encode_json ([0, [
283 root 1.7 reply => $call->[1][1], $success, $result,
284     ]]) or die "send Vim RPC reply: $!";
285     }
286    
287     sub mcp_reply {
288 root 1.16 IO::Select->new ($out)->can_read (30) or die "MCP reply timeout\n";
289 root 1.7 JSON::XS::decode_json (scalar <$out>)
290     }
291    
292 root 1.8 my $other = vim_connect ("secondary", "parallel-vim");
293     $other->autoflush (1);
294     my $other_visible;
295 root 1.16 for (1 .. 1000) {
296 root 1.8 $other_visible = grep $_ eq "parallel-vim", @{target_names ()};
297     last if $other_visible;
298     Time::HiRes::sleep (0.03);
299     }
300     ok $other_visible, "second mock editor connected for parallel state collection";
301    
302 root 1.12 sub permission_params {
303     my ($name, $args, $state, $answer) = @_;
304     +{
305     name => $name, arguments => $args,
306     _meta => {
307     "io.modelcontextprotocol/protocolVersion" => "2026-07-28",
308     "io.modelcontextprotocol/clientCapabilities" => { elicitation => { form => {} } },
309     },
310     (defined $state ? (
311     requestState => $state, inputResponses => { permission => $answer },
312     ) : ()),
313     }
314     }
315    
316     # a saved grant for one editor must not authorize another, or start a partial fan-out.
317     permission_rules (["allow", "read", "targets"], ["allow", "read", "target:secondary-vim"]);
318     my $challenge = rpc (800, "tools/call", permission_params ("state", {}));
319     is $challenge->{result}{resultType}, "input_required", "another editor requires its own read permission";
320     ok !IO::Select->new ($valid, $other)->can_read (0.1), "state starts no RPC before all editor permissions pass";
321     my $declined = rpc (801, "tools/call", permission_params (
322     "state", {}, $challenge->{result}{requestState}, { action => "decline" },
323     ));
324     ok $declined->{result}{isError}, "declining an editor permission fails the state request";
325     ok !IO::Select->new ($valid, $other)->can_read (0.1), "declined state sends no editor RPC";
326    
327     $challenge = rpc (802, "tools/call", permission_params ("state", {}));
328     print {$in} JSON::XS::encode_json ({
329     jsonrpc => "2.0", id => 803, method => "tools/call",
330     params => permission_params ("state", {}, $challenge->{result}{requestState}, {
331     action => "accept", content => { decision => "allow-once" },
332     }),
333     }), "\n";
334     my $approved_first = vim_call;
335     my $approved_second = vim_call $other;
336     vim_reply $approved_first, 1, { approved => 1 };
337     vim_reply $approved_second, 1, { approved => 2 }, $other;
338     is mcp_reply ()->{id}, 803, "approved state dispatches both RPCs and completes the continuation";
339     $challenge = rpc (804, "tools/call", permission_params ("state", { target => "parallel-vim" }));
340     is $challenge->{result}{resultType}, "input_required", "one-time approval does not grant later editor reads";
341     rpc (805, "tools/call", permission_params (
342     "state", { target => "parallel-vim" }, $challenge->{result}{requestState}, { action => "decline" },
343     ));
344    
345 root 1.15 permission_rules (["allow", "read"]);
346     my $patch_args = {
347     target => "secondary-vim", buffer => 1,
348     diff => "@@ -1 @@\n-old\n+new\n", expected_changedtick => 7,
349     };
350     my $patch_challenge = rpc (806, "tools/call", permission_params ("apply-diff", $patch_args));
351    
352     is_deeply $patch_challenge->{result}{inputRequests}{permission}{params}{_meta}{"anyevent-mcp/permission"}{request}{details},
353     { "View patch" => "Editor: secondary-vim\nBuffer: 1\n\n$patch_args->{diff}" },
354     "Vim patch permission carries generic details with editor and buffer";
355     like $patch_challenge->{result}{inputRequests}{permission}{params}{message}, qr/-old\n\+new\n/,
356     "native Vim permission displays the patch";
357     ok !IO::Select->new ($valid)->can_read (0.1), "patch preview starts no editor RPC";
358     rpc (807, "tools/call", permission_params (
359     "apply-diff", $patch_args, $patch_challenge->{result}{requestState}, { action => "decline" },
360     ));
361     ok !IO::Select->new ($valid)->can_read (0.1), "declined patch starts no editor RPC";
362    
363 root 1.12 permission_rules (["allow", "read"], ["deny", "write"]);
364     for my $case (
365     ["apply-diff", { target => "secondary-vim", buffer => 1, diff => "@@ -1 @@\n-old\n+new\n", expected_changedtick => 7 }],
366     ["substitute", { target => "secondary-vim", buffer => 1, range => "%", pattern => "x", replacement => "y", flags => "", expected_changedtick => 7 }],
367     ["set-cursor", { target => "secondary-vim", buffer => 1, line => 1, column => 1 }],
368     ) {
369     my $reply = rpc (++$main::permission_id + 810, "tools/call", { name => $case->[0], arguments => $case->[1] });
370     ok $reply->{result}{isError}, "$case->[0] requires write permission despite an existing read grant";
371     ok !IO::Select->new ($valid)->can_read (0.1), "$case->[0] denial precedes Vim RPC";
372     }
373     permission_rules (["deny", "read"], ["allow", "write"]);
374     for my $case (
375     ["targets", {}],
376     ["state", { target => "secondary-vim" }],
377     ["read-lines", { target => "secondary-vim", buffer => 1, ranges => ["1"] }],
378     ["grep", { target => "secondary-vim", buffers => [1], pattern => "x", mode => "word", max_results => 1 }],
379     ) {
380     my $reply = rpc (++$main::permission_id + 810, "tools/call", { name => $case->[0], arguments => $case->[1] });
381     ok $reply->{result}{isError}, "$case->[0] requires read permission despite an existing write grant";
382     ok !IO::Select->new ($valid)->can_read (0.1), "$case->[0] denial precedes Vim RPC";
383     }
384     {
385     my $http = tcp () or die "connect permission HTTP test: $!";
386     $http->autoflush (1);
387     my $body = JSON::XS::encode_json ({
388     jsonrpc => "2.0", id => 840, method => "tools/call",
389     params => { name => "targets", arguments => {} },
390     });
391     print {$http} "POST / HTTP/1.1\r\nHost: localhost\r\n",
392     "Authorization: Bearer primary\r\nContent-Type: application/json\r\n",
393     "Content-Length: ", length $body, "\r\n\r\n", $body;
394 root 1.16 IO::Select->new ($http)->can_read (30) or die "HTTP permission response timed out\n";
395 root 1.12 local $/;
396     my $wire = <$http>;
397     close $http;
398     my (undef, $json) = split /\r\n\r\n/, $wire, 2;
399     my $reply = JSON::XS::decode_json $json;
400     ok $reply->{result}{isError}, "HTTP tool calls enforce the same read denial as stdio";
401     }
402     permission_rules (["allow", "read"], ["allow", "write"]);
403    
404     # read/write grants must not authorize unrestricted execution.
405     my $ex_args = { target => "secondary-vim", command => "echo 'hello' | echo 'world'\nlet g:example = 1" };
406     my $ex_challenge = rpc (850, "tools/call", permission_params ("ex", $ex_args));
407     is $ex_challenge->{result}{resultType}, "input_required", "read and write grants do not authorize exec";
408 root 1.13 like ($ex_challenge->{result}{inputRequests}{permission}{params}{message}, qr/\Q$ex_args->{command}\E/,
409     "exec permission prompt includes the complete command");
410 root 1.12 ok !IO::Select->new ($valid)->can_read (0.1), "exec waits for permission before sending Vim a command";
411     my $ex_denied = rpc (851, "tools/call", permission_params (
412     "ex", $ex_args, $ex_challenge->{result}{requestState}, { action => "decline" },
413     ));
414     ok $ex_denied->{result}{isError}, "declining exec does not execute the command";
415    
416     $ex_challenge = rpc (852, "tools/call", permission_params ("ex", $ex_args));
417     my $changed_ex = rpc (853, "tools/call", permission_params (
418     "ex", { %$ex_args, command => "echo 'different'" }, $ex_challenge->{result}{requestState},
419     { action => "accept", content => { decision => "allow-once" } },
420     ));
421     ok $changed_ex->{result}{isError}, "exec continuation cannot substitute another command";
422     ok !IO::Select->new ($valid)->can_read (0.1), "changed exec continuation sends no Vim RPC";
423    
424     $ex_challenge = rpc (854, "tools/call", permission_params ("ex", $ex_args));
425     print {$in} JSON::XS::encode_json ({
426     jsonrpc => "2.0", id => 855, method => "tools/call",
427     params => permission_params ("ex", $ex_args, $ex_challenge->{result}{requestState}, {
428     action => "accept", content => { decision => "allow-once" },
429     }),
430     }), "\n";
431     my $ex_call = vim_call;
432     is_deeply [@{$ex_call->[1]}[2, 3]], ["ex", $ex_args->{command}], "approved Ex text reaches Vim without filtering";
433     vim_reply $ex_call, 1, { output => "\nhello\nworld" };
434     my $ex_result = mcp_reply;
435     is_deeply JSON::XS::decode_json ($ex_result->{result}{content}[0]{text}), { output => "\nhello\nworld" },
436     "exec returns the captured Vim messages";
437     $ex_challenge = rpc (856, "tools/call", permission_params ("ex", $ex_args));
438     is $ex_challenge->{result}{resultType}, "input_required", "one-time exec permission does not authorize a later call";
439     rpc (857, "tools/call", permission_params (
440     "ex", $ex_args, $ex_challenge->{result}{requestState}, { action => "decline" },
441     ));
442    
443 root 1.13 $ex_challenge = rpc (861, "tools/call", permission_params ("ex", $ex_args));
444     my $ex_rule = rpc (862, "tools/call", permission_params (
445     "ex", $ex_args, $ex_challenge->{result}{requestState},
446     { action => "accept", content => { decision => "allow-always" } },
447     ));
448     my $ex_scopes = $ex_rule->{result}{inputRequests}{permission}{params}{requestedSchema}{properties}{subject}{enum};
449     is scalar @$ex_scopes, 3, "Ex offers exact command, editor-wide and global persistent scopes";
450     is $ex_scopes->[0], 'ex:"secondary-vim":' . JSON::XS->new->allow_nonref->encode ($ex_args->{command}),
451     "exact scope encodes the complete command including newlines";
452     print {$in} JSON::XS::encode_json ({
453     jsonrpc => "2.0", id => 863, method => "tools/call",
454     params => permission_params ("ex", $ex_args, $ex_rule->{result}{requestState}, {
455     action => "accept", content => {
456     decision => "allow-always", sandbox_grants => "", subject => $ex_scopes->[0],
457     },
458     }),
459     }), "\n";
460     $ex_call = vim_call;
461     vim_reply $ex_call, 1, { output => "" };
462     ok !mcp_reply ()->{result}{isError}, "exact-command persistent approval executes the approved call";
463     send_tool 864, "ex", { %$ex_args, buffer => 7, expected_changedtick => 42 };
464     $ex_call = vim_call;
465     is_deeply [@{$ex_call->[1]}[2 .. 5]], ["ex", $ex_args->{command}, 7, 42],
466     "exact approval survives buffer/tick changes and forwards both guards to Vim";
467     vim_reply $ex_call, 0, "rpc/stale_buffer: expected 42, got 43";
468     ok mcp_reply ()->{result}{isError}, "stale guarded Ex execution returns a tool error";
469     for my $args (
470     { %$ex_args, command => "$ex_args->{command} " },
471     { %$ex_args, command => "echo 'different'" },
472     { %$ex_args, target => "parallel-vim" },
473     ) {
474     my $id = ++$main::permission_id + 950;
475     my $challenge = rpc ($id, "tools/call", permission_params ("ex", $args));
476     is $challenge->{result}{resultType}, "input_required", "exact approval rejects changed command text or editor";
477     rpc ($id, "tools/call", permission_params (
478     "ex", $args, $challenge->{result}{requestState}, { action => "decline" },
479     ));
480     }
481     my $missing_buffer = rpc (865, "tools/call", permission_params (
482     "ex", { %$ex_args, expected_changedtick => 42 },
483     ));
484     ok $missing_buffer->{result}{isError}, "changedtick without a buffer is rejected";
485     ok !IO::Select->new ($valid, $other)->can_read (0.1), "unapproved and malformed Ex calls send no Vim RPC";
486    
487 root 1.12 permission_rules (["allow", "read"], ["allow", "write"], ["allow", "exec", "target:secondary-vim"]);
488 root 1.13 $ex_challenge = rpc (866, "tools/call", permission_params ("ex", $ex_args));
489     is $ex_challenge->{result}{resultType}, "input_required", "legacy literal target exec rule requires a fresh approval";
490     rpc (867, "tools/call", permission_params (
491     "ex", $ex_args, $ex_challenge->{result}{requestState}, { action => "decline" },
492     ));
493     permission_rules (["allow", "read"], ["allow", "write"], ["allow", "exec", $ex_scopes->[1]]);
494 root 1.12 send_tool 858, "ex", { target => "secondary-vim", command => "NoSuchExCommand" };
495     $ex_call = vim_call;
496     vim_reply $ex_call, 0, "Vim:E492: Not an editor command";
497     my $ex_error = mcp_reply;
498     ok $ex_error->{result}{isError} && $ex_error->{result}{content}[0]{text} =~ /E492/,
499     "Vim execution failure becomes a tool error";
500     $ex_challenge = rpc (859, "tools/call", permission_params ("ex", { %$ex_args, target => "parallel-vim" }));
501     is $ex_challenge->{result}{resultType}, "input_required", "saved exec permission remains scoped to its editor";
502     ok !IO::Select->new ($other)->can_read (0.1), "unapproved editor receives no exec RPC";
503     rpc (860, "tools/call", permission_params (
504     "ex", { %$ex_args, target => "parallel-vim" }, $ex_challenge->{result}{requestState}, { action => "decline" },
505     ));
506     for my $command ("", [], "echo\0bad") {
507     my $reply = rpc (++$main::permission_id + 900, "tools/call", {
508     name => "ex", arguments => { target => "secondary-vim", command => $command },
509     });
510     ok $reply->{result}{isError}, "malformed Ex command is rejected before RPC";
511     }
512     ok !IO::Select->new ($valid)->can_read (0.1), "invalid commands never reach Vim";
513     permission_rules (["allow", "read"], ["allow", "write"]);
514    
515 root 1.8 send_tool 181, "state", {};
516     my $first_state_call = vim_call;
517     my $second_state_call = vim_call $other;
518     is_deeply [$first_state_call->[1][2], $second_state_call->[1][2]], ["state", "state"],
519     "state sends both editor requests before waiting for either reply";
520     my $first_state = { cwd => "/first", buffers => [] };
521     my $second_state = { cwd => "/second", buffers => [] };
522     vim_reply $second_state_call, 1, $second_state, $other;
523     vim_reply $first_state_call, 1, $first_state;
524     my $states = mcp_reply;
525     is $states->{id}, 181, "parallel state completes the original request";
526     is_deeply JSON::XS::decode_json ($states->{result}{content}[0]{text}), {
527     "secondary-vim" => $first_state,
528     "parallel-vim" => $second_state,
529     }, "state collects both editor replies under their target names";
530    
531     send_tool 182, "state", {};
532     my $failed_state_call = vim_call;
533     my $late_state_call = vim_call $other;
534     vim_reply $failed_state_call, 0, "mock state error";
535     my $state_error = mcp_reply;
536     ok $state_error->{id} == 182 && $state_error->{result}{isError}
537     && $state_error->{result}{content}[0]{text} =~ /mock state error/,
538     "state fails without waiting for the other editor";
539     vim_reply $late_state_call, 1, $second_state, $other;
540    
541     send_tool 183, "state", { target => "secondary-vim" };
542     my $selected_state_call = vim_call;
543     vim_reply $selected_state_call, 1, $first_state;
544     my $selected_state = mcp_reply;
545     is $selected_state->{id}, 183, "late state reply does not complete a failed request again";
546     is_deeply JSON::XS::decode_json ($selected_state->{result}{content}[0]{text}),
547     { "secondary-vim" => $first_state }, "state can select one editor";
548     close $other;
549    
550 root 1.7 my $tool_id = 190;
551     for my $case (
552     ["grep", {
553     target => "secondary-vim", buffers => [1], pattern => "alpha",
554     mode => "word", max_results => 2,
555     }, "grep", [[1], "alpha", "word", 2]],
556     ["apply-diff", {
557     target => "secondary-vim", buffer => 1,
558     diff => "@@ -1 @@\n-old\n+new\n", expected_changedtick => 7,
559     }, "apply_patch", [1, "@@ -1,1 +1,1 @@\n-old\n+new\n", [0], 7]],
560     ["substitute", {
561     target => "secondary-vim", buffer => 1, range => "%",
562     pattern => "alpha", replacement => "beta", flags => "g",
563     expected_changedtick => 7,
564     }, "substitute", [1, "%", "alpha", "beta", "g", 7]],
565     ["set-cursor", {
566     target => "secondary-vim", buffer => 1, line => 2, column => 3,
567     expected_changedtick => 7,
568     }, "set_cursor", [1, 2, 3, 7]],
569     ["set-cursor", {
570     target => "secondary-vim", buffer => 1, line => 2, column => 3,
571     }, "set_cursor", [1, 2, 3]],
572     ) {
573     my ($name, $args, $command, $rpc_args) = @$case;
574     send_tool ++$tool_id, $name, $args;
575     my $call = vim_call;
576     is_deeply [@{$call->[1]}[2 .. $#{$call->[1]}]], [$command, @$rpc_args],
577     "$name forwards its arguments and guards through callback RPC";
578     my $result = { changedtick => 8, tool => $name };
579     vim_reply $call, 1, $result;
580     my $reply = mcp_reply;
581     is $reply->{id}, $tool_id, "$name completes the original MCP request";
582     is_deeply JSON::XS::decode_json ($reply->{result}{content}[0]{text}), $result,
583     "$name preserves the JSON tool result";
584     }
585    
586     my $grep_args = {
587     target => "secondary-vim", buffers => [1], pattern => "alpha",
588     mode => "word", max_results => 2,
589     };
590     send_tool 196, "grep", $grep_args;
591     my $failed_call = vim_call;
592     vim_reply $failed_call, 0, "mock Vim error";
593     my $failed_reply = mcp_reply;
594     ok $failed_reply->{id} == 196 && $failed_reply->{result}{isError}
595     && $failed_reply->{result}{content}[0]{text} =~ /mock Vim error/,
596     "failed Vim RPC becomes an MCP tool error";
597    
598     send_tool 197, "grep", $grep_args;
599     my $cancelled_call = vim_call;
600     print {$in} JSON::XS::encode_json ({
601     jsonrpc => "2.0", method => "notifications/cancelled",
602     params => { requestId => 197 },
603     }), "\n" or die "cancel tool request: $!";
604     is rpc (198, "ping", {})->{id}, 198, "cancellation processed before the late Vim reply";
605     send_tool 199, "grep", $grep_args;
606     my $next_call = vim_call;
607     vim_reply $cancelled_call, 1, { cancelled => 1 };
608     vim_reply $next_call, 1, { after_cancel => 1 };
609     my $after_cancel = mcp_reply;
610     ok $after_cancel->{id} == 199 && !$after_cancel->{result}{isError}
611     && JSON::XS::decode_json ($after_cancel->{result}{content}[0]{text})->{after_cancel},
612     "late cancelled reply is ignored and the next tool call completes";
613    
614 root 1.2 my ($invalid_ws, $invalid_headers) = upgrade ("secret-do-not-log-XYZ");
615 root 1.1 unlike $invalid_headers, qr{\AHTTP/1\.[01] 101\b},
616     "unknown WebSocket URL token does not upgrade";
617     close $invalid_ws;
618    
619 root 1.2 my ($malformed_ws, $malformed_headers) = upgrade ("secondary", "/secondary/");
620     unlike $malformed_headers, qr{\AHTTP/1\.[01] 101\b},
621     "malformed WebSocket URL rejected even when it contains a valid token";
622     close $malformed_ws;
623    
624 root 1.10 {
625 root 1.1 my ($sock, $headers, $pending) = upgrade ("secondary");
626     like $headers, qr{\AHTTP/1\.1 101\b},
627 root 1.10 "secondary token authenticates xpcse WebSocket handshake";
628 root 1.1 if ($headers =~ /\AHTTP\/1\.1 101\b/) {
629 root 1.10 my $payload = JSON::XS::encode_json (["xpcse-client", 99]);
630 root 1.1 my $frame = Protocol::WebSocket::Frame->new (
631     type => "text", masked => 1, buffer => $payload,
632     );
633 root 1.10 print {$sock} $frame->to_bytes or die "send xpcse mismatch: $!";
634 root 1.1 is ws_close_code ($sock, $pending), 1002,
635 root 1.10 "xpcse version mismatch triggers protocol-error close";
636 root 1.1 } else {
637 root 1.10 fail "xpcse version mismatch closes connection";
638 root 1.1 }
639     close $sock;
640     }
641    
642 root 1.16 subtest "browser transfers" => sub {
643     plan skip_all => "extended browser transfer tests (PERL_ANYEVENT_MCP_TESTS=1)"
644     unless ($ENV{PERL_ANYEVENT_MCP_TESTS} || 0) >= 1;
645    
646     # browser transfers use the same broker, with Coro unavailable.
647     sub browser {
648     my ($sock, $headers, $pending) = upgrade ("secondary");
649     $headers =~ /\AHTTP\/1\.1 101\b/ or die "browser upgrade failed\n";
650     my $frame = Protocol::WebSocket::Frame->new (max_payload_size => 100e6);
651     $frame->append ($pending);
652     my $browser = [$sock, $frame];
653     ws_message ($browser); # nick
654     ws_message ($browser); # targets
655     $browser
656     }
657 root 1.9
658 root 1.16 sub ws_message {
659     my ($browser, $timeout) = @_;
660     $timeout //= 30;
661     my ($socket, $frame) = @$browser;
662     my $deadline = Time::HiRes::time () + $timeout;
663     while (1) {
664     while (defined (my $payload = $frame->next_bytes)) {
665     next if $frame->opcode == 10;
666     return [$frame->opcode, $payload];
667     }
668     my $left = $deadline - Time::HiRes::time ();
669     return if $left <= 0 || !IO::Select->new ($socket)->can_read ($left);
670     my $n = sysread $socket, my $bytes, 65536;
671     return unless $n;
672     $frame->append ($bytes);
673 root 1.9 }
674     }
675    
676 root 1.16 sub browser_send {
677     my ($browser, $message) = @_;
678     print {$browser->[0]} Protocol::WebSocket::Frame->new (
679     type => "text", masked => 1, buffer => JSON::XS::encode_json ($message),
680     )->to_bytes or die "send browser message: $!";
681     }
682    
683     sub vim_send {
684     print {$valid} JSON::XS::encode_json ([0, $_[0]]) or die "send Vim message: $!";
685     }
686    
687     sub browser_json {
688     my $message = ws_message $_[0];
689     $message && $message->[0] == 1 or die "expected browser JSON\n";
690     JSON::XS::decode_json $message->[1]
691     }
692    
693     vim_send [session => "save-test", {
694     origin => "http://page.example:818", filename => "test.txt",
695     }];
696    
697     my $browser = browser ();
698     vim_send [save => "save-test"];
699     like vim_call ()->[1][1], qr/requesting save/, "save reports its destination";
700     is browser_json ($browser)->[0], "upload", "save starts a browser upload";
701    
702     require MIME::Base64;
703     my $data = "x" x (10e6 + 37);
704     vim_send [data => MIME::Base64::encode_base64 ($data, "")];
705    
706     my $message = ws_message $browser or die "oversized upload chunk stalled\n";
707     is $message->[0], 2, "upload frame is binary";
708     ok $message->[1] eq $data, "one oversized Vim chunk is forwarded whole";
709     ok !IO::Select->new ($valid)->can_read (0.1), "receiving Vim data does not acknowledge browser receipt";
710    
711     # further chunks wait while credit is negative; eof and a queued save may already arrive.
712     my @tail = ("first tail", "", "second tail");
713     vim_send [data => MIME::Base64::encode_base64 ($_, "")] for @tail;
714     vim_send [eof => 1];
715     vim_send [save => "save-test"];
716     like vim_call ()->[1][1], qr/requesting save/, "another save queues without acknowledging unsent data";
717     vim_send [eof => 1];
718     ok !ws_message ($browser, 0.1), "negative credit holds back the next whole chunk";
719    
720     browser_send $browser, [ack => length $data];
721     is_deeply vim_call ()->[1], [ack => length $data], "browser receipt is forwarded to the originating Vim after its eof";
722     for my $tail (@tail) {
723     my $message = ws_message $browser or die "upload did not resume after acknowledgement\n";
724     is_deeply $message, [2, $tail], "acknowledgement resumes output with the original chunk boundary";
725     }
726     is_deeply browser_json ($browser), ["upload-done"], "eof follows all input chunks";
727     ok !ws_message ($browser, 0.1), "next upload waits for the browser's completion reply";
728     for my $tail (@tail) {
729     browser_send $browser, [ack => length $tail];
730     is_deeply vim_call ()->[1], [ack => length $tail], "each browser chunk acknowledgement reaches Vim";
731     }
732     browser_send $browser, ["upload-done", "200", "saved first"];
733     is_deeply vim_call ()->[1], [echo => "200 saved first"], "save completion remains separate from chunk receipt";
734     is browser_json ($browser)->[0], "upload", "completion releases the queued save";
735     is_deeply browser_json ($browser), ["upload-done"], "empty save sends eof without waiting for credit";
736     browser_send $browser, ["upload-done", "500", "upload ok, but errors:\nat line 12, broken\n\n"];
737     is_deeply vim_call ()->[1], [error => "error: at line 12, broken"], "multiline upload error retains its diagnostic";
738     is_deeply vim_call ()->[1], [goto => "save-test", 12, 1], "upload error retains its session and line";
739    
740     vim_send [save => "save-test"];
741     vim_call ();
742     is browser_json ($browser)->[0], "upload", "another upload starts after an error reply";
743     vim_send [eof => 0];
744     my $aborted = ws_message $browser;
745     is $aborted->[0], 8, "failed Vim eof closes the active upload instead of posting a partial file";
746     is_deeply vim_call ()->[1], [echo => "save-test: browser disconnected"], "aborted upload releases its Vim input";
747     close $browser->[0];
748    
749     # rejected saves still consume their input and leave RPC dispatch usable.
750     vim_send [save => "save-test"];
751     like vim_call ()->[1][1], qr/no origin found/, "save without a browser explains how to reconnect";
752     vim_send [data => MIME::Base64::encode_base64 ("ignored", "")];
753     vim_send [eof => 1];
754     is_deeply vim_call ()->[1], [ack => 7], "rejected save consumes subsequent data";
755    
756     $browser = browser ();
757     vim_send [save => "save-test"];
758     vim_call ();
759     browser_json $browser;
760     close $browser->[0];
761     is_deeply vim_call ()->[1], [echo => "save-test: browser disconnected"], "browser disconnect releases an unfinished save";
762    
763     my $leaving = vim_connect ("secondary", "leaving-vim");
764     $leaving->autoflush (1);
765     for (1 .. 1000) {
766     last if grep $_ eq "leaving-vim", @{target_names ()};
767     Time::HiRes::sleep (0.03);
768     }
769     $browser = browser ();
770     print {$leaving} JSON::XS::encode_json ([0, [session => "leaving", {
771     origin => "http://page.example:818", filename => "leaving.txt",
772     }]]), JSON::XS::encode_json ([0, [save => "leaving"]]);
773     vim_call $leaving;
774     is browser_json ($browser)->[0], "upload", "disconnect test starts an unfinished upload";
775     close $leaving;
776     is ws_message ($browser)->[0], 8, "Vim disconnect aborts its unfinished browser upload";
777     close $browser->[0];
778    
779     done_testing;
780     };
781 root 1.9
782 root 1.7 send_tool 200, "grep", $grep_args;
783     my $disconnected_call = vim_call;
784 root 1.1 close $valid;
785 root 1.7 my $disconnected_reply = mcp_reply;
786     ok $disconnected_reply->{id} == 200 && $disconnected_reply->{result}{isError}
787     && $disconnected_reply->{result}{content}[0]{text} =~ /vim disconnected/,
788     "disconnect fails an outstanding callback RPC";
789     close $ready if $ready;
790 root 1.1 close $in;
791     my $exit;
792 root 1.16 for (1 .. 1200) {
793 root 1.1 my $w = waitpid ($pid, WNOHANG);
794     if ($w == $pid) {
795     $exit = $? >> 8;
796     last;
797     }
798     Time::HiRes::sleep (0.025);
799     }
800     if (!defined $exit) {
801     kill TERM => $pid;
802     waitpid ($pid, 0);
803     $exit = -1;
804     }
805     is $exit, 0, "broker exits after stdio EOF";
806     close $out;
807 root 1.2 local $/;
808     my $log = <$err> // "";
809     like $log, qr/illegal websocket connect from 127\.0\.0\.1:\d+/,
810     "rejected websocket handshake logs the numeric TCP peer and port";
811     unlike $log, qr/secret-do-not-log-XYZ|\/secondary\//,
812     "rejected URL never exposes supplied credentials in the log";
813 root 1.1 close $err;
814    
815     done_testing;