ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/AnyEvent-MCP/t/c16_vim_auth.t
Revision: 1.6
Committed: Sun Nov 29 14:30:05 2026 UTC (4 days, 8 hours ago) by root
Content type: application/x-troff
Branch: MAIN
CVS Tags: HEAD
Changes since 1.5: +39 -38 lines
Log Message:
*** empty log message ***

File Contents

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