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