ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-MCP/t/c16_vim_auth.t
Revision: 1.2
Committed: Tue Nov 10 21:05:59 2026 UTC (2 weeks, 1 day ago) by root
Content type: application/x-troff
Branch: MAIN
CVS Tags: rel-0_91, HEAD
Changes since 1.1: +4 -0 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     my $have_websocket = eval {
15     require AnyEvent::WebSocket::Server;
16     require AnyEvent::WebSocket::Message;
17     require Protocol::WebSocket::Frame;
18     1
19     };
20     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     my $policy = "$dir/config/anyevent-mcp/rules/vim-default.ini";
25     File::Path::mkpath (["$dir/config/anyevent-mcp/rules"], 0, 0700);
26    
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 ? "match.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     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     local $ENV{PERL_ANYEVENT_LOG} = ""; # capture the broker's full activity log.
49     local $ENV{PERL_ANYEVENT_VERBOSE} = 6; # include notice-level rejection logs
50     my $pid = IPC::Open3::open3 (my $in, my $out, $err, $^X, "-Ilib",
51     "-e", 'unshift @INC, sub { die "Coro must not be loaded\\n" if $_[1] =~ m{^Coro(?:/|\\.pm)}; return }; do shift @ARGV; die $@ if $@;',
52     "./bin/mcp-vim", "--name", "default", "--stdio", "--bind", "127.0.0.1:$port",
53     "--token", "primary", "--token", "secondary", "--ask", "mcp");
54     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     for (1 .. 1000) {
67     $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     # leave this connection silent while the other protocols are exercised.
73    
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     IO::Select->new ($out)->can_read (30) or die "MCP stdio response timed out";
80     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     { name => "targets", arguments => {} });
87     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     my $hello = JSON::XS::encode_json ([
95     "mcp-vim", $token, 1, 0, $target, "test-$target",
96     ]) . "\n";
97     print {$sock} $hello or die "send private Vim hello: $!";
98     $sock
99     }
100    
101     sub upgrade {
102     my ($token, $path) = @_;
103     my $sock = tcp () or die "connect browser WS TCP: $!";
104     $sock->autoflush (1);
105     $path //= "/$token/http://page.example:818";
106     my $req = "GET $path HTTP/1.1\r\n"
107     . "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     "stdio control channel initializes while a TCP peer sends no first byte";
150     is $init->{result}{serverInfo}{name}, "mcp-vim", "stdio reports mcp-vim as its identity";
151     like $init->{result}{instructions}, qr/Live Vim buffers/,
152     "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    
186     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     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     for (1 .. 1000) {
198     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     # 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     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     for (1 .. 100) {
217     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     IO::Select->new ($out)->can_read (30) or die "read-lines MCP reply timeout";
241     my $lines_reply = JSON::XS::decode_json (scalar <$out>);
242     my $blocks = $lines_reply->{result}{content} || [];
243     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     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     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    
260    
261     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     my %vim_parser;
270    
271     sub vim_call {
272     my $socket = $_[0] || $valid;
273     my $parser = $vim_parser{fileno $socket} ||= JSON::XS->new->utf8;
274     for (1 .. 120) {
275     my $packet = $parser->incr_parse;
276     return $packet if $packet;
277     next unless IO::Select->new ($socket)->can_read (0.25);
278     my $n = sysread $socket, my $fragment, 8192;
279     last unless $n;
280     $parser->incr_parse ($fragment); # void context: leave complete packets for the next iteration
281     }
282     die "private Vim message timeout\n";
283     }
284    
285     sub vim_reply {
286     my ($call, $success, $result, $socket) = @_;
287     $socket ||= $valid;
288     print {$socket} JSON::XS::encode_json ([0, [
289     reply => $call->[1][1], $success, $result,
290     ]]) or die "send Vim RPC reply: $!";
291     }
292    
293     sub mcp_reply {
294     IO::Select->new ($out)->can_read (30) or die "MCP reply timeout\n";
295     JSON::XS::decode_json (scalar <$out>)
296     }
297    
298     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     my $other = vim_connect ("secondary", "parallel-vim");
315     $other->autoflush (1);
316     my $other_visible;
317     for (1 .. 1000) {
318     $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     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     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     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     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     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     ["undo", { target => "secondary-vim", buffer => 1, expected_changedtick => 7 }],
396     ["redo", { target => "secondary-vim", buffer => 1, expected_changedtick => 7 }],
397     ["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     IO::Select->new ($http)->can_read (30) or die "HTTP permission response timed out\n";
425     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     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.2 like $ex_challenge->{result}{inputRequests}{permission}{params}{_meta}{"anyevent-mcp/permission"}
441     {request}{dimensions}{subject}{choices}[0]{label},
442     qr/This command: echo 'hello' \| echo 'world' let g:example = 1/,
443     "exact Vim Ex scope displays the selected command in one line";
444 root 1.1 ok !IO::Select->new ($valid)->can_read (0.1), "exec waits for permission before sending Vim a command";
445     my $ex_denied = rpc (851, "tools/call", permission_params (
446     "ex", $ex_args, $ex_challenge->{result}{requestState}, { action => "decline" },
447     ));
448     ok $ex_denied->{result}{isError}, "declining exec does not execute the command";
449    
450     $ex_challenge = rpc (852, "tools/call", permission_params ("ex", $ex_args));
451     my $changed_ex = rpc (853, "tools/call", permission_params (
452     "ex", { %$ex_args, command => "echo 'different'" }, $ex_challenge->{result}{requestState},
453     { action => "accept", content => { decision => "allow-once" } },
454     ));
455     ok $changed_ex->{result}{isError}, "exec continuation cannot substitute another command";
456     ok !IO::Select->new ($valid)->can_read (0.1), "changed exec continuation sends no Vim RPC";
457    
458     $ex_challenge = rpc (854, "tools/call", permission_params ("ex", $ex_args));
459     print {$in} JSON::XS::encode_json ({
460     jsonrpc => "2.0", id => 855, method => "tools/call",
461     params => permission_params ("ex", $ex_args, $ex_challenge->{result}{requestState}, {
462     action => "accept", content => { decision => "allow-once" },
463     }),
464     }), "\n";
465     my $ex_call = vim_call;
466     is_deeply [@{$ex_call->[1]}[2, 3]], ["ex", $ex_args->{command}], "approved Ex text reaches Vim without filtering";
467     vim_reply $ex_call, 1, { output => "\nhello\nworld" };
468     my $ex_result = mcp_reply;
469     is_deeply JSON::XS::decode_json ($ex_result->{result}{content}[0]{text}), { output => "\nhello\nworld" },
470     "exec returns the captured Vim messages";
471     $ex_challenge = rpc (856, "tools/call", permission_params ("ex", $ex_args));
472     is $ex_challenge->{result}{resultType}, "input_required", "one-time exec permission does not authorize a later call";
473     rpc (857, "tools/call", permission_params (
474     "ex", $ex_args, $ex_challenge->{result}{requestState}, { action => "decline" },
475     ));
476    
477     $ex_challenge = rpc (861, "tools/call", permission_params ("ex", $ex_args));
478     my $ex_rule = rpc (862, "tools/call", permission_params (
479     "ex", $ex_args, $ex_challenge->{result}{requestState},
480     { action => "accept", content => { decision => "allow-always" } },
481     ));
482     my $ex_scopes = $ex_rule->{result}{inputRequests}{permission}{params}{requestedSchema}{properties}{dim_subject}{enum};
483     is scalar @$ex_scopes, 3, "Ex offers exact command, editor-wide and global persistent scopes";
484     is $ex_scopes->[0], 'ex:"secondary-vim":' . JSON::XS->new->allow_nonref->encode ($ex_args->{command}),
485     "exact scope encodes the complete command including newlines";
486     print {$in} JSON::XS::encode_json ({
487     jsonrpc => "2.0", id => 863, method => "tools/call",
488     params => permission_params ("ex", $ex_args, $ex_rule->{result}{requestState}, {
489     action => "accept", content => {
490     decision => "allow-always", sandbox_grants => "", dim_subject => $ex_scopes->[0],
491     },
492     }),
493     }), "\n";
494     $ex_call = vim_call;
495     vim_reply $ex_call, 1, { output => "" };
496     ok !mcp_reply ()->{result}{isError}, "exact-command persistent approval executes the approved call";
497     send_tool 864, "ex", { %$ex_args, buffer => 7, expected_changedtick => 42 };
498     $ex_call = vim_call;
499     is_deeply [@{$ex_call->[1]}[2 .. 5]], ["ex", $ex_args->{command}, 7, 42],
500     "exact approval survives buffer/tick changes and forwards both guards to Vim";
501     vim_reply $ex_call, 0, "rpc/stale_buffer: expected 42, got 43";
502     ok mcp_reply ()->{result}{isError}, "stale guarded Ex execution returns a tool error";
503     for my $args (
504     { %$ex_args, command => "$ex_args->{command} " },
505     { %$ex_args, command => "echo 'different'" },
506     { %$ex_args, target => "parallel-vim" },
507     ) {
508     my $id = ++$main::permission_id + 950;
509     my $challenge = rpc ($id, "tools/call", permission_params ("ex", $args));
510     is $challenge->{result}{resultType}, "input_required", "exact approval rejects changed command text or editor";
511     rpc ($id, "tools/call", permission_params (
512     "ex", $args, $challenge->{result}{requestState}, { action => "decline" },
513     ));
514     }
515     my $missing_buffer = rpc (865, "tools/call", permission_params (
516     "ex", { %$ex_args, expected_changedtick => 42 },
517     ));
518     ok $missing_buffer->{result}{isError}, "changedtick without a buffer is rejected";
519     ok !IO::Select->new ($valid, $other)->can_read (0.1), "unapproved and malformed Ex calls send no Vim RPC";
520    
521     permission_rules (["allow", "read"], ["allow", "write"], ["allow", "exec", "target:secondary-vim"]);
522     $ex_challenge = rpc (866, "tools/call", permission_params ("ex", $ex_args));
523     is $ex_challenge->{result}{resultType}, "input_required", "legacy literal target exec rule requires a fresh approval";
524     rpc (867, "tools/call", permission_params (
525     "ex", $ex_args, $ex_challenge->{result}{requestState}, { action => "decline" },
526     ));
527     permission_rules (["allow", "read"], ["allow", "write"], ["allow", "exec", $ex_scopes->[1]]);
528     send_tool 858, "ex", { target => "secondary-vim", command => "NoSuchExCommand" };
529     $ex_call = vim_call;
530     vim_reply $ex_call, 0, "Vim:E492: Not an editor command";
531     my $ex_error = mcp_reply;
532     ok $ex_error->{result}{isError} && $ex_error->{result}{content}[0]{text} =~ /E492/,
533     "Vim execution failure becomes a tool error";
534     $ex_challenge = rpc (859, "tools/call", permission_params ("ex", { %$ex_args, target => "parallel-vim" }));
535     is $ex_challenge->{result}{resultType}, "input_required", "saved exec permission remains scoped to its editor";
536     ok !IO::Select->new ($other)->can_read (0.1), "unapproved editor receives no exec RPC";
537     rpc (860, "tools/call", permission_params (
538     "ex", { %$ex_args, target => "parallel-vim" }, $ex_challenge->{result}{requestState}, { action => "decline" },
539     ));
540     for my $command ("", [], "echo\0bad") {
541     my $reply = rpc (++$main::permission_id + 900, "tools/call", {
542     name => "ex", arguments => { target => "secondary-vim", command => $command },
543     });
544     ok $reply->{result}{isError}, "malformed Ex command is rejected before RPC";
545     }
546     ok !IO::Select->new ($valid)->can_read (0.1), "invalid commands never reach Vim";
547     permission_rules (["allow", "read"], ["allow", "write"]);
548    
549     send_tool 181, "state", {};
550     my $first_state_call = vim_call;
551     my $second_state_call = vim_call $other;
552     is_deeply [$first_state_call->[1][2], $second_state_call->[1][2]], ["state", "state"],
553     "state sends both editor requests before waiting for either reply";
554     my $first_state = { cwd => "/first", buffers => [] };
555     my $second_state = { cwd => "/second", buffers => [] };
556     vim_reply $second_state_call, 1, $second_state, $other;
557     vim_reply $first_state_call, 1, $first_state;
558     my $states = mcp_reply;
559     is $states->{id}, 181, "parallel state completes the original request";
560     is_deeply JSON::XS::decode_json ($states->{result}{content}[0]{text}), {
561     "secondary-vim" => $first_state,
562     "parallel-vim" => $second_state,
563     }, "state collects both editor replies under their target names";
564    
565     send_tool 182, "state", {};
566     my $failed_state_call = vim_call;
567     my $late_state_call = vim_call $other;
568     vim_reply $failed_state_call, 0, "mock state error";
569     my $state_error = mcp_reply;
570     ok $state_error->{id} == 182 && $state_error->{result}{isError}
571     && $state_error->{result}{content}[0]{text} =~ /mock state error/,
572     "state fails without waiting for the other editor";
573     vim_reply $late_state_call, 1, $second_state, $other;
574    
575     send_tool 183, "state", { target => "secondary-vim" };
576     my $selected_state_call = vim_call;
577     vim_reply $selected_state_call, 1, $first_state;
578     my $selected_state = mcp_reply;
579     is $selected_state->{id}, 183, "late state reply does not complete a failed request again";
580     is_deeply JSON::XS::decode_json ($selected_state->{result}{content}[0]{text}),
581     { "secondary-vim" => $first_state }, "state can select one editor";
582     close $other;
583    
584     permission_rules (["allow", "read"], ["allow", "write"], ["allow", "save"]);
585     my $tool_id = 190;
586     for my $case (
587     ["grep", {
588     target => "secondary-vim", buffers => [1], pattern => "alpha",
589     mode => "word", max_results => 2,
590     }, "grep", [[1], "alpha", "word", 2]],
591     ["apply-diff", {
592     target => "secondary-vim", buffer => 1,
593     diff => "@@ -1 @@\n-old\n+new\n", expected_changedtick => 7,
594     }, "apply_patch", [1, "@@ -1,1 +1,1 @@\n-old\n+new\n", [0], 7]],
595     ["substitute", {
596     target => "secondary-vim", buffer => 1, range => "%",
597     pattern => "alpha", replacement => "beta", flags => "g",
598     expected_changedtick => 7,
599     }, "substitute", [1, "%", "alpha", "beta", "g", 7]],
600     ["undo", {
601     target => "secondary-vim", buffer => 1, expected_changedtick => 7,
602     }, "undo", [1, 7]],
603     ["redo", {
604     target => "secondary-vim", buffer => 1, expected_changedtick => 7,
605     }, "redo", [1, 7]],
606     ["save", {
607     target => "secondary-vim", buffer => 1, expected_changedtick => 7,
608     }, "update", [1, 7]],
609     ["set-cursor", {
610     target => "secondary-vim", buffer => 1, line => 2, column => 3,
611     expected_changedtick => 7,
612     }, "set_cursor", [1, 2, 3, 7]],
613     ["set-cursor", {
614     target => "secondary-vim", buffer => 1, line => 2, column => 3,
615     }, "set_cursor", [1, 2, 3]],
616     ) {
617     my ($name, $args, $command, $rpc_args) = @$case;
618     send_tool ++$tool_id, $name, $args;
619     my $call = vim_call;
620     is_deeply [@{$call->[1]}[2 .. $#{$call->[1]}]], [$command, @$rpc_args],
621     "$name forwards its arguments and guards through callback RPC";
622     is JSON::XS::encode_json ([$call->[1][3]]), "[1]", "apply-diff keeps buffer ID numeric"
623     if $name eq "apply-diff";
624     my $result = { changedtick => 8, tool => $name };
625     vim_reply $call, 1, $result;
626     my $reply = mcp_reply;
627     is $reply->{id}, $tool_id, "$name completes the original MCP request";
628     is_deeply JSON::XS::decode_json ($reply->{result}{content}[0]{text}), $result,
629     "$name preserves the JSON tool result";
630     }
631    
632     permission_rules (["allow", "read"], ["allow", "write"], ["allow", "exec"]);
633     my $save_args = { target => "secondary-vim", buffer => 1, expected_changedtick => 7 };
634     my $save_challenge = rpc (1050, "tools/call", permission_params ("save", $save_args));
635     is $save_challenge->{result}{resultType}, "input_required", "editing and exec grants do not imply save permission";
636     is $save_challenge->{result}{inputRequests}{permission}{params}{_meta}{"anyevent-mcp/permission"}{request}{action},
637     "save", "save uses the separate save action";
638     ok !IO::Select->new ($valid)->can_read (0.1), "unapproved save sends no Vim RPC";
639     my $save_denied = rpc (1051, "tools/call", permission_params (
640     "save", $save_args, $save_challenge->{result}{requestState}, { action => "decline" },
641     ));
642     ok $save_denied->{result}{isError}, "declining save denies save tool";
643     permission_rules (["allow", "read"], ["allow", "save"], ["deny", "write"]);
644     send_tool 1052, "save", $save_args;
645     my $save_call = vim_call;
646     is_deeply [@{$save_call->[1]}[2 .. $#{$save_call->[1]}]], ["update", 1, 7],
647     "save grant permits the save tool without edit permission";
648     vim_reply $save_call, 1, { buffer => 1, changedtick => 7, modified => 0, filename => "/saved" };
649     is mcp_reply ()->{id}, 1052, "save returns the update result";
650     permission_rules (["allow", "read"], ["allow", "write"]);
651    
652     permission_rules (["allow", "read"], ["allow", "write"], ["allow", "save"], ["allow", "exec"]);
653     my $open_args = { target => "secondary-vim", path => "/tmp/literal | % # [name]" };
654     my $open_challenge = rpc (1100, "tools/call", permission_params ("open", $open_args));
655     is $open_challenge->{result}{resultType}, "input_required", "read/edit/save/exec grants do not imply opening files";
656     my $open_request = $open_challenge->{result}{inputRequests}{permission}{params}{_meta}{"anyevent-mcp/permission"}{request};
657     is $open_request->{action}, "open", "opening files has a separate action";
658     like $open_request->{reason}, qr/\Q$open_args->{path}\E/, "open permission displays the requested pathname";
659     ok !IO::Select->new ($valid)->can_read (0.1), "unapproved open sends no Vim RPC";
660     my $open_denied = rpc (1101, "tools/call", permission_params (
661     "open", $open_args, $open_challenge->{result}{requestState}, { action => "decline" },
662     ));
663     ok $open_denied->{result}{isError}, "declining open stops the operation";
664     permission_rules (["allow", "open"], ["deny", "read"], ["deny", "write"]);
665     send_tool 1102, "open", $open_args;
666     my $open_call = vim_call;
667     is_deeply [@{$open_call->[1]}[2 .. $#{$open_call->[1]}]], ["open", $open_args->{path}],
668     "open forwards the literal pathname without requiring read/edit grants";
669     my $opened_buffer = { buffer => 4, filename => $open_args->{path}, changedtick => 2, line_count => 3, modified => 0 };
670     vim_reply $open_call, 1, $opened_buffer;
671     my $open_reply = mcp_reply;
672     is_deeply JSON::XS::decode_json ($open_reply->{result}{content}[0]{text}), $opened_buffer,
673     "open returns the loaded buffer identity and state";
674     for my $path ("", [], "bad\0path") {
675     my $reply = rpc (++$main::open_test_id + 1110, "tools/call",
676     { name => "open", arguments => { target => "secondary-vim", path => $path } });
677     ok $reply->{result}{isError}, "open rejects empty, non-text and NUL-containing paths";
678     ok !IO::Select->new ($valid)->can_read (0.1), "invalid open pathname never reaches Vim";
679     }
680     permission_rules (["allow", "read"], ["allow", "write"]);
681    
682     for my $operation (qw(undo redo save)) {
683     for my $args (
684     { target => "secondary-vim", buffer => 1 },
685     { target => "secondary-vim", buffer => 0, expected_changedtick => 7 },
686     { target => "secondary-vim", buffer => 1, expected_changedtick => -1 },
687     ) {
688     my $reply = rpc (++$main::undo_test_id + 1000, "tools/call",
689     { name => $operation, arguments => $args });
690     ok $reply->{result}{isError}, "$operation rejects an invalid buffer or missing/invalid tick";
691     ok !IO::Select->new ($valid)->can_read (0.1), "$operation validation precedes Vim RPC";
692     }
693     }
694    
695     my $grep_args = {
696     target => "secondary-vim", buffers => [1], pattern => "alpha",
697     mode => "word", max_results => 2,
698     };
699     send_tool 196, "grep", $grep_args;
700     my $failed_call = vim_call;
701     vim_reply $failed_call, 0, "mock Vim error";
702     my $failed_reply = mcp_reply;
703     ok $failed_reply->{id} == 196 && $failed_reply->{result}{isError}
704     && $failed_reply->{result}{content}[0]{text} =~ /mock Vim error/,
705     "failed Vim RPC becomes an MCP tool error";
706    
707     send_tool 197, "grep", $grep_args;
708     my $cancelled_call = vim_call;
709     print {$in} JSON::XS::encode_json ({
710     jsonrpc => "2.0", method => "notifications/cancelled",
711     params => { requestId => 197 },
712     }), "\n" or die "cancel tool request: $!";
713     is rpc (198, "ping", {})->{id}, 198, "cancellation processed before the late Vim reply";
714     send_tool 199, "grep", $grep_args;
715     my $next_call = vim_call;
716     vim_reply $cancelled_call, 1, { cancelled => 1 };
717     vim_reply $next_call, 1, { after_cancel => 1 };
718     my $after_cancel = mcp_reply;
719     ok $after_cancel->{id} == 199 && !$after_cancel->{result}{isError}
720     && JSON::XS::decode_json ($after_cancel->{result}{content}[0]{text})->{after_cancel},
721     "late cancelled reply is ignored and the next tool call completes";
722    
723     SKIP: {
724     skip "WebSocket modules not installed", 5 unless $have_websocket;
725     my ($invalid_ws, $invalid_headers) = upgrade ("secret-do-not-log-XYZ");
726     unlike $invalid_headers, qr{\AHTTP/1\.[01] 101\b},
727     "unknown WebSocket URL token does not upgrade";
728     close $invalid_ws;
729    
730     my ($malformed_ws, $malformed_headers) = upgrade ("secondary", "/secondary/");
731     unlike $malformed_headers, qr{\AHTTP/1\.[01] 101\b},
732     "malformed WebSocket URL rejected even when it contains a valid token";
733     close $malformed_ws;
734    
735     {
736     my ($sock, $headers, $pending) = upgrade ("secondary");
737     like $headers, qr{\AHTTP/1\.1 101\b},
738     "secondary token authenticates xpcse WebSocket handshake";
739     if ($headers =~ /\AHTTP\/1\.1 101\b/) {
740     my $payload = JSON::XS::encode_json (["xpcse-client", 99]);
741     my $frame = Protocol::WebSocket::Frame->new (
742     type => "text", masked => 1, buffer => $payload,
743     );
744     print {$sock} $frame->to_bytes or die "send xpcse mismatch: $!";
745     is ws_close_code ($sock, $pending), 1002,
746     "xpcse version mismatch triggers protocol-error close";
747     } else {
748     fail "xpcse version mismatch closes connection";
749     }
750     close $sock;
751     }
752    
753     subtest "browser transfers" => sub {
754     plan skip_all => "extended browser transfer tests (PERL_ANYEVENT_MCP_TESTS=1)"
755     unless ($ENV{PERL_ANYEVENT_MCP_TESTS} || 0) >= 1;
756    
757     # browser transfers use the same broker, with Coro unavailable.
758     sub browser {
759     my ($sock, $headers, $pending) = upgrade ("secondary");
760     $headers =~ /\AHTTP\/1\.1 101\b/ or die "browser upgrade failed\n";
761     my $frame = Protocol::WebSocket::Frame->new (max_payload_size => 100e6);
762     $frame->append ($pending);
763     my $browser = [$sock, $frame];
764     ws_message ($browser); # nick
765     ws_message ($browser); # targets
766     $browser
767     }
768    
769     sub ws_message {
770     my ($browser, $timeout) = @_;
771     $timeout //= 30;
772     my ($socket, $frame) = @$browser;
773     my $deadline = Time::HiRes::time () + $timeout;
774     while (1) {
775     while (defined (my $payload = $frame->next_bytes)) {
776     next if $frame->opcode == 10;
777     return [$frame->opcode, $payload];
778     }
779     my $left = $deadline - Time::HiRes::time ();
780     return if $left <= 0 || !IO::Select->new ($socket)->can_read ($left);
781     my $n = sysread $socket, my $bytes, 65536;
782     return unless $n;
783     $frame->append ($bytes);
784     }
785     }
786    
787     sub browser_send {
788     my ($browser, $message) = @_;
789     print {$browser->[0]} Protocol::WebSocket::Frame->new (
790     type => "text", masked => 1, buffer => JSON::XS::encode_json ($message),
791     )->to_bytes or die "send browser message: $!";
792     }
793    
794     sub vim_send {
795     print {$valid} JSON::XS::encode_json ([0, $_[0]]) or die "send Vim message: $!";
796     }
797    
798     sub browser_json {
799     my $message = ws_message $_[0];
800     $message && $message->[0] == 1 or die "expected browser JSON\n";
801     JSON::XS::decode_json $message->[1]
802     }
803    
804     vim_send [session => "save-test", {
805     origin => "http://page.example:818", filename => "test.txt",
806     etag => '"sha256-from-fetch"',
807     }];
808    
809     my $browser = browser ();
810     vim_send [save => "save-test"];
811     like vim_call ()->[1][1], qr/requesting save/, "save reports its destination";
812     my $upload = browser_json $browser;
813     is_deeply [$upload->[0], $upload->[2]], ["upload", 0], "legacy save starts an ordinary browser upload";
814     is $upload->[1]{etag}, '"sha256-from-fetch"', "fetch ETag survives Vim session and broker upload metadata";
815    
816     require MIME::Base64;
817     my $data = "x" x (10e6 + 37);
818     vim_send [data => MIME::Base64::encode_base64 ($data, "")];
819    
820     my $message = ws_message $browser or die "oversized upload chunk stalled\n";
821     is $message->[0], 2, "upload frame is binary";
822     ok $message->[1] eq $data, "one oversized Vim chunk is forwarded whole";
823     ok !IO::Select->new ($valid)->can_read (0.1), "receiving Vim data does not acknowledge browser receipt";
824    
825     # further chunks wait while credit is negative; eof and a queued save may already arrive.
826     my @tail = ("first tail", "", "second tail");
827     vim_send [data => MIME::Base64::encode_base64 ($_, "")] for @tail;
828     vim_send [eof => 1];
829     vim_send [save => "save-test", 1];
830     like vim_call ()->[1][1], qr/requesting save/, "another save queues without acknowledging unsent data";
831     vim_send [eof => 1];
832     ok !ws_message ($browser, 0.1), "negative credit holds back the next whole chunk";
833    
834     browser_send $browser, [ack => length $data];
835     is_deeply vim_call ()->[1], [ack => length $data], "browser receipt is forwarded to the originating Vim after its eof";
836     for my $tail (@tail) {
837     my $message = ws_message $browser or die "upload did not resume after acknowledgement\n";
838     is_deeply $message, [2, $tail], "acknowledgement resumes output with the original chunk boundary";
839     }
840     is_deeply browser_json ($browser), ["upload-done"], "eof follows all input chunks";
841     ok !ws_message ($browser, 0.1), "next upload waits for the browser's completion reply";
842     for my $tail (@tail) {
843     browser_send $browser, [ack => length $tail];
844     is_deeply vim_call ()->[1], [ack => length $tail], "each browser chunk acknowledgement reaches Vim";
845     }
846     my $new_etag = '"sha256:' . ("a" x 64) . '"';
847     browser_send $browser, ["upload-done", "200", "saved first", $new_etag];
848     is_deeply vim_call ()->[1], ["update-metadata", "save-test", { etag => $new_etag }],
849     "successful save updates Vim-owned session metadata";
850     is_deeply vim_call ()->[1], [echo => "200 saved first"], "save completion remains separate from chunk receipt";
851     $upload = browser_json $browser;
852     is_deeply [$upload->[0], $upload->[2]], ["upload", 1], "completion forwards the queued force flag";
853     is $upload->[1]{etag}, $new_etag, "queued save uses the refreshed ETag";
854     is_deeply browser_json ($browser), ["upload-done"], "empty save sends eof without waiting for credit";
855     browser_send $browser, ["upload-done", "500", "upload ok, but errors:\nat line 12, broken\n\n"];
856     is_deeply vim_call ()->[1], [error => "error: HTTP 500: at line 12, broken"], "multiline upload error retains its diagnostic";
857     is_deeply vim_call ()->[1], [goto => "save-test", 12, 1], "upload error retains its session and line";
858    
859     vim_send [save => "save-test"];
860     vim_call ();
861     $upload = browser_json $browser;
862     is $upload->[0], "upload", "another upload starts after an error reply";
863     is $upload->[1]{etag}, $new_etag, "failed upload leaves current ETag untouched";
864     vim_send [eof => 1];
865     is_deeply browser_json ($browser), ["upload-done"], "empty conditional save completes its input";
866     browser_send $browser, ["upload-done", "412", "save rejected: remote content changed since it was opened\n"];
867     is_deeply vim_call ()->[1], [error => "error: HTTP 412: save rejected: remote content changed since it was opened"],
868     "stale conditional save reports a conflict to Vim";
869    
870     vim_send [save => "save-test"];
871     vim_call ();
872     $upload = browser_json $browser;
873     is $upload->[1]{etag}, $new_etag, "conflict does not change Vim's ETag";
874     vim_send [eof => 0];
875     my $aborted = ws_message $browser;
876     is $aborted->[0], 8, "failed Vim eof closes the active upload instead of posting a partial file";
877     is_deeply vim_call ()->[1], [echo => "save-test: browser disconnected"], "aborted upload releases its Vim input";
878     close $browser->[0];
879    
880     # rejected saves still consume their input and leave RPC dispatch usable.
881     vim_send [save => "save-test"];
882     like vim_call ()->[1][1], qr/no origin found/, "save without a browser explains how to reconnect";
883     vim_send [data => MIME::Base64::encode_base64 ("ignored", "")];
884     vim_send [eof => 1];
885     is_deeply vim_call ()->[1], [ack => 7], "rejected save consumes subsequent data";
886    
887     $browser = browser ();
888     vim_send [save => "save-test"];
889     vim_call ();
890     browser_json $browser;
891     close $browser->[0];
892     is_deeply vim_call ()->[1], [echo => "save-test: browser disconnected"], "browser disconnect releases an unfinished save";
893    
894     my $leaving = vim_connect ("secondary", "leaving-vim");
895     $leaving->autoflush (1);
896     for (1 .. 1000) {
897     last if grep $_ eq "leaving-vim", @{target_names ()};
898     Time::HiRes::sleep (0.03);
899     }
900     $browser = browser ();
901     print {$leaving} JSON::XS::encode_json ([0, [session => "leaving", {
902     origin => "http://page.example:818", filename => "leaving.txt",
903     }]]), JSON::XS::encode_json ([0, [save => "leaving"]]);
904     vim_call $leaving;
905     is browser_json ($browser)->[0], "upload", "disconnect test starts an unfinished upload";
906     close $leaving;
907     is ws_message ($browser)->[0], 8, "Vim disconnect aborts its unfinished browser upload";
908     close $browser->[0];
909    
910     done_testing;
911     };
912     }
913    
914     send_tool 200, "grep", $grep_args;
915     my $disconnected_call = vim_call;
916     close $valid;
917     my $disconnected_reply = mcp_reply;
918     ok $disconnected_reply->{id} == 200 && $disconnected_reply->{result}{isError}
919     && $disconnected_reply->{result}{content}[0]{text} =~ /vim disconnected/,
920     "disconnect fails an outstanding callback RPC";
921     close $ready if $ready;
922     close $in;
923     my $exit;
924     for (1 .. 1200) {
925     my $w = waitpid ($pid, WNOHANG);
926     if ($w == $pid) {
927     $exit = $? >> 8;
928     last;
929     }
930     Time::HiRes::sleep (0.025);
931     }
932     if (!defined $exit) {
933     kill TERM => $pid;
934     waitpid ($pid, 0);
935     $exit = -1;
936     }
937     is $exit, 0, "broker exits after stdio EOF";
938     close $out;
939     local $/;
940     my $log = <$err> // "";
941     like $log, qr/vim <secondary-vim> connected/,
942     "authenticated editor registration is logged without debug mode";
943     like $log, qr/vim <secondary-vim> disconnected/,
944     "editor disconnect is logged without debug mode";
945     like $log, qr/ex target=secondary-vim command="echo 'hello' \| echo 'world'\\nlet g:example = 1"/,
946     "Ex call logs its command preview without requiring debug verbosity";
947     SKIP: {
948     skip "WebSocket modules not installed", 4 unless $have_websocket;
949     like $log, qr/Vim WebSocket rejected: invalid token \(127\.0\.0\.1:\d+\)/,
950     "wrong Vim WebSocket token produces one meaningful warning with peer";
951     like $log, qr/Vim WebSocket rejected: invalid path \(127\.0\.0\.1:\d+\)/,
952     "malformed Vim WebSocket path produces one meaningful warning with peer";
953     unlike $log, qr/secret-do-not-log-XYZ|\/secondary\//,
954     "rejected URL never exposes supplied credentials in the log";
955     unlike $log, qr/handshake response was undef/,
956     "rejected Vim WebSocket upgrade never reports an undef handshake response";
957     }
958     close $err;
959    
960     done_testing;