bin/mcp-fs

filter: Statementstmt 88.1% 973 / 1104 Branchbran 68.4% 508 / 742 Conditioncond 56.2% 253 / 450 MC/DCmcdc 27.3% 68 / 249 Subroutinesub 86.8% 99 / 114 Podpod n/a totaltotal 71.4% 1901 / 2659 CC 455 SCAR 30.7
CC
455
Cov
76%
__ANON__
72.0
fs_sandbox
65.9
__ANON__
44.4
CRAP 21.6
« lib/AnyEvent/MCP/IMAP/OAuth2.pm ↑ Summary blib/lib/AnyEvent/MCP/Server/HTTP.pm »
1 #!/opt/bin/perl
2  
3 =head1 NAME
4  
5 mcp-fs - filesystem and command tools with optional sandboxing
6  
7 =head1 SYNOPSIS
8  
9 mcp-fs --stdio /path/to/workdir
10 mcp-fs --name project --bind 127.0.0.1:31741 /path/to/workdir
11 mcp-fs --stdio --host kaos --rsh rsh /root/src
12  
13 =head1 DESCRIPTION
14  
15 C<mcp-fs> gives an MCP client tools to read, search and change files, and
16 run commands. An assistant can use these tools to work on your projects
17 without you writing a Perl server.
18  
19 Start it with one or more project directories, called workdirs. The client
20 connects to the server, lists its tools and makes requests. A request can
21 select one of these workdirs; with only one, the selection can be omitted.
22 Tools operate on files on disk. To work with unsaved Vim buffers, use
23 L<mcp-vim>.
24  
25 Before starting an operation, the server checks permission rules and, when
26 needed, asks you for approval. Operations normally run in a bubblewrap
27 sandbox with the approved access. Workdirs provide the default filesystem
28 scope; operations needing access elsewhere require the corresponding
29 sandbox grants.
30  
31 You can connect an MCP client directly over HTTP or stdin/stdout, or run
32 the server through C<mcp-multibroker>. See L<AnyEvent::MCP::Intro> for a
33 walkthrough from installation to a first filesystem request.
34  
35 With C<--host>, the same tools operate on a remote host over SSH (or the
36 command selected by C<--rsh>). Only Perl 5.8.4 and the tools used by the
37 requested operations are needed remotely; neither mcp-fs nor its CPAN
38 modules must be installed there. Each server instance uses one host, with
39 any number of workdirs on that host.
40  
41 =head1 FIRST USE
42  
43 Configure your MCP client to launch the server with an existing project:
44  
45 mcp-fs --stdio --name project /home/alice/src/project
46  
47 The client starts the process and speaks MCP over stdin/stdout. Do not run
48 another copy in a terminal. For HTTP clients, run without C<--stdio> and
49 use C<--print-url> with the same C<--name> and C<--bind> settings; see
50 L<AnyEvent::MCP::Intro/YOUR FIRST FILESYSTEM SERVER>.
51  
52 To inspect the tools available with your installed utilities without
53 starting a listener, run C<mcp-fs --tool-help /home/alice/src/project>.
54  
55 Once connected, ask the assistant:
56  
57 Show the configured workdirs and list my project's top-level files.
58 Read its README if present. Do not change files or run commands.
59  
60 C<workdirs> shows the available paths without a worker. Listing requests
61 C<inspect> permission, and reading a file requests C<read>. Allow each once
62 to try them. Approval is specific to the requested action and sandbox grants.
63 If no dialog appears, inspect the tool error and server stderr: the helper
64 needs a YAD display or usable terminal. See L</PERMISSIONS>.
65  
66 For a separate sandbox check without MCP, change to your project directory
67 and run:
68  
69 mcp-fs --exec-cmd workdir-read -- ls
70  
71 This uses the current directory as the workdir. It tests the sandbox,
72 not client connectivity or permission prompting.
73  
74 =head2 Remote workdirs
75  
76 To use an existing directory on another machine:
77  
78 mcp-fs --stdio --host server.example.org /srv/project
79 mcp-fs --stdio -h kaos -e rsh /root/src /srv/projects
80  
81 Workdir arguments are ordinary absolute paths on that host, without a
82 C<host:> prefix. Omitting C<--host> retains local operation, regardless of
83 C<--rsh>. The remote shell is started locally, outside the operation
84 sandbox. Its connection does not require the remote operation's C<network>
85 grant. Combine unrelated hosts through C<mcp-multibroker>.
86  
87 Remote request cancellation and timeouts terminate the local remote-shell
88 process, but may leave the remote worker running. After a connection failure,
89 the outcome of a modifying operation may be unknown; inspect the remote
90 filesystem before retrying it. Reliable remote process termination is not
91 yet implemented.
92  
93 =head1 TOOLS
94  
95 The filesystem tools are:
96  
97 =over
98  
99 =item C<workdirs>
100  
101 Report configured workdirs and available sandbox grants, without starting a worker.
102  
103 =item C<list>, C<find>
104  
105 Enumerate directory entries.
106  
107 =item C<stat>
108  
109 Return lstat metadata without following symlinks.
110  
111 =item C<file-read>
112  
113 Read byte ranges and return Base64 data.
114  
115 =item C<read-lines>
116  
117 Read LF-delimited lines with selectable UTF-8, Latin-1 or Base64 representation.
118  
119 =item C<grep>
120  
121 Search files using a literal pattern or PCRE.
122  
123 =item C<file-write>
124  
125 Write Base64 bytes at an offset without implicit truncation.
126  
127 =item C<path-op>
128  
129 Perform pathname mutations.
130  
131 =item C<file-patch>
132  
133 Apply a unified diff to a single file.
134  
135 =item C<exec>
136  
137 Run an argv array, not a shell command string. To use shell syntax,
138 explicitly invoke a shell in that array.
139  
140 =back
141  
142 For C<exec>, C<stdin_encoding> selects C<utf-8> (default), C<latin1>
143 or C<base64>. The 4 MiB limit applies to the resulting stdin bytes.
144 Stdout and stderr are decoded as UTF-8, with a raw capture limit of
145 1 MiB per stream; use the byte-range tools for binary file contents.
146 Its optional C<sandbox_grants> B<replaces> the default C<workdir-read>
147 grant rather than adding to it. Explicitly passing an empty array
148 therefore asks for no grants. Command exit codes are normal tool results,
149 not transport errors. On timeout, output collection stops and
150 C<truncated> is true; C<exit> and C<signal> still describe the reaped child.
151  
152 Perl is required for normal server operation; missing optional GNU utilities
153 can cause their tools to be omitted. The command requested by C<exec>
154 is resolved when the worker runs; it need not be present when the server
155 starts. Inspect C<tools/list> rather than assuming every tool is present.
156  
157 =head2 Command output
158  
159 C<exec>, C<vcs-diff>, C<vcs-status> and C<vcs-log> share three presentation options:
160  
161 =over
162  
163 =item grep => $pattern
164  
165 Optional PCRE line filter for stdout. It runs in a separate timed GNU grep
166 worker after command output has been captured. It is not passed to the
167 original command or a shell. Stderr remains unfiltered.
168  
169 =item max_lines => $integer
170  
171 Maximum returned stdout lines after filtering, default 2000, maximum 100000.
172  
173 =item max_bytes => $integer
174  
175 Maximum returned UTF-8 bytes per stream, default 65536, maximum 1048576.
176 Clipping does not leave an incomplete UTF-8 character. Stderr has its own
177 budget, so a large stdout does not hide diagnostics.
178  
179 =back
180  
181 The command runs once and is drained to completion, subject to its timeout.
182 Raw capture is bounded to 1 MiB per stream, independently of the returned
183 output limits. C<capture_truncated> means bytes were omitted before filtering
184 or collection ended on timeout: matches in that omitted output are unknown.
185 C<stdout_truncated>, C<stderr_truncated> and the combined C<truncated> flag
186 also account for returned-output limits.
187  
188 Changing presentation options does not change the command's permission
189 subject. C<exit>, C<signal> and C<timed_out> always describe the original
190 command, including a diff exit code indicating differences. A filter error
191 makes the tool result an error and adds C<filter_error>, while retaining that
192 command status. The command may already have completed; do not rerun it
193 merely because its output filter failed.
194  
195 =head2 Version control
196  
197 C<vcs-diff>, C<vcs-status> and C<vcs-log> take a required C<backend>: C<git>, C<svn>,
198 C<cvs> or C<hg>, a workdir, an optional C<cwd> (default C<.>), and an optional
199 C<files> array. C<cwd> selects a directory within the workdir; it does not
200 change the granted mount boundary. Files are relative to C<cwd> and must
201 stay within the selected workdir. The worker checks its resolved directory
202 after chdir and before starting the client, rejecting symlink escapes.
203 Backend selection is explicit. With no files, the command examines the
204 working copy at C<cwd>. Files must be inside the selected workdir;
205 they are passed as literal filenames, not options, revisions or shell code.
206 Git diff shows unstaged changes; SVN, CVS and Mercurial diff compare the
207 working copy with its base. No commit, update, fetch or push is performed.
208 C<vcs-log> reads revision history. CVS reports revisions separately per file
209 (including their commit IDs), unlike Git's repository-wide commits.
210 Use output limits to bound potentially long histories.
211  
212 These tools have separate C<vcs-diff>, C<vcs-status> and C<vcs-log> permission actions.
213 They request C<workdir-read> for the selected working copy. CVS additionally
214 requests C<ssh-agent>, which includes network access. SVN log may contact the
215 repository and also requests C<ssh-agent> to support svn+ssh; SVN diff/status,
216 Git and Mercurial operations run without network or home access.
217 A saved approval can cover the fixed operation regardless of filenames or
218 output filters, for that workdir and backend, or all supported backends.
219 Configured VCS clients and their configuration are trusted, including any
220 helpers they invoke; these tools do not sandbox the client's own semantics.
221 The ordinary sandbox grants still bound its host access. In unsandboxed
222 mode, the normal full-authority approval requirement applies.
223  
224 Clients are resolved at startup. C<executable.git>, C<executable.svn>,
225 C<executable.cvs> and C<executable.hg> in trusted program/instance settings
226 can override them. A missing client produces a tool error for that backend.
227  
228 =head1 REQUIREMENTS
229  
230 Bubblewrap is required by default, but can be disabled explicitly.
231 Perl 5.8.4 or later must run in the worker environment at startup (except
232 for C<--exec-cmd>). GNU find, grep, patch and sed are optional; tools
233 requiring an unavailable utility are omitted. Use C<tools/list> to see
234 which tools are available.
235  
236 Remote startup resolves workdirs, HOME, required mounts, executable
237 locations and VCS markers once; C<workdirs> thereafter uses this snapshot.
238 Optional C<mount-try> paths are instead passed to bubblewrap for every
239 invocation. Restart mcp-fs to refresh the workdir configuration and tools.
240  
241 =head1 CONNECTIONS
242  
243 HTTP is the default and does not print its URL on startup. C<--print-url>
244 prints the credential-bearing URL; the same token works in a bearer header.
245 C<--stdio> or
246 C<PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL=stdio> selects stdin/stdout.
247 See L<AnyEvent::MCP/GLOBAL CONFIGURATION> for named HTTP settings.
248  
249 =head1 OPTIONS
250  
251 Shared switches are documented in
252 L<AnyEvent::MCP::Server::Simple/COMMON COMMAND-LINE OPTIONS>.
253 The following switches are specific to C<mcp-fs>.
254  
255 =over
256  
257 =item --exec-cmd SANDBOX-GRANT,...
258  
259 Run command with specified sandbox grants, using current directory as
260 workdir; no MCP listener or permission rules. Supply command and arguments
261 after optional C<--> delimiter. Without command, run C<$SHELL> or C</bin/sh>.
262 C<--sandbox none> runs with normal host-user privileges.
263 Example: C<mcp-fs --exec-cmd workdir-read -- ls>.
264 C<--exec-cmd> is local-only; it cannot be combined with C<--host>.
265  
266 =item --ask MODE
267  
268 Permission prompts: C<helper> (default), C<tty>, C<yad>, C<mcp>, C<auto>.
269 Local helper keeps decisions local; tty/yad force interface without fallback.
270 C<mcp> asks client; C<auto> prefers client elicitation when advertised,
271 otherwise local helper. Overrides C<PERL_ANYEVENT_MCP_PERMISSION_ASK>.
272  
273 =item -h, --host HOST
274  
275 Run filesystem operations on HOST instead of the local machine. Empty or
276 omitted HOST selects local operation. All workdirs belong to this one host.
277 Remote workdir paths must be absolute. Host identity qualifies permission
278 scopes, not workdir IDs, which use logical pathnames without following symlinks.
279  
280 =item -e, --rsh COMMAND
281  
282 Remote shell command, default C<ssh>. Like rsync's C<-e>, COMMAND may include
283 arguments. Only used with C<--host>; C<rsh> is also supported.
284 The command is split into arguments locally without a local shell. The
285 remote shell invokes a short Perl loader. The launcher source is transferred
286 over stdin, followed by length-prefixed binary startup frames; subsequent
287 worker input remains on the same stream.
288  
289 =item --sandbox MODE
290  
291 Worker sandbox mode: C<bwrap> (default), C<auto>, C<none>.
292 C<bwrap> requires working bubblewrap. C<auto> uses bubblewrap if installed,
293 otherwise runs unsandboxed; failing bubblewrap does not silently fall back.
294 C<none> runs with full host-user privileges. Unsandboxed workers require
295 approval for maximum authority (world-write, network, shared-tmp, host-proc)
296 even for reads; narrower grants cannot authorize them. Startup warns.
297  
298 =item --bwrap PATH
299  
300 Use specified bubblewrap executable. Default: C<bwrap> found in C<PATH>.
301 Relevant with C<--sandbox bwrap> or C<--sandbox auto>.
302  
303 =back
304  
305 =head2 Shared-option behavior
306  
307 =over
308  
309 =item --name NAME
310  
311 Also selects permission profile C<fs-NAME> and its rule file,
312 C<rules/fs-NAME.ini>. Default instance name: C<default>.
313  
314 =item --print-url[=USER]
315  
316 Does not require a WORKDIR argument.
317  
318 =item --tool-help
319  
320 Requires normal WORKDIR arguments, since available tools depend on the
321 selected workdirs and installed utilities.
322  
323 =item --auto-allow TOOL[,ACTION[,CAPABILITY]]
324  
325 For example, combining C<--auto-allow '*,inspect,workdir-read'> with
326 C<--auto-allow '*,read,workdir-read'> approves only those two actions
327 within read-only workdir authority. C<--auto-allow '*,*,workdir-write'>
328 approves any action requiring at most workdir-write authority,
329 including reads.
330  
331 =back
332  
333 Rules reside in C<$XDG_CONFIG_HOME/anyevent-mcp/rules/fs-NAME.ini>,
334 or the corresponding C<$HOME/.config> path. The rules filename shares the
335 service-instance name but has an C<fs> namespace. The default instance uses
336 C<rules/fs-default.ini>. The rules path is printed on stderr when starting
337 HTTP; normal startup leaves stdout untouched.
338 Local and remote instances with the same C<--name> intentionally share
339 the same rule profile. Permission requests include a host dimension: C<local>
340 for local execution, or C<remote HOST> using C<--host> independently of
341 C<--rsh>. New persistent rules default to this host, but may match all hosts.
342 The workdir matcher is simply the logical path, independent of host. Existing
343 rules lacking C<match.host> continue to apply across local and remote hosts;
344 only newly saved host-specific rules restrict this.
345 Use different instance names or C<match.host> to separate approvals for
346 different hosts. Unscoped rules apply across hosts sharing the profile.
347  
348 =head1 TRUSTED CONFIGURATION
349  
350 In C<~/.config/anyevent-mcp/global.ini> (or the corresponding
351 C<XDG_CONFIG_HOME> location), C<[program NAME]> supplies defaults based
352 on the executable basename, while C<[instance NAME]> overrides them for
353 C<--name NAME>. A symlinked executable therefore has its own program defaults.
354  
355 [program mcp-fs]
356 mount-try.opt = ro:/opt
357 mount-try.perl = ro:/opt/perl
358 prepend-path = /opt/bin:/opt/sbin
359 mount.shared = rw:/srv/shared
360 env.cvs = CVS_RSH=/my/cvs/rsh
361 executable.perl = /opt/bin/perl
362  
363 [instance myproject]
364 mount.opt =
365 prepend-path =
366 mount.extra = ro:/srv/project-tools
367  
368 To override settings for one invocation, use the common C<-s> / C<--set>
369 option rather than editing the file:
370  
371 mcp-fs --stdio -s executable.perl=/opt/perl/bin/perl \
372 -s prepend-path=/opt/perl/bin /srv/project
373  
374 Command-line settings take precedence over program and instance settings;
375 repeated keys use their last value. See L<AnyEvent::MCP::Server::Simple/COMMON COMMAND-LINE OPTIONS>.
376  
377 Automatic permission rules can also be configured:
378  
379 [program mcp-fs]
380 auto-rule.10 = allow *,read,workdir-read
381 auto-rule.20 = allow *,write,workdir-write
382 auto-rule.30 = deny *,exec,*
383  
384 The supported configuration entries are:
385  
386 =over
387  
388 =item C<auto-rule.SUFFIX>
389  
390 Automatic permission rules apply to every named mcp-fs instance;
391 CLI auto-rules are evaluated first.
392  
393 =item C<mount.SUFFIX>
394  
395 A required sandbox mount. The named path must exist at startup.
396  
397 =item C<mount-try.SUFFIX>
398  
399 An optional sandbox mount, using bubblewrap's C<--ro-bind-try> or
400 C<--bind-try>. An absent path is skipped by bubblewrap at each invocation,
401 without a startup existence check.
402  
403 Both mount kinds are applied in alphabetical key order after the private
404 sandbox mounts. The suffix is an arbitrary stable name; an empty instance
405 value suppresses an inherited entry. Paths must be absolute. A colon after
406 C<ro:> or C<rw:> starts the literal pathname; no separate quoting or escaping
407 syntax is used.
408  
409 =item C<env.SUFFIX>
410  
411 Specify C<NAME=value> to set a literal value, or C<NAME> to inherit that
412 variable from the server environment if present. Values may contain spaces
413 and equals signs; there is no shell expansion. Entries are applied in
414 alphabetical key order after the default environment. An empty instance
415 entry suppresses the corresponding program entry. C<SSH_AUTH_SOCK> is managed
416 exclusively by the C<ssh-agent> grant, even when listed in these settings.
417 Environment settings do not expose paths; custom executables outside the
418 runtime/workdir mounts need configured mounts.
419  
420 =item C<prepend-path>
421  
422 Add colon-separated directories before the bubblewrapped worker's fixed
423 C<PATH> of C</usr/bin:/usr/sbin:/bin:/sbin:/usr/local/bin:/usr/local/sbin>.
424 Trailing colons are ignored, so both C</opt/bin> and C</opt/bin:> work.
425 The server's C<PATH> is not inherited. An empty instance value restores the
426 fixed default rather than the program value. C<--sandbox=none> continues to
427 use the host environment. Directories outside the normal runtime mounts
428 still need a configured mount to be accessible.
429  
430 =item C<executable.find>, C<executable.grep>, C<executable.patch>,
431 C<executable.perl>, C<executable.sed>, C<executable.bwrap>
432  
433 Override automatic executable discovery. Explicit choices must resolve to
434 executable files and are trusted instead of version-probed, except for
435 C<executable.perl>, which must satisfy the Perl minimum version.
436 C<executable.perl> defaults to C<perl> in the worker's C<PATH>;
437 the other worker executables are discovered there too. C<--bwrap>
438 overrides C<executable.bwrap> and is located on the host.
439  
440 =back
441  
442 Configured mounts grant baseline access to every sandbox invocation
443 (when present for C<mount-try>), independently of tool permission grants.
444 With C<world-read>, only C<rw:> exceptions are applied over the read-only
445 host filesystem. With C<world-write>, these configured mounts are ignored.
446 Baseline execution paths include C</usr>, C</bin>, system libraries and
447 selected system configuration, but not C</opt>. Shared host temporary
448 directories require C<shared-tmp>, a configured mount, or a C<world-*> grant.
449  
450 Defaults also include alternatives, font configuration, local timezone,
451 TLS certificate stores, NSS configuration and DNS configuration where
452 present. Unless C<world-read> or C<world-write> is granted, a synthetic
453 passwd entry is supplied without exposing the host passwd or group
454 databases. With either world grant, the host databases remain visible.
455  
456 The C<workdirs> result includes C<workdir_vcs>, a mapping from configured
457 workdir identities to arrays of backends with metadata markers directly
458 in that directory. Detection checks C<CVS>, C<.git>, C<.hg> and C<.svn>;
459 a Git metadata file is supported as well as a directory. Symlink markers
460 are reported without following them. This is a hint, not validation of a
461 repository. There is no recursive scan or parent search, multiple markers
462 are retained, and an empty array means no marker was found. Detection is
463 independent of the available clients in C<vcs_backends> and does not choose
464 the backend for a VCS command.
465  
466 =head1 SANDBOX GRANTS
467  
468 =over
469  
470 =item C<workdir-read>
471  
472 Read access to the selected workdir.
473  
474 =item C<workdir-write>
475  
476 Write access to the selected workdir; implies C<workdir-read>.
477  
478 =item C<all-workdirs-read>
479  
480 Read access to every configured workdir.
481  
482 =item C<all-workdirs-write>
483  
484 Write access to every configured workdir; implies read access.
485  
486 =item C<homedir-read>
487  
488 Read access to HOME.
489  
490 =item C<homedir-write>
491  
492 Write access to HOME; implies read access.
493  
494 =item C<world-read>
495  
496 Read access to the host filesystem.
497  
498 =item C<world-write>
499  
500 Write access to the host filesystem; implies C<world-read>.
501  
502 =item C<network>
503  
504 Enable networking outside the sandbox's network namespace. Without this
505 grant, bubblewrap uses a separate network namespace. Loopback connections
506 between processes in that same sandbox work, but its C<127.0.0.1> is not
507 the host's C<127.0.0.1>. Connecting to a host-side loopback server requires
508 C<network>.
509  
510 =item C<shared-tmp>
511  
512 Expose the host's C</tmp> and C</var/tmp>.
513  
514 =item C<long-running>
515  
516 Allow C<exec> timeouts over 300 seconds.
517  
518 =item C<host-proc>
519  
520 Host-process access, available only without bubblewrap.
521  
522 =item C<ssh-agent>
523  
524 Implies C<network>. Exposes the server's C<SSH_AUTH_SOCK> at
525 C</run/anyevent-mcp/ssh-agent> and sets the child's variable to that path.
526 In remote mode it uses the remote shell's agent socket, when available
527 (for example through SSH agent forwarding), rather than mounting the local
528 socket path. SSH authentication used to reach the host is separate from
529 the worker's C<ssh-agent> and C<network> grants.
530  
531 Also exposes C<~/.ssh/known_hosts> read-only if present, without mounting
532 the rest of HOME. Private key files and SSH user configuration are not exposed.
533 An unset or empty C<SSH_AUTH_SOCK> exposes no socket, allowing rsh-based CVS;
534 a configured socket must be an absolute path naming an existing socket node.
535 Socket replacement requires a new invocation; an existing bind mount keeps
536 the old node. Agent access permits authentication, not retrieval of private keys.
537  
538 =back
539  
540 C<all-workdirs-read> combined with C<workdir-write> mounts all workdirs
541 read-only except the selected one, which is writable. C<all-workdirs-write>
542 makes all writable. Configured workdirs are mounted using resolved absolute
543 paths, but their permission-rule identities are verbatim command-line
544 arguments.
545  
546 =head2 Workdir selection
547  
548 Persistent permission rules default to the selected workdir, with an explicit
549 option to match any configured workdir, including future additions. This
550 controls reuse of the rule, not the workdirs accessible in one operation.
551 The multibroker alias is shown in permission prompts, without changing the rule file.
552 Tools accept C<workdir> as a persistent positive integer ID, a numeric
553 string containing that ID, or an exact configured or resolved workdir path.
554 C<workdirs> returns C<workdirs> and C<resolved_workdirs> objects keyed by ID,
555 not arrays indexed by argument position. IDs are shared across server
556 instances in C<$XDG_CONFIG_HOME/anyevent-mcp/fs-workdir-ids.json>, or under
557 C<$HOME/.config> when XDG_CONFIG_HOME is unset. IDs use the logical
558 absolute pathname, without resolving symlinks (relative local arguments
559 are made absolute against the server's working directory). The same logical
560 pathname on local and remote servers receives the same ID, even when it
561 resolves to different physical directories. Permission-rule identities
562 remain the verbatim arguments; each server interprets IDs in its own workdirs.
563  
564 The registry stores C<ID =E<gt> [workdir, last_use]> pairs, with C<last_use>
565 as a Unix timestamp. Starting
566 a server resolves its IDs once and reserves any new allocations under the
567 file lock. An AnyEvent timer runs immediately and every 5.25 days, rereading
568 the registry and overwriting those fixed assignments with fresh timestamps.
569 Other entries expire after seven days without refresh;
570 their IDs can be reused. Restart servers after manually changing the registry.
571 Numeric IDs therefore survive restarts and argument reordering while retained,
572 but are not permanent references to paths that have expired.
573  
574 Non-numeric strings are matched only against configured workdirs, never
575 interpreted as arbitrary filesystem paths. Unknown or ambiguous selectors
576 fail. With only one workdir, the field may be omitted.
577 Overlapping workdirs have unspecified mount order and access effects;
578 do not rely on overlapping workdir boundaries for isolation.
579  
580 =head1 LIMITATIONS
581  
582 With bubblewrap, regardless of granted sandbox grants, the sandbox mounts procfs at
583 C</proc>. Its process entries are restricted by the PID namespace, but
584 kernel-wide and hardware information (including C</proc/irq> and
585 C</proc/bus>) remains visible. This is a limitation of bubblewrap's
586 C<--proc> option, which does not support C<subset=pid>.
587  
588 =head1 PERMISSIONS
589  
590 L<AnyEvent::MCP::Server::Permissions> applies ordered allow, deny and ask
591 decisions to these action classes:
592  
593 =over
594  
595 =item C<inspect>
596  
597 C<stat>, C<list>, C<find>.
598  
599 =item C<read>
600  
601 C<file-read>, C<read-lines>, C<grep>.
602  
603 =item C<write>
604  
605 C<file-write>, C<file-patch>.
606  
607 =item C<manage>
608  
609 C<path-op>.
610  
611 =item C<exec>
612  
613 Command execution.
614  
615 =back
616  
617 C<file-write> may create files despite being in the write class; manage
618 refers specifically to pathname operations rather than an exclusive right
619 to create files.
620 Filesystem operations have no path-based persistent subjects: their rules
621 match C<action>, C<sandbox-grants>, and C<match.workdir> when selected-workdir
622 authority is required. All-workdirs-only requests have no workdir identity.
623 Rules without C<match.workdir> can apply to any selected workdir if their sandbox
624 grants cover the request; dialog-generated workdir rules select exact or any.
625 The independent C<match.host> dimension matches C<local>, a remote host,
626 or all hosts, independently of the remote transport.
627 Instances with the same name share a rule file, including broad unscoped rules.
628 Requested paths are shown in the approval dialog for information only.
629 Exec additionally offers persistent
630 command/argv scopes as C<match.subject>. When stdin is provided, exec attaches display-only
631 details to the permission request: Unicode text for UTF-8 input, or a
632 bounded escaped-byte preview for Latin-1/Base64 input. The YAD helper offers
633 a separate C<View stdin...> window; the preview shows input size and
634 truncation. This does not change authorization: persistent exec rules match
635 argv, not stdin, and later runs may supply different scripts or bytes.
636 Conversion takes place before approval and the worker receives the exact
637 resulting bytes.
638 C<file-patch> supplies C<View patch> details with the target and supplied diff.
639 Base64 patches are decoded for display: valid UTF-8 is shown as Unicode,
640 otherwise non-printable bytes and backslashes are escaped in a byte view.
641 The UI chooses whether to show a separate viewer or an inline preview.
642 Each tool checks permissions before starting its worker. Approval
643 defaults to the local helper selected by C<PERL_ANYEVENT_MCP_PERMISSION_HELPER>,
644 which tries YAD, then a terminal, then denies once. Client elicitation is
645 selected with C<--ask mcp>, C<--ask auto>, or the corresponding
646 C<PERL_ANYEVENT_MCP_PERMISSION_ASK> value.
647  
648 You can edit the rule file at any time. It is reread on permission checks,
649 so changes apply without restarting the server. Keep it owned by your user
650 and private (mode 0600). See L<AnyEvent::MCP::Server::Permissions> for the
651 rule syntax and ordering.
652  
653 Permission retries retain earlier one-time approvals within the same call.
654 For one worker accessing several paths, the required sandbox-grant set combines
655 the authority needed for all paths and is approved once. An insufficient reduction fails before
656 the worker starts.
657 Multi-path C<stat> requires all paths inside its selected workdir.
658 C<path-op> can attempt cross-workdir renames after approving the sandbox
659 grants required for both paths. The sandboxed C<rename(2)> may fail with
660 C<EXDEV> across mounts; no copy/delete fallback is attempted.
661 C<mkpath> requires a path inside the selected workdir.
662 C<path-op> performs requested operations in this fixed order:
663 C<unlink>, C<rmdir>, C<mkpath>, C<mkdir>, C<symlink>, C<truncate>,
664 C<chmod>, C<rename>. C<mkpath> includes each missing component in the
665 combined permission check before starting the worker.
666 The first failure stops subsequent operations; successful earlier mutations
667 remain in place. There is no rollback or all-or-nothing transaction.
668  
669 Exec defaults to a 30-second timeout and permits up to 300 seconds without
670 additional timeout authority. A larger explicit C<timeout>, up to 21600
671 seconds (six hours), also requires C<long-running>. This capability is added
672 to the requested permissions automatically. Cancellation still terminates
673 the worker, regardless of its allowed timeout.
674  
675 The C<host-proc> grant is unavailable with bubblewrap. Runtime mounts
676 provide sandbox machinery. Symlinks resolve within granted mounts.
677 Without bubblewrap, workers operate in the host mount and process namespaces.
678  
679 =head1 PATCHES
680  
681 C<file-patch> uses L<AnyEvent::MCP/PATCH UTILITIES> for normalization and
682 validation. GNU patch runs inside the granted sandbox with fuzz zero.
683 Successful output replaces the original by rename after checking its
684 identity, size, timestamps, metadata and link count. These stat checks
685 do not detect every concurrent edit; they are not a filesystem transaction.
686  
687 =cut
688  
689 177 ▶use common::sense;
Subroutine BEGIN: called CC=1 SCAR=0.0
690  
691 177 ▶use MIME::Base64 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
692 177 ▶use Getopt::Long ();
Subroutine BEGIN: called CC=1 SCAR=0.0
693 177 ▶use Cwd ();
Subroutine BEGIN: called CC=1 SCAR=0.0
694 177 ▶use File::Basename ();
Subroutine BEGIN: called CC=1 SCAR=0.0
695 177 ▶use File::Spec::Unix ();
Subroutine BEGIN: called CC=1 SCAR=0.0
696 177 ▶use Text::ParseWords ();
Subroutine BEGIN: called CC=1 SCAR=0.0
697 177 ▶use IPC::Open2 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
698 177 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
699 177 ▶use Fcntl qw(F_SETFD);
Subroutine BEGIN: called CC=1 SCAR=0.0
700 177 ▶use Scalar::Util qw(weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
701  
702 177 ▶use JSON::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
703 177 ▶use AnyEvent ();
Subroutine BEGIN: called CC=1 SCAR=0.0
704 177 ▶use AnyEvent::MCP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
705 177 ▶use AnyEvent::MCP::Config ();
Subroutine BEGIN: called CC=1 SCAR=0.0
706 177 ▶use AnyEvent::MCP::Workdirs ();
Subroutine BEGIN: called CC=1 SCAR=0.0
707 177 ▶use AnyEvent::MCP::Server::Permissions ();
Subroutine BEGIN: called CC=1 SCAR=0.0
708 177 ▶use AnyEvent::Handle ();
Subroutine BEGIN: called CC=1 SCAR=0.0
709 177 ▶use AnyEvent::Log ();
Subroutine BEGIN: called CC=1 SCAR=0.0
710 177 ▶use AnyEvent::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
711  
712 177 ▶use AnyEvent::MCP::Server::Simple;
Subroutine BEGIN: called CC=1 SCAR=0.0
713  
714 # resolve an executable name or path to an absolute executable file.
715 128 ▶sub find_executable {
Subroutine find_executable: called CC=10 SCAR=27.8
716 128 my ($name) = @_;
717  
718 128 ▶ !ref $name and length $name and $name !~ /\0/
Branch: 1 branch
BranchTrueFalseTotal
not ref $name and length $name and not $name =~ /\0/u or return 128 0 128
Condition33%2/6
not ref $name and length $name and not $name =~ /\0/u
!ll&&!rl&&r
00128
not ref $name and length $name
!ll&&!rl&&r
00128
MC/DC0%0/3
not ref $name and length $name and not $name =~ /\0/u
not ref $name length $name not $name =~ /\0/u
Truth table25%1/4
not(A) and B and not(C)
A= not ref $nameB= length $nameC= not $name =~ /\0/u
ABCresult
0XX0
10X0
1100
1111
719 or return;
720  
721 my @path = $name =~ m{/}
722 ? ($name)
723 0 ▶ : map { (length $_ ? $_ : ".") . "/$name" } split /:/, $ENV{PATH};
Branch: 2 branches
BranchTrueFalseTotal
$name =~ m[/]u ? : 128 0 128
length $_ ? : 0 0 0
724 128 my $cwd = Cwd::getcwd;
725  
726 128 for my $path (@path) {
727 128 ▶ next unless -f $path and -x _;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path and -x _ 5 123 128
Condition66%2/3
-f $path and -x _
!ll&&!rl&&r
50123
MC/DC50%1/2
-f $path and -x _
-f $path -x _
Truth table66%2/3
A and B
A= -f $pathB= -x _
ABresult
0X0
100
111
728 123 ▶ return $path =~ m{\A/} ? $path : "$cwd/$path";
Branch: 1 branch
BranchTrueFalseTotal
$path =~ m[\A/]u ? : 123 0 123
729 }
730  
731 undef
732 5 }
733  
734 160 Getopt::Long::Configure qw(bundling no_ignore_case require_order);
735  
736 160 my $sandbox_mode = "bwrap";
737 160 my $usage = "Usage: $0 [OPTION]... WORKDIR [WORKDIR]...\n"
738 . " $0 --exec-cmd GRANT,... [--] [COMMAND [ARG]...]\n";
739  
740 160 my $server_options = mcp_getoptions ({
741 usage => $usage,
742 description => "Expose filesystem tools and command execution over MCP.\n"
743 . "Operations require permission and normally run inside bubblewrap.",
744 option_heading => "Filesystem options:",
745 options => [
746 ["--ask MODE", "Ask for permission via helper (default), tty, yad, mcp, or auto"],
747 ["-h, --host HOST", "Run on one remote host (default: local)"],
748 ["-e, --rsh COMMAND", "Remote shell command (default: ssh)"],
749 ["--sandbox MODE", "Use bwrap (default), auto, or none (unsandboxed)"],
750 ["--bwrap PATH", "Path to the bubblewrap executable"],
751 ["--exec-cmd GRANT,...", "Run a command directly with the named grants"],
752 ],
753 examples => " $0 --stdio /home/alice/src/project\n"
754 . " $0 --name project --print-url\n"
755 . " $0 --sandbox bwrap /home/alice/src/project\n"
756 . " $0 --auto-allow '*,inspect,workdir-read' --auto-allow '*,read,workdir-read' /project\n"
757 . " $0 --auto-allow '*,*,workdir-write' /project",
758 },
759 "sandbox=s" => \$sandbox_mode,
760 "ask=s" => \my $ask,
761 "host|h=s" => \my $host,
762 "rsh|e=s" => \my $rsh,
763 "exec-cmd=s" => \my $exec_cmd,
764 "bwrap=s" => \my $bwrap,
765 );
766  
767 156 my $name = $server_options->{name};
768 156 my $stdio = delete $server_options->{stdio};
769  
770 156 ▶die "--ask must be helper, tty, yad, mcp, or auto\n"
Branch: 1 branch
BranchTrueFalseTotal
if defined $ask and not $ask =~ /\A(?:helper|tty|yad|mcp|auto)\z/u 0 156 156
Condition66%2/3
defined $ask and not $ask =~ /\A(?:helper|tty|yad|mcp|auto)\z/u
!ll&&!rl&&r
421140
MC/DC0%0/2
defined $ask and not $ask =~ /\A(?:helper|tty|yad|mcp|auto)\z/u
defined $ask not $ask =~ /\A(?:helper|tty|yad|mcp|auto)\z/u
Truth table66%2/3
A and not(B)
A= defined $askB= not $ask =~ /\A(?:helper|tty|yad|mcp|auto)\z/u
ABresult
0X0
100
111
771 if defined $ask && $ask !~ /\A(?:helper|tty|yad|mcp|auto)\z/;
772  
773 156 ▶(defined $exec_cmd or @ARGV)
Branch: 1 branch
BranchTrueFalseTotal
defined $exec_cmd or @ARGV or die $usage 156 0 156
Condition66%2/3
defined $exec_cmd or @ARGV
l!l&&r!l&&!r
11550
MC/DC0%0/2
defined $exec_cmd or @ARGV
defined $exec_cmd @ARGV
Truth table66%2/3
A or B
A= defined $exec_cmdB= @ARGV
ABresult
1X1
011
000
774 or die $usage;
775  
776 156 ▶$sandbox_mode =~ /\A(?:bwrap|auto|none)\z/
Branch: 1 branch
BranchTrueFalseTotal
$sandbox_mode =~ /\A(?:bwrap|auto|none)\z/u or die "--sandbox must be bwrap, auto, or none\n" 156 0 156
777 or die "--sandbox must be bwrap, auto, or none\n";
778  
779 156 ▶$host //= "";
Condition100%2/2
$host //= ""
l!l
30126
MC/DC100%1/1
$host //= ""
$host
Truth table100%2/2
A
A= $host
Aresult
11
00
780 156 ▶$host !~ m{[\s/\0]} && $host !~ /\A-/
Branch: 1 branch
BranchTrueFalseTotal
$host =~ m[[\s/\0]]u || $host =~ /\A-/u and die "invalid remote host\n" 0 156 156
Condition33%1/3
$host =~ m[[\s/\0]]u or $host =~ /\A-/u
l!l&&r!l&&!r
00156
MC/DC0%0/2
$host =~ m[[\s/\0]]u or $host =~ /\A-/u
$host =~ m[[\s/\0]]u $host =~ /\A-/u
Truth table33%1/3
A or B
A= $host =~ m[[\s/\0]]uB= $host =~ /\A-/u
ABresult
1X1
011
000
781 or die "invalid remote host\n";
782 156 ▶$rsh //= "ssh";
Condition100%2/2
$rsh //= "ssh"
l!l
30126
MC/DC100%1/1
$rsh //= "ssh"
$rsh
Truth table100%2/2
A
A= $rsh
Aresult
11
00
783 156 my @rsh = Text::ParseWords::shellwords ($rsh);
784 156 ▶@rsh or die "empty remote shell command\n";
Branch: 1 branch
BranchTrueFalseTotal
@rsh or die "empty remote shell command\n" 156 0 156
785 156 my $remote = length $host;
786 156 ▶!($remote && defined $exec_cmd)
Branch: 1 branch
BranchTrueFalseTotal
($remote and defined $exec_cmd) and die "--host cannot be combined with --exec-cmd\n" 0 156 156
Condition66%2/3
$remote and defined $exec_cmd
!ll&&!rl&&r
126300
MC/DC0%0/2
$remote and defined $exec_cmd
$remote defined $exec_cmd
Truth table66%2/3
A and B
A= $remoteB= defined $exec_cmd
ABresult
0X0
100
111
787 or die "--host cannot be combined with --exec-cmd\n";
788  
789 156 my $program_name = AnyEvent::MCP::Config::program_name ();
790 156 my $config_file = AnyEvent::MCP::Config::_file ();
791 156 ▶my $config = -e $config_file ? AnyEvent::MCP::Config->global : undef;
Branch: 1 branch
BranchTrueFalseTotal
-e $config_file ? : 67 89 156
792 my %settings = $config ? (
793 67 %{ $config->{section}{"program $program_name"} },
794 156 ▶ %{ $config->{section}{"instance $name"} },
Branch: 1 branch
BranchTrueFalseTotal
$config ? : 67 89 156
795 ) : ();
796  
797 156 my $sandbox_path = "/usr/bin:/usr/sbin:/bin:/sbin:/usr/local/bin:/usr/local/sbin";
798 156 ▶(my $prepend = $settings{"prepend-path"} // "") =~ s/:+\z//;
Condition100%2/2
$settings{"prepend-path"} // ""
l!l
22134
MC/DC100%1/1
$settings{"prepend-path"} // ""
$settings{"prepend-path"}
Truth table100%2/2
A
A= $settings{"prepend-path"}
Aresult
11
00
799 156 ▶$sandbox_path = "$prepend:$sandbox_path" if length $prepend;
Branch: 1 branch
BranchTrueFalseTotal
if length $prepend 14 142 156
800  
801 156 my @mount;
802 156 for my $key (sort grep /\Amount(?:-try)?\./, keys %settings) {
803 236 my $value = $settings{$key};
804 236 ▶ next unless length $value;
Branch: 1 branch
BranchTrueFalseTotal
unless length $value 19 217 236
805 217 ▶ my ($mode, $path) = $value =~ /\A(ro|rw):(\/.*)\z/
Branch: 1 branch
BranchTrueFalseTotal
() = $value =~ m[\A(ro|rw):(/.*)\z]u or die "invalid $key mount '${value}'\n" 217 0 217
806 or die "invalid $key mount '$value'\n";
807 217 ▶ -e $path or die "invalid $key mount path '$path'\n" unless $remote || $key =~ /\Amount-try\./;
Branch: 1 branch
BranchTrueFalseTotal
unless $remote or $key =~ /\Amount-try\./u 53 164 217
Condition75%6/8
$remote || $key =~ /\Amount-try\./u || (-e $path || die("invalid $key mount path '${path}'\n"))
l!l&&r!l&&!r
164530
$remote or $key =~ /\Amount-try\./u
l!l&&r!l&&!r
907453
-e $path or die "invalid $key mount path '${path}'\n"
l!l
530
MC/DC0%0/3
$remote || $key =~ /\Amount-try\./u || (-e $path || die("invalid $key mount path '${path}'\n"))
$remote $key =~ /\Amount-try\./u -e $path
Truth table50%2/4
A or B || C
A= $remoteB= $key =~ /\Amount-try\./uC= -e $path
ABCresult
1XX1
01X1
0011
0000
808 217 push @mount, [$key, $mode, $path];
809 }
810  
811 156 my @environment;
812 156 for my $key (sort grep /\Aenv\./, keys %settings) {
813 88 my $value = $settings{$key};
814 88 ▶ next unless length $value;
Branch: 1 branch
BranchTrueFalseTotal
unless length $value 8 80 88
815 80 ▶ my ($name, $text) = $value =~ /\A([A-Za-z_][A-Za-z_0-9]*)(?:=(.*))?\z/s
Branch: 1 branch
BranchTrueFalseTotal
() = $value =~ /\A([A-Za-z_][A-Za-z_0-9]*)(?:=(.*))?\z/su or die "invalid $key environment entry '${value}'\n" 80 0 80
816 or die "invalid $key environment entry '$value'\n";
817 80 push @environment, [$name, $text];
818 }
819  
820 # SSH and rsh execute their command through a remote shell. Only this fixed
821 # launcher goes through that shell; all executable arguments are framed on stdin.
822 156 my $remote_launcher = q{#perl
823 use 5.008004;
824 use POSIX ();
825 use Fcntl qw(F_SETFD);
826 binmode STDIN;
827 my $read = sub {
828 my ($length) = @_;
829 my $data = "";
830 while (length $data < $length) {
831 my $got = sysread STDIN, my $part, $length - length $data;
832 defined $got or die "remote stdin: $!\n";
833 $got or die "short remote startup frame\n";
834 $data .= $part;
835 }
836 $data
837 };
838 my $length = unpack "N", $read->(4);
839 $length <= 1048576 or die "remote startup frame too large\n";
840 my ($home, @command) = unpack "(w/a*)*", $read->($length);
841 @command or die "empty remote command\n";
842 my $agent_index;
843 if (length $home) {
844 for my $i (1 .. $#command - 1) {
845 last if $command[$i] eq "--";
846 if ($command[$i - 1] eq "--ro-bind"
847 && $command[$i] eq "__MCP_REMOTE_AGENT__"
848 && $command[$i + 1] eq "/run/anyevent-mcp/ssh-agent") {
849 $agent_index = $i;
850 last;
851 }
852 }
853 }
854 if (defined $agent_index) {
855 my $source = $ENV{SSH_AUTH_SOCK};
856 if (length $source) {
857 $source =~ m{\A/} && -S $source
858 or die "remote SSH_AUTH_SOCK must name an absolute socket\n";
859 $command[$agent_index] = $source;
860 } else {
861 splice @command, $agent_index - 1, 3;
862 for (my $i = 0; $i < @command; ++$i) {
863 last if $command[$i] eq "--";
864 if ($command[$i] eq "--setenv" && $command[$i + 1] eq "SSH_AUTH_SOCK") {
865 splice @command, $i, 3;
866 last;
867 }
868 }
869 }
870 }
871 my $passwd_fd;
872 if (length $home) {
873 pipe (my $rd, my $wr) or die "passwd pipe: $!\n";
874 print {$wr} "sandbox:x:$<:" . POSIX::getgid () . ":Sandbox:$home:/bin/sh\n"
875 or die "passwd pipe: $!\n";
876 close $wr or die "passwd pipe: $!\n";
877 if (fileno ($rd) != 3) {
878 POSIX::dup2 (fileno ($rd), 3) == 3 or die "passwd dup2: $!\n";
879 close $rd;
880 open $rd, "<&=3" or die "passwd fd: $!\n";
881 }
882 defined fcntl ($rd, F_SETFD, 0) or die "passwd fcntl: $!\n";
883 $passwd_fd = $rd;
884 }
885 exec {$command[0]} @command;
886 die "remote exec $command[0]: $!\n";
887 };
888  
889 346 ▶sub shell_quote {
Subroutine shell_quote: called CC=1 SCAR=0.0
890 346 my ($text) = @_;
891 346 $text =~ s/'/'"'"'/g;
892 346 "'$text'"
893 }
894  
895 # Keep the remote command short (rsh limits its size). The tiny loader reads
896 # exactly the launcher source; unlike parsing a script from stdin, it cannot
897 # buffer bytes intended for the eventual exec'd worker.
898 156 my $remote_loader = q{binmode STDIN; my $n = shift; my $s;
899 while (length $s < $n) {
900 sysread STDIN, my $p, $n - length $s or die "short remote source\n";
901 $s .= $p;
902 }
903 eval $s; die $@ if $@;
904 };
905 156 ▶my $remote_command = shell_quote ($settings{"executable.perl"} || "perl")
Condition100%2/2
$settings{'executable.perl'} || 'perl'
l!l
6096
MC/DC100%1/1
$settings{'executable.perl'} || 'perl'
$settings{'executable.perl'}
Truth table100%2/2
A
A= $settings{'executable.perl'}
Aresult
11
00
906 . " -e " . shell_quote ($remote_loader) . " " . length $remote_launcher;
907  
908 136 ▶sub fs_remote_frame {
Subroutine fs_remote_frame: called CC=1 SCAR=0.0
909 136 pack "N/a*", pack "(w/a*)*", @_
910 }
911  
912 156 my ($find, $grep, $patch, $perl, $sed);
913 156 my %vcs_program;
914  
915 156 ▶$bwrap //= $settings{"executable.bwrap"} || "bwrap";
Condition75%3/4
$bwrap //= $settings{"executable.bwrap"} || "bwrap"
l!l
1497
$settings{'executable.bwrap'} || 'bwrap'
l!l
07
MC/DC100%1/1
$bwrap //= $settings{"executable.bwrap"} || "bwrap"
$bwrap
Truth table100%2/2
A
A= $bwrap
Aresult
11
00
916  
917 156 ▶if ($sandbox_mode ne "none" && !$remote) {
Branch: 2 branches
BranchTrueFalseTotal
if ($sandbox_mode ne 'none' and not $remote) { } 121 35 156
elsif ($sandbox_mode eq 'none') { } 7 28 35
Condition100%3/3
$sandbox_mode ne "none" and not $remote
!ll&&!rl&&r
728121
MC/DC100%2/2
$sandbox_mode ne "none" and not $remote
$sandbox_mode ne "none" not $remote
Truth table100%3/3
A and not(B)
A= $sandbox_mode ne "none"B= not $remote
ABresult
0X0
100
111
918 121 my $name = $bwrap;
919 121 $bwrap = find_executable $name;
920 121 ▶ die "bubblewrap executable not found: $name\n"
Branch: 1 branch
BranchTrueFalseTotal
if not $bwrap and $sandbox_mode eq "bwrap" 0 121 121
Condition33%1/3
not $bwrap and $sandbox_mode eq "bwrap"
!ll&&!rl&&r
12100
MC/DC0%0/2
not $bwrap and $sandbox_mode eq "bwrap"
not $bwrap $sandbox_mode eq "bwrap"
Truth table33%1/3
not(A) and B
A= not $bwrapB= $sandbox_mode eq "bwrap"
ABresult
0X0
100
111
921 if !$bwrap && $sandbox_mode eq "bwrap";
922 } elsif ($sandbox_mode eq "none") {
923 7 undef $bwrap;
924 }
925  
926 156 my @runtime_path = qw(
927 /usr
928 /bin
929 /sbin
930 /lib
931 /lib64
932 /etc/ld.so.cache
933 /etc/alternatives
934 /etc/fonts
935 /etc/localtime
936 /etc/ssl/openssl.cnf
937 /etc/ssl/certs
938 /etc/pki/tls/openssl.cnf
939 /etc/pki/tls/certs
940 /etc/pki/ca-trust
941 /etc/nsswitch.conf
942 /etc/hosts
943 /etc/resolv.conf
944 );
945 156 ▶@runtime_path = grep -e, @runtime_path unless $remote;
Branch: 1 branch
BranchTrueFalseTotal
unless $remote 126 30 156
946  
947 156 my (@workdir, @workdir_identity);
948 156 ▶if (defined $exec_cmd) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $exec_cmd) { } 1 155 156
949 1 @workdir = Cwd::abs_path ".";
950 1 ▶ @workdir or die "cannot resolve current directory\n";
Branch: 1 branch
BranchTrueFalseTotal
@workdir or die "cannot resolve current directory\n" 1 0 1
951 1 ▶ utf8::decode $workdir[0] or die "workdir is not UTF-8\n";
Branch: 1 branch
BranchTrueFalseTotal
utf8::decode($workdir[0]) or die "workdir is not UTF-8\n" 1 0 1
952 1 @workdir_identity = @workdir;
953 } else {
954 155 for my $path (@ARGV) {
955 167 my $workdir;
956 167 ▶ if ($remote) {
Branch: 1 branch
BranchTrueFalseTotal
if ($remote) { } 30 137 167
957 30 ▶ $path =~ m{\A/} or die "remote workdirs must be absolute paths\n";
Branch: 1 branch
BranchTrueFalseTotal
$path =~ m[\A/]u or die "remote workdirs must be absolute paths\n" 30 0 30
958 30 $workdir = $path;
959 } else {
960 137 $workdir = Cwd::abs_path $path;
961 137 ▶ -d $workdir or die "invalid workdir '$path'\n";
Branch: 1 branch
BranchTrueFalseTotal
-d $workdir or die "invalid workdir '${path}'\n" 137 0 137
962 }
963 167 ▶ utf8::decode $workdir or die "workdir is not UTF-8\n";
Branch: 1 branch
BranchTrueFalseTotal
utf8::decode($workdir) or die "workdir is not UTF-8\n" 167 0 167
964 167 my $identity = $path;
965 167 ▶ utf8::decode $identity or die "workdir identity is not UTF-8\n";
Branch: 1 branch
BranchTrueFalseTotal
utf8::decode($identity) or die "workdir identity is not UTF-8\n" 167 0 167
966 167 push @workdir, $workdir;
967 167 push @workdir_identity, $identity;
968 }
969 }
970  
971 156 my $home = $ENV{HOME};
972 156 ▶$home =~ m{\A/} and -d $home
Branch: 1 branch
BranchTrueFalseTotal
$home =~ m[\A/]u and -d $home or die "HOME must name an absolute existing directory\n" 156 0 156
Condition33%1/3
$home =~ m[\A/]u and -d $home
!ll&&!rl&&r
00156
MC/DC0%0/2
$home =~ m[\A/]u and -d $home
$home =~ m[\A/]u -d $home
Truth table33%1/3
A and B
A= $home =~ m[\A/]uB= -d $home
ABresult
0X0
100
111
973 or die "HOME must name an absolute existing directory\n";
974 156 ▶$home = Cwd::abs_path $home
Condition50%1/2
$home // die("cannot resolve HOME\n")
l!l
1560
MC/DC0%0/1
$home // die("cannot resolve HOME\n")
$home
Truth table50%1/2
A
A= $home
Aresult
11
00
975 // die "cannot resolve HOME\n";
976 156 ▶utf8::decode $home
Branch: 1 branch
BranchTrueFalseTotal
utf8::decode($home) or die "HOME is not a valid UTF-8 path\n" 156 0 156
977 or die "HOME is not a valid UTF-8 path\n";
978  
979 156 my $config_home;
980 156 ▶unless (defined $exec_cmd) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $exec_cmd) 155 1 156
981 155 $config_home = $ENV{XDG_CONFIG_HOME};
982 155 ▶ if (length $config_home) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $config_home) { } 155 0 155
983 155 ▶ $config_home =~ m{\A/}
Branch: 1 branch
BranchTrueFalseTotal
$config_home =~ m[\A/]u or die "permission config directory must be absolute\n" 155 0 155
984 or die "permission config directory must be absolute\n";
985 155 ▶ utf8::decode $config_home
Branch: 1 branch
BranchTrueFalseTotal
utf8::decode($config_home) or die "permission config directory is not UTF-8\n" 155 0 155
986 or die "permission config directory is not UTF-8\n";
987 } else {
988 0 $config_home = "$home/.config";
989 }
990 }
991  
992 156 my (%remote_program, @remote_vcs_marker, $remote_umask);
993 156 ▶if ($remote) {
Branch: 1 branch
BranchTrueFalseTotal
if ($remote) 30 126 156
994 # Probe once per startup; the local MCP frontend keeps the result.
995 # No remote package beyond core Perl, nor a remote installed mcp-fs.
996 30 my $probe = q{#perl
997 use 5.008004;
998 use Cwd ();
999 binmode STDOUT;
1000  
1001 my ($path, $mode, $bwrap_name, $nwork) = splice @ARGV, 0, 4;
1002 my @work = splice @ARGV, 0, $nwork;
1003 my $nmount = shift @ARGV;
1004 my @mount = splice @ARGV, 0, $nmount;
1005 my $nrun = shift @ARGV;
1006 my @runtime = splice @ARGV, 0, $nrun;
1007 $ENV{PATH} = $path;
1008  
1009 my $find_executable = sub {
1010 my ($name) = @_;
1011 my @path = $name =~ m{/} ? ($name)
1012 : map { (length $_ ? $_ : ".") . "/$name" } split /:/, $ENV{PATH}, -1;
1013 for (@path) {
1014 next unless -f $_ && -x _;
1015 return m{\A/} ? $_ : Cwd::getcwd () . "/$_";
1016 }
1017 ""
1018 };
1019  
1020 my $home = $ENV{HOME} || (getpwuid $<)[7];
1021 $home =~ m{\A/} && -d $home or die "remote HOME is not an absolute directory\n";
1022 $home = Cwd::abs_path $home or die "cannot resolve remote HOME\n";
1023 my @resolved = map {
1024 my $path = Cwd::abs_path $_;
1025 -d $path or die "invalid remote workdir '$_'\n";
1026 $path
1027 } @work;
1028 -e $_ or die "invalid remote mount '$_'\n" for @mount;
1029  
1030 my $bwrap = $mode eq "none" ? "" : $find_executable->($bwrap_name);
1031 $bwrap or die "remote bubblewrap executable not found: $bwrap_name\n"
1032 if $mode eq "bwrap";
1033  
1034 my %marker = (cvs => "CVS", git => ".git", hg => ".hg", svn => ".svn");
1035 my @markers = map {
1036 my $dir = $_;
1037 join ",", grep {
1038 lstat "$dir/$marker{$_}" && (-d _ || -l _ || ($_ eq "git" && -f _))
1039 } sort keys %marker
1040 } @resolved;
1041  
1042 my %test = (
1043 find => [[qw(--version)], qr/^find \(GNU findutils\)/m],
1044 grep => [[qw(--version)], qr/^grep \(GNU grep\)/m],
1045 patch => [[qw(--version)], qr/^GNU patch /m],
1046 sed => [[qw(--version)], qr/\(GNU sed\)/],
1047 );
1048 my @program;
1049 while (@ARGV) {
1050 my ($name, $wanted, $explicit) = splice @ARGV, 0, 3;
1051 my $found = $find_executable->($wanted);
1052 if ($found && !$explicit && $test{$name}) {
1053 my ($args, $match) = @{$test{$name}};
1054 my $ok = open my $fh, "-|", $found, @$args;
1055 if ($ok) {
1056 my $output = do { local $/; <$fh> };
1057 $ok = close $fh && $output =~ $match;
1058 }
1059 $found = "" unless $ok;
1060 }
1061 push @program, $found;
1062 }
1063  
1064 print pack "N/a*", pack "(w/a*)*",
1065 $home, $bwrap, scalar umask, @resolved, @markers,
1066 (map { -e $_ ? $_ : "" } @runtime), @program;
1067 };
1068  
1069 30 my @names = qw(perl find grep patch sed git svn cvs hg);
1070 my @args = (
1071 $sandbox_path, $sandbox_mode, $bwrap, scalar @workdir,
1072 @workdir, scalar (grep $_->[0] =~ /\Amount\./, @mount), (map $_->[2], grep $_->[0] =~ /\Amount\./, @mount),
1073 scalar @runtime_path, @runtime_path,
1074 30 ▶ (map { ($_, $settings{"executable.$_"} || $_, length $settings{"executable.$_"} ? 1 : 0) } @names),
Branch: 1 branch
BranchTrueFalseTotal
length $settings{"executable.$_"} ? : 30 240 270
Condition66%2/3
$settings{"executable.$_"} || $_
l!l&&r!l&&!r
302400
MC/DC0%0/2
$settings{"executable.$_"} || $_
$settings{"executable.$_"} $_
Truth table66%2/3
A || B
A= $settings{"executable.$_"}B= $_
ABresult
1X1
011
000
1075 );
1076 30 ▶ my @command = ($settings{"executable.perl"} || "perl", "-e", $probe, @args);
Condition50%1/2
$settings{'executable.perl'} || 'perl'
l!l
300
MC/DC0%0/1
$settings{'executable.perl'} || 'perl'
$settings{'executable.perl'}
Truth table50%1/2
A
A= $settings{'executable.perl'}
Aresult
11
00
1077 30 my $pid = IPC::Open2::open2 (my $out, my $in, @rsh, $host, $remote_command);
1078 30 binmode $in;
1079 30 binmode $out;
1080 30 ▶ print {$in} $remote_launcher, fs_remote_frame ("", @command) or die "remote probe input: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
print {$in;} $remote_launcher, fs_remote_frame("", @command) or die "remote probe input: $!\n" 30 0 30
1081 30 ▶ close $in or die "remote probe input: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
close $in or die "remote probe input: $!\n" 30 0 30
1082 30 my $output = do { local $/; <$out> };
1083 30 close $out;
1084 30 waitpid $pid, 0;
1085 30 ▶ $? == 0 or die "remote probe failed (wait status $?)\n";
Branch: 1 branch
BranchTrueFalseTotal
$? == 0 or die "remote probe failed (wait status $?)\n" 30 0 30
1086 30 my $declared = unpack "N", substr $output, 0, 4;
1087 30 ▶ length ($output) >= 4 && length ($output) == $declared + 4
Branch: 1 branch
BranchTrueFalseTotal
length $output >= 4 and length $output == $declared + 4 or die 'invalid remote probe frame (received ' . length($output) . " bytes, declared $declared, first bytes " . unpack("H*", substr($output, 0, 16)) . ")\n" 30 0 30
Condition33%1/3
length $output >= 4 and length $output == $declared + 4
!ll&&!rl&&r
0030
MC/DC0%0/2
length $output >= 4 and length $output == $declared + 4
length $output >= 4 length $output == $declared + 4
Truth table33%1/3
A and B
A= length $output >= 4B= length $output == $declared + 4
ABresult
0X0
100
111
1088 or die "invalid remote probe frame (received " . length ($output)
1089 . " bytes, declared $declared, first bytes " . unpack ("H*", substr ($output, 0, 16)) . ")\n";
1090 30 my @values = unpack "(w/a*)*", substr $output, 4;
1091 30 my $expected = 3 + 2 * @workdir + @runtime_path + @names;
1092 30 ▶ @values == $expected or die "invalid remote probe result\n";
Branch: 1 branch
BranchTrueFalseTotal
@values == $expected or die "invalid remote probe result\n" 30 0 30
1093 30 $home = shift @values;
1094 30 $bwrap = shift @values;
1095 30 $remote_umask = shift @values;
1096 30 @workdir = splice @values, 0, @workdir;
1097 30 ▶ @remote_vcs_marker = map { [length $_ ? split /,/, $_ : ()] } splice @values, 0, @workdir;
Branch: 1 branch
BranchTrueFalseTotal
length $_ ? : 13 17 30
1098 30 @runtime_path = grep length, splice @values, 0, @runtime_path;
1099 30 @remote_program{@names} = @values;
1100 30 for ($home, @workdir, @runtime_path, values %remote_program) {
1101 690 ▶ utf8::decode $_ or die "remote path is not UTF-8\n";
Branch: 1 branch
BranchTrueFalseTotal
utf8::decode($_) or die "remote path is not UTF-8\n" 690 0 690
1102 }
1103 }
1104  
1105 156 my ($workdir_ids, $workdir_refresh);
1106  
1107 156 ▶unless (defined $exec_cmd) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $exec_cmd) 155 1 156
1108 # IDs represent logical pathnames, not physical symlink destinations.
1109 155 $workdir_ids = AnyEvent::MCP::Workdirs->new (
1110 file => "$config_home/anyevent-mcp/fs-workdir-ids.json",
1111 paths => [map File::Spec::Unix->rel2abs ($_), @workdir_identity],
1112 );
1113  
1114 155 my $interval = .75 * $workdir_ids->{expiry};
1115 132 ▶ $workdir_refresh = AE::timer 0, $interval, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1116 132 $workdir_ids->refresh;
1117 155 };
1118 }
1119  
1120 156 my %sandbox_grant = (
1121 "workdir-read" => [],
1122 "workdir-write" => ["workdir-read"],
1123 "all-workdirs-read" => ["workdir-read"],
1124 "all-workdirs-write" => [qw(all-workdirs-read workdir-write)],
1125 "homedir-read" => [],
1126 "homedir-write" => ["homedir-read"],
1127 "world-read" => [qw(all-workdirs-read homedir-read)],
1128 "world-write" => [qw(world-read all-workdirs-write homedir-write)],
1129 "network" => [],
1130 "ssh-agent" => ["network"],
1131 "long-running" => [],
1132 "shared-tmp" => [],
1133 "host-proc" => [],
1134 );
1135  
1136 156 ▶my %sandbox_grant_description = (
Branch: 1 branch
BranchTrueFalseTotal
$bwrap ? : 147 9 156
1137 "workdir-read" => "Read files in the selected workdir",
1138 "workdir-write" => "Change files in the selected workdir",
1139 "all-workdirs-read" => "Read files in all configured workdirs",
1140 "all-workdirs-write" => "Change files in all configured workdirs",
1141 "homedir-read" => "Read files in your home directory",
1142 "homedir-write" => "Change files in your home directory",
1143 "world-read" => "Read the host filesystem",
1144 "world-write" => "Change the host filesystem",
1145 "network" => "Use network connections",
1146 "ssh-agent" => "Use your SSH agent to authenticate, read known_hosts and use network connections",
1147 "long-running" => "Run commands longer than five minutes",
1148 "shared-tmp" => "Access host temporary directories",
1149 "host-proc" => $bwrap ? "Host process access (unavailable with bubblewrap)"
1150 : "Full access to host processes",
1151 );
1152  
1153 156 my @exec_default_sandbox_grants = ("workdir-read");
1154  
1155 156 ▶my $umask = $remote ? $remote_umask : umask;
Branch: 1 branch
BranchTrueFalseTotal
$remote ? : 30 126 156
1156  
1157 156 my $permissions;
1158 $permissions = AnyEvent::MCP::Server::Permissions->new (
1159 sandbox_grants => \%sandbox_grant,
1160 5390 ▶ sandbox_grant_descriptions => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1161 5390 my ($request) = @_;
1162  
1163 5390 my %description = %sandbox_grant_description;
1164 5390 ▶ if (defined $request->{selected_workdir}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $request->{"selected_workdir"}) 5390 0 5390
1165 my $name = JSON::XS->new->utf8 (0)->allow_nonref
1166 5390 ->encode ($request->{selected_workdir});
1167 5390 $description{"workdir-read"} = "Read files in selected workdir $name";
1168 5390 $description{"workdir-write"} = "Change files in selected workdir $name";
1169 }
1170 5390 \%description
1171 },
1172 (defined $ask ? (ask => $ask) : ()),
1173 156 ▶ auto_rules => [@{$server_options->{auto_rules} || []},
Branch: 4 branches
BranchTrueFalseTotal
unless defined $exec_cmd 155 1 156
defined $ask ? : 114 41 155
$config ? : 66 89 155
$bwrap ? : 147 8 155
Condition100%2/2
$server_options->{'auto_rules'} || []
l!l
26129
MC/DC100%1/1
$server_options->{'auto_rules'} || []
$server_options->{'auto_rules'}
Truth table100%2/2
A
A= $server_options->{'auto_rules'}
Aresult
11
00
1174 ($config ? $config->auto_rules ($name) : ())],
1175 sandbox_implementation => $bwrap ? "bubblewrap" : "NONE - UNSANDBOXED (full host-user privileges)",
1176 actions => {
1177 inspect => "Inspect resource metadata and enumerate names",
1178 read => "Read resource contents",
1179 write => "Modify resource contents",
1180 manage => "Rename, remove, and manage filesystem paths",
1181 exec => "Run arbitrary commands",
1182 "vcs-diff" => "Read working-copy differences using a VCS client",
1183 "vcs-status" => "Read working-copy status using a VCS client",
1184 "vcs-log" => "Read revision history using a VCS client",
1185 },
1186 name => $name,
1187 file => "$config_home/anyevent-mcp/rules/fs-$name.ini",
1188 ) unless defined $exec_cmd;
1189  
1190 # permissions group tools by their kind of access, not by MCP tool name.
1191 156 my %tool_action = (
1192 stat => "inspect", list => "inspect", find => "inspect",
1193 "file-read" => "read", "read-lines" => "read", grep => "read",
1194 "file-write" => "write", "file-patch" => "write",
1195 "path-op" => "manage", exec => "exec",
1196 );
1197  
1198 # normalize an API pathname lexically against its selected workdir.
1199 3453 ▶sub fs_path {
Subroutine fs_path: called CC=9 SCAR=22.0
1200 3453 my ($workdir, $path) = @_;
1201  
1202 3453 ▶ !ref $path and length $path and $path !~ /\0/
Branch: 1 branch
BranchTrueFalseTotal
not ref $path and length $path and not $path =~ /\0/u or die "path must be a nonempty string without NUL\n" 3392 61 3453
Condition66%4/6
not ref $path and length $path and not $path =~ /\0/u
!ll&&!rl&&r
6103392
not ref $path and length $path
!ll&&!rl&&r
0613392
MC/DC33%1/3
not ref $path and length $path and not $path =~ /\0/u
not ref $path length $path not $path =~ /\0/u
Truth table50%2/4
not(A) and B and not(C)
A= not ref $pathB= length $pathC= not $path =~ /\0/u
ABCresult
0XX0
10X0
1100
1111
1203 or die "path must be a nonempty string without NUL\n";
1204 3392 ▶ $path = "$workdir/$path" unless $path =~ m{\A/};
Branch: 1 branch
BranchTrueFalseTotal
unless $path =~ m[\A/]u 3308 84 3392
1205  
1206 3392 my @part;
1207  
1208 3392 for (split m{/+}, $path) {
1209 17835 ▶ next if !length or $_ eq ".";
Branch: 1 branch
BranchTrueFalseTotal
if not length $_ or $_ eq "." 4283 13552 17835
Condition100%3/3
not length $_ or $_ eq "."
l!l&&r!l&&!r
339289113552
MC/DC100%2/2
not length $_ or $_ eq "."
not length $_ $_ eq "."
Truth table100%3/3
not(A) or B
A= not length $_B= $_ eq "."
ABresult
1X1
011
000
1210 13552 ▶ if ($_ eq "..") {
Branch: 1 branch
BranchTrueFalseTotal
if ($_ eq '..') { } 215 13337 13552
1211 215 pop @part;
1212 } else {
1213 13337 push @part, $_;
1214 }
1215 }
1216  
1217 3392 "/" . join "/", @part
1218 }
1219  
1220 # test pathname containment without resolving symlinks.
1221 9786 ▶sub fs_inside {
Subroutine fs_inside: called CC=3 SCAR=11.1
1222 9786 my ($path, $directory) = @_;
1223  
1224 9786 ▶ $directory eq "/" or $path eq $directory or (index $path, "$directory/") == 0
Branch: 1 branch
BranchTrueFalseTotal
$directory eq "/" or $path eq $directory or index($path, "$directory/") == 0 930 8856 9786
Condition66%2/3
$directory eq "/" or $path eq $directory
l!l&&r!l&&!r
09308856
MC/DC50%1/2
$directory eq "/" or $path eq $directory
$directory eq "/" $path eq $directory
Truth table66%2/3
A or B
A= $directory eq "/"B= $path eq $directory
ABresult
1X1
011
000
1225 }
1226  
1227 # classify relative to the selected workdir, not any configured workdir.
1228 1522 ▶sub fs_path_capability {
Subroutine fs_path_capability: called CC=6 SCAR=22.1
1229 1522 my ($workdir, $path, $mode) = @_;
1230  
1231 1522 ▶ return "workdir-$mode"
Branch: 1 branch
BranchTrueFalseTotal
if fs_inside($path, $workdir) 1440 82 1522
1232 if fs_inside $path, $workdir;
1233 return "all-workdirs-$mode"
1234 82 ▶ if grep { fs_inside $path, $_ } @workdir;
Branch: 1 branch
BranchTrueFalseTotal
if grep {fs_inside($path, $_);} @workdir 4 78 82
1235 78 ▶ return "homedir-$mode" if fs_inside $path, $home;
Branch: 1 branch
BranchTrueFalseTotal
if fs_inside($path, $home) 78 0 78
1236 0 ▶ return "shared-tmp" if (fs_inside $path, "/tmp") or (fs_inside $path, "/var/tmp");
Branch: 1 branch
BranchTrueFalseTotal
if fs_inside($path, "/tmp") or fs_inside($path, "/var/tmp") 0 0 0
Condition0%0/3
fs_inside($path, "/tmp") or fs_inside($path, "/var/tmp")
l!l&&r!l&&!r
000
MC/DC0%0/2
fs_inside($path, "/tmp") or fs_inside($path, "/var/tmp")
fs_inside($path, "/tmp") fs_inside($path, "/var/tmp")
Truth table0%0/3
A or B
A= fs_inside($path, "/tmp")B= fs_inside($path, "/var/tmp")
ABresult
1X1
011
000
1237  
1238 0 "world-$mode"
1239 }
1240  
1241 # persist selected-workdir identities only where the requested authority
1242 # actually depends on that selection. Broad all-workdirs grants are unscoped.
1243 2909 ▶sub fs_grant_workdir {
Subroutine fs_grant_workdir: called CC=5 SCAR=16.1
1244 2909 my ($identity, $grants) = @_;
1245  
1246 2909 my $have = $permissions->closure ($grants);
1247 2909 ▶ return $identity if $have->{"workdir-write"} && !$have->{"all-workdirs-write"};
Branch: 1 branch
BranchTrueFalseTotal
if $have->{"workdir-write"} and not $have->{"all-workdirs-write"} 861 2048 2909
Condition100%3/3
$have->{"workdir-write"} and not $have->{"all-workdirs-write"}
!ll&&!rl&&r
199652861
MC/DC100%2/2
$have->{"workdir-write"} and not $have->{"all-workdirs-write"}
$have->{"workdir-write"} not $have->{"all-workdirs-write"}
Truth table100%3/3
A and not(B)
A= $have->{"workdir-write"}B= not $have->{"all-workdirs-write"}
ABresult
0X0
100
111
1248 2048 ▶ return $identity if $have->{"workdir-read"} && !$have->{"all-workdirs-read"};
Branch: 1 branch
BranchTrueFalseTotal
if $have->{"workdir-read"} and not $have->{"all-workdirs-read"} 1968 80 2048
Condition100%3/3
$have->{"workdir-read"} and not $have->{"all-workdirs-read"}
!ll&&!rl&&r
8721968
MC/DC100%2/2
$have->{"workdir-read"} and not $have->{"all-workdirs-read"}
$have->{"workdir-read"} not $have->{"all-workdirs-read"}
Truth table100%3/3
A and not(B)
A= $have->{"workdir-read"}B= not $have->{"all-workdirs-read"}
ABresult
0X0
100
111
1249 undef
1250 80 }
1251  
1252 # permission prompts display the selected, verbatim configured workdir next
1253 # to workdir-specific grant choices. This is information, not a rule scope.
1254 2909 ▶sub fs_require_permission {
Subroutine fs_require_permission: called CC=1 SCAR=0.0
1255 2909 my ($req, $identity, $request) = @_;
1256  
1257 2909 $request->{selected_workdir} = $identity;
1258 2909 $req->require_permission ($request)
1259 }
1260  
1261 # direct execution has no filesystem, network or process isolation. Request
1262 # every grant the process effectively receives, regardless of client wishes.
1263 156 my @unsandboxed_grants = qw(world-write network shared-tmp host-proc);
1264 2957 ▶sub fs_effective_grants {
Subroutine fs_effective_grants: called CC=2 SCAR=6.9
1265 2957 ▶ return @_ if $bwrap;
Branch: 1 branch
BranchTrueFalseTotal
if $bwrap 2923 34 2957
1266 34 (@unsandboxed_grants, grep $_ eq "long-running", @_)
1267 }
1268  
1269 # one worker needs the combined sandbox authority for every path it will access.
1270 2909 ▶sub fs_permission_dimensions {
Subroutine fs_permission_dimensions: called CC=4 SCAR=13.9
1271 2909 my ($workdir, $subject, $choices) = @_;
1272 2909 my %dimensions;
1273  
1274 2909 ▶ my $host_id = $remote ? "remote $host" : "local";
Branch: 1 branch
BranchTrueFalseTotal
$remote ? : 110 2799 2909
1275 $dimensions{host} = {
1276 2909 label => "Host", value => $host_id,
1277 choices => [
1278 { label => "This host", match => $host_id },
1279 { label => "All hosts", match => "^" },
1280 ],
1281 };
1282  
1283 $dimensions{workdir} = {
1284 2909 ▶ label => "Workdir", value => $workdir,
Branch: 1 branch
BranchTrueFalseTotal
if defined $workdir 2829 80 2909
1285 choices => [
1286 { label => "This configured workdir", match => $workdir },
1287 { label => "Any configured workdir, including future ones", match => "^" },
1288 ],
1289 } if defined $workdir;
1290 $dimensions{subject} = {
1291 2909 ▶ label => "Subject", value => $subject, choices => $choices,
Branch: 1 branch
BranchTrueFalseTotal
if defined $subject 1708 1201 2909
1292 } if defined $subject;
1293  
1294 2909 \%dimensions
1295 }
1296  
1297 1201 ▶sub fs_require_paths {
Subroutine fs_require_paths: called CC=5 SCAR=16.1
1298 1201 my ($req, $workdir, $identity, $paths, $mode, $reason, $details) = @_;
1299  
1300 1201 my %seen;
1301 1201 $paths = [grep !$seen{$_}++, @$paths];
1302 1201 my %need = map { (fs_path_capability $workdir, $_, $mode) => 1 } @$paths;
1303 1201 %need = map { $_ => 1 } fs_effective_grants (keys %need);
1304 1201 my @grants = sort keys %need;
1305 my $grant = fs_require_permission ($req, $identity, {
1306 tool => $req->{tool},
1307 action => $tool_action{$req->{tool}},
1308 1201 ▶ dimensions => fs_permission_dimensions (fs_grant_workdir ($identity, \@grants)),
Branch: 1 branch
BranchTrueFalseTotal
defined $details ? : 0 1201 1201
Condition100%2/2
$reason // qq[$req->{"tool"} ] . join(", ", @$paths)
l!l
111190
MC/DC100%1/1
$reason // qq[$req->{"tool"} ] . join(", ", @$paths)
$reason
Truth table100%2/2
A
A= $reason
Aresult
11
00
1309 paths => $paths,
1310 sandbox_grants => \@grants,
1311 reason => $reason // "$req->{tool} " . join (", ", @$paths),
1312 (defined $details ? (details => $details) : ()),
1313 });
1314  
1315 674 my $have = $permissions->closure ($grant);
1316 674 for my $capability (sort keys %need) {
1317 742 ▶ $have->{$capability}
Branch: 1 branch
BranchTrueFalseTotal
$have->{$capability} or die qq[permission reduced below $capability for $req->{"tool"}\n] 663 79 742
1318 or die "permission reduced below $capability for $req->{tool}\n";
1319 }
1320  
1321 595 [sort keys %$have]
1322 }
1323  
1324 # test whether the granted capability set makes this pathname writable.
1325 21764 ▶sub fs_writable {
Subroutine fs_writable: called CC=10 SCAR=23.4
1326 21764 my ($workdir, $path, $have) = @_;
1327  
1328 $have->{"world-write"}
1329 140 ▶ or ($have->{"all-workdirs-write"} and (grep { fs_inside $path, $_ } @workdir))
Condition83%10/12
$have->{"workdir-write"} and fs_inside($path, $workdir)
!ll&&!rl&&r
1683149250
$have->{"homedir-write"} and fs_inside($path, $home)
!ll&&!rl&&r
2117154639
$have->{"shared-tmp"} and fs_inside($path, "/tmp") || fs_inside($path, "/var/tmp")
!ll&&!rl&&r
21669426
fs_inside($path, "/tmp") or fs_inside($path, "/var/tmp")
l!l&&r!l&&!r
6042
MC/DC0%0/2
$have->{"workdir-write"} and fs_inside($path, $workdir)
$have->{"workdir-write"} fs_inside($path, $workdir)
MC/DC100%2/2
$have->{"homedir-write"} and fs_inside($path, $home)
$have->{"homedir-write"} fs_inside($path, $home)
MC/DC0%0/3
$have->{"shared-tmp"} and fs_inside($path, "/tmp") || fs_inside($path, "/var/tmp")
$have->{"shared-tmp"} fs_inside($path, "/tmp") fs_inside($path, "/var/tmp")
Truth table66%2/3
A and B
A= $have->{"workdir-write"}B= fs_inside($path, $workdir)
ABresult
0X0
100
111
Truth table100%3/3
A and B
A= $have->{"homedir-write"}B= fs_inside($path, $home)
ABresult
0X0
100
111
Truth table0%0/4
A and B or C
A= $have->{"shared-tmp"}B= fs_inside($path, "/tmp")C= fs_inside($path, "/var/tmp")
ABCresult
0XX0
1000
11X1
1011
1330 or ($have->{"workdir-write"} and fs_inside $path, $workdir)
1331 or ($have->{"homedir-write"} and (fs_inside $path, $home))
1332 21764 ▶ or ($have->{"shared-tmp"} and ((fs_inside $path, "/tmp") or (fs_inside $path, "/var/tmp")))
Branch: 1 branch
BranchTrueFalseTotal
$have->{"world-write"} or $have->{"all-workdirs-write"} and grep {fs_inside($path, $_);} @workdir or $have->{"workdir-write"} and fs_inside($path, $workdir) or $have->{"homedir-write"} and fs_inside($path, $home) or $have->{"shared-tmp"} and fs_inside($path, "/tmp") || fs_inside($path, "/var/tmp") 47 21717 21764
Condition80%12/15
$have->{'world-write'} || $have->{'all-workdirs-write'} && grep({fs_inside($path, $_);} @workdir) || $have->{'workdir-write'} && fs_inside($path, $workdir) || $have->{'homedir-write'} && fs_inside($path, $home) || $have->{'shared-tmp'} && (fs_inside($path, '/tmp') || fs_inside($path, '/var/tmp'))
l!l&&r!l&&!r
47621711
$have->{"world-write"} or $have->{"all-workdirs-write"} and grep {fs_inside($path, $_);} @workdir or $have->{"workdir-write"} and fs_inside($path, $workdir) or $have->{"homedir-write"} and fs_inside($path, $home)
l!l&&r!l&&!r
83921717
$have->{"world-write"} or $have->{"all-workdirs-write"} and grep {fs_inside($path, $_);} @workdir or $have->{"workdir-write"} and fs_inside($path, $workdir)
l!l&&r!l&&!r
8021756
$have->{"world-write"} or $have->{"all-workdirs-write"} and grep {fs_inside($path, $_);} @workdir
l!l&&r!l&&!r
8021756
$have->{"all-workdirs-write"} and grep {fs_inside($path, $_);} @workdir
!ll&&!rl&&r
21686700
MC/DC0%0/6
$have->{'world-write'} || $have->{'all-workdirs-write'} && grep({fs_inside($path, $_);} @workdir) || $have->{'workdir-write'} && fs_inside($path, $workdir) || $have->{'homedir-write'} && fs_inside($path, $home) || $have->{'shared-tmp'} && (fs_inside($path, '/tmp') || fs_inside($path, '/var/tmp'))
$have->{"world-write"} $have->{"all-workdirs-write"} grep {fs_inside($path, $_);} @workdir $have->{"workdir-write"} and fs_inside($path, $workdir) $have->{"homedir-write"} and fs_inside($path, $home) $have->{'shared-tmp'} && (fs_inside($path, '/tmp') || fs_inside($path, '/var/tmp'))
Truth table10%1/10
A or B and C or D or E || F
A= $have->{"world-write"}B= $have->{"all-workdirs-write"}C= grep {fs_inside($path, $_);} @workdirD= $have->{"workdir-write"} and fs_inside($path, $workdir)E= $have->{"homedir-write"} and fs_inside($path, $home)F= $have->{'shared-tmp'} && (fs_inside($path, '/tmp') || fs_inside($path, '/var/tmp'))
ABCDEFresult
1XXXXX1
011XXX1
00X1XX1
0101XX1
00X01X1
01001X1
00X0011
0100011
00X0000
0100000
1333 }
1334  
1335 # build the bubblewrap argv implementing the granted sandbox authority.
1336 1553 ▶sub fs_sandbox {
Subroutine fs_sandbox: called CC=62 SCAR=41.9
1337 1553 my ($workdir, $sandbox_grants) = @_;
1338  
1339 1553 my $have = {};
1340 1553 my @todo = @$sandbox_grants;
1341 1553 ▶ while (@todo) {
Branch: 1 branch
BranchTrueFalseTotal
if (@todo) 2875 1553 4428
1342 2875 my $capability = pop @todo;
1343 2875 ▶ exists $sandbox_grant{$capability} or die "Unknown permission capability '$capability'\n";
Branch: 1 branch
BranchTrueFalseTotal
exists $sandbox_grant{$capability} or die "Unknown permission capability '${capability}'\n" 2875 0 2875
1344 2875 ▶ next if $have->{$capability}++;
Branch: 1 branch
BranchTrueFalseTotal
if $have->{$capability}++ 514 2361 2875
1345 2361 push @todo, @{$sandbox_grant{$capability}};
1346 }
1347  
1348 1553 ▶ unless ($bwrap) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($bwrap) 18 1535 1553
1349 18 ▶ unless (defined $exec_cmd) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $exec_cmd) 17 1 18
1350 $have->{$_} or die "unsandboxed execution needs $_ grant\n"
1351 17 ▶ for @unsandboxed_grants;
Branch: 1 branch
BranchTrueFalseTotal
$have->{$_} or die "unsandboxed execution needs $_ grant\n" 60 2 62
1352 }
1353 16 return ();
1354 }
1355  
1356 die "host-proc sandbox authority is unresolved and unavailable in v1\n"
1357 1535 ▶ if $have->{"host-proc"};
Branch: 1 branch
BranchTrueFalseTotal
if $have->{"host-proc"} 0 1535 1535
1358  
1359 1535 my @command = ($bwrap, qw(
1360 --die-with-parent
1361 --unshare-user --unshare-pid --unshare-ipc --unshare-uts
1362 --unshare-cgroup-try --disable-userns --cap-drop ALL
1363 ));
1364 1535 ▶ push @command, "--new-session" unless defined $exec_cmd;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $exec_cmd 1535 0 1535
1365  
1366 1535 ▶ push @command, "--unshare-net" unless $have->{network};
Branch: 1 branch
BranchTrueFalseTotal
unless $have->{"network"} 1390 145 1535
1367  
1368 push @command, $have->{"world-write"} ? "--bind-try" : "--ro-bind-try", "/", "/"
1369 1535 ▶ if $have->{"world-read"};
Branch: 2 branches
BranchTrueFalseTotal
if $have->{"world-read"} 9 1526 1535
$have->{'world-write'} ? : 4 5 9
1370  
1371 1535 my @scope_mount;
1372  
1373 1535 ▶ unless ($have->{"world-read"}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($have->{"world-read"}) 1526 9 1535
1374 1526 for my $path (@runtime_path) {
1375 18312 ▶ my $mount = (fs_writable $workdir, $path, $have) ? "--bind-try" : "--ro-bind-try";
Branch: 1 branch
BranchTrueFalseTotal
fs_writable($workdir, $path, $have) ? : 0 18312 18312
1376 18312 push @scope_mount, $mount, $path, $path;
1377 }
1378 }
1379  
1380 1535 ▶ if ($have->{"homedir-read"}
Branch: 1 branch
BranchTrueFalseTotal
if ($have->{"homedir-read"} and !$have->{"world-read"} || $have->{"homedir-write"} && !$have->{"world-write"}) 39 1496 1535
Condition77%7/9
$have->{"homedir-read"} and !$have->{"world-read"} || $have->{"homedir-write"} && !$have->{"world-write"}
!ll&&!rl&&r
1487939
not $have->{"world-read"} or $have->{"homedir-write"} and not $have->{"world-write"}
l!l&&r!l&&!r
3909
$have->{"homedir-write"} and not $have->{"world-write"}
!ll&&!rl&&r
540
MC/DC50%2/4
$have->{"homedir-read"} and !$have->{"world-read"} || $have->{"homedir-write"} && !$have->{"world-write"}
$have->{"homedir-read"} not $have->{"world-read"} $have->{"homedir-write"} not $have->{"world-write"}
Truth table80%4/5
A and not(B) or C and not(D)
A= $have->{"homedir-read"}B= not $have->{"world-read"}C= $have->{"homedir-write"}D= not $have->{"world-write"}
ABCDresult
0XXX0
100X0
10100
11XX1
10111
1381 and (!$have->{"world-read"} or ($have->{"homedir-write"} and !$have->{"world-write"}))) {
1382 39 ▶ my $mount = (fs_writable $workdir, $home, $have) ? "--bind-try" : "--ro-bind-try";
Branch: 1 branch
BranchTrueFalseTotal
fs_writable($workdir, $home, $have) ? : 39 0 39
1383 39 push @scope_mount, $mount, $home, $home;
1384 }
1385  
1386 1535 ▶ if ($have->{"all-workdirs-read"}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($have->{'all-workdirs-read'}) { } 23 1512 1535
elsif ($have->{'workdir-read'}) { } 1384 128 1512
1387 23 for my $path (@workdir) {
1388 my $mount = ($have->{"all-workdirs-write"}
1389 37 ▶ or ($path eq $workdir && $have->{"workdir-write"}))
Branch: 1 branch
BranchTrueFalseTotal
$have->{'all-workdirs-write'} || $path eq $workdir && $have->{'workdir-write'} ? : 18 19 37
Condition100%6/6
$have->{"all-workdirs-write"} or $path eq $workdir and $have->{"workdir-write"}
l!l&&r!l&&!r
14419
$path eq $workdir and $have->{"workdir-write"}
!ll&&!rl&&r
9104
MC/DC100%3/3
$have->{"all-workdirs-write"} or $path eq $workdir and $have->{"workdir-write"}
$have->{"all-workdirs-write"} $path eq $workdir $have->{"workdir-write"}
Truth table100%4/4
A or B and C
A= $have->{"all-workdirs-write"}B= $path eq $workdirC= $have->{"workdir-write"}
ABCresult
1XX1
0111
00X0
0100
1390 ? "--bind" : "--ro-bind";
1391 37 push @scope_mount, $mount, $path, $path;
1392 }
1393 } elsif ($have->{"workdir-read"}) {
1394 1384 ▶ my $mount = $have->{"workdir-write"} ? "--bind" : "--ro-bind";
Branch: 1 branch
BranchTrueFalseTotal
$have->{'workdir-write'} ? : 338 1046 1384
1395 1384 push @scope_mount, $mount, $workdir, $workdir;
1396 }
1397  
1398 # replace special host mounts even when broad filesystem authority was asked.
1399 1535 push @command, qw(--tmpfs /sys --tmpfs /run --dev /dev);
1400 1535 push @command, "--proc", "/proc";
1401  
1402 1535 for my $tmp (qw(/tmp /var/tmp)) {
1403 3070 ▶ if ($have->{"shared-tmp"} && !$have->{"world-write"}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($have->{'shared-tmp'} and not $have->{'world-write'}) { } 6 3064 3070
elsif (not $have->{'world-read'} || grep(($_->[2] eq $tmp && $_->[0] =~ /\Amount\./u), @mount)) { } 3046 18 3064
Condition66%2/3
$have->{"shared-tmp"} and not $have->{"world-write"}
!ll&&!rl&&r
306406
MC/DC50%1/2
$have->{"shared-tmp"} and not $have->{"world-write"}
$have->{"shared-tmp"} not $have->{"world-write"}
Truth table66%2/3
A and not(B)
A= $have->{"shared-tmp"}B= not $have->{"world-write"}
ABresult
0X0
100
111
1404 6 push @command, "--bind-try", $tmp, $tmp;
1405 ▶ } elsif (!$have->{"world-read"}
Condition50%3/6
$have->{'world-read'} || grep(($_->[2] eq $tmp && $_->[0] =~ /\Amount\./u), @mount)
l!l&&r!l&&!r
1803046
$_->[2] eq $tmp && $_->[0] =~ /\Amount\./u
!ll&&!rl&&r
108000
MC/DC50%1/2
$have->{'world-read'} || grep(($_->[2] eq $tmp && $_->[0] =~ /\Amount\./u), @mount)
$have->{'world-read'} grep(($_->[2] eq $tmp && $_->[0] =~ /\Amount\./u), @mount)
MC/DC0%0/2
$_->[2] eq $tmp && $_->[0] =~ /\Amount\./u
$_->[2] eq $tmp $_->[0] =~ /\Amount\./u
Truth table66%2/3
A || B
A= $have->{'world-read'}B= grep(($_->[2] eq $tmp && $_->[0] =~ /\Amount\./u), @mount)
ABresult
1X1
011
000
Truth table33%1/3
A && B
A= $_->[2] eq $tmpB= $_->[0] =~ /\Amount\./u
ABresult
0X0
100
111
1406 && !(grep $_->[2] eq $tmp && $_->[0] =~ /\Amount\./, @mount)) {
1407 3046 push @command, "--tmpfs", $tmp;
1408 }
1409 }
1410  
1411 # explicit mounts override the private baseline where bwrap/kernel permit it.
1412 1535 push @command, @scope_mount;
1413 1535 for my $path (qw(/etc/resolv.conf /etc/hosts)) {
1414 3070 ▶ my $mount = (fs_writable $workdir, $path, $have) ? "--bind-try" : "--ro-bind-try";
Branch: 1 branch
BranchTrueFalseTotal
fs_writable($workdir, $path, $have) ? : 8 3062 3070
1415 3070 push @command, $mount, $path, $path;
1416 }
1417  
1418 # configured exceptions come after workdir/home mounts. Do not let an
1419 # administrator's ro exception narrow explicitly granted write authority.
1420 1535 ▶ unless ($have->{"world-write"}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($have->{"world-write"}) 1531 4 1535
1421 1531 for my $entry (@mount) {
1422 572 my ($key, $mode, $path) = @$entry;
1423 572 ▶ next if $mode eq "ro" && ($have->{"world-read"} || fs_writable $workdir, $path, $have);
Branch: 1 branch
BranchTrueFalseTotal
if $mode eq "ro" and $have->{"world-read"} || fs_writable($workdir, $path, $have) 16 556 572
Condition100%6/6
$mode eq "ro" and $have->{"world-read"} || fs_writable($workdir, $path, $have)
!ll&&!rl&&r
21933716
$have->{"world-read"} or fs_writable($workdir, $path, $have)
l!l&&r!l&&!r
106337
MC/DC100%3/3
$mode eq "ro" and $have->{"world-read"} || fs_writable($workdir, $path, $have)
$mode eq "ro" $have->{"world-read"} fs_writable($workdir, $path, $have)
Truth table100%4/4
A and B or C
A= $mode eq "ro"B= $have->{"world-read"}C= fs_writable($workdir, $path, $have)
ABCresult
0XX0
1000
11X1
1011
1424 556 ▶ push @command, ($mode eq "rw" ? "--bind" : "--ro-bind")
Branch: 2 branches
BranchTrueFalseTotal
$mode eq 'rw' ? : 219 337 556
$key =~ /\Amount-try\./u ? : 345 211 556
1425 . ($key =~ /\Amount-try\./ ? "-try" : ""), $path, $path;
1426 }
1427 }
1428  
1429 push @command, "--file", 3, "/etc/passwd"
1430 1535 ▶ unless $have->{"world-read"};
Branch: 1 branch
BranchTrueFalseTotal
unless $have->{"world-read"} 1526 9 1535
1431  
1432 1535 my $agent_socket;
1433 1535 ▶ if ($have->{"ssh-agent"}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($have->{"ssh-agent"}) 145 1390 1535
1434 145 ▶ if ($remote) {
Branch: 2 branches
BranchTrueFalseTotal
if ($remote) { } 2 143 145
elsif (length $ENV{'SSH_AUTH_SOCK'}) { } 143 0 143
1435 2 $agent_socket = "/run/anyevent-mcp/ssh-agent";
1436 2 push @command, "--ro-bind", "__MCP_REMOTE_AGENT__", $agent_socket;
1437 } elsif (length $ENV{SSH_AUTH_SOCK}) {
1438 $ENV{SSH_AUTH_SOCK} =~ m{\A/} && -S $ENV{SSH_AUTH_SOCK}
1439 143 ▶ or die "SSH_AUTH_SOCK must name an absolute existing socket\n";
Branch: 1 branch
BranchTrueFalseTotal
$ENV{"SSH_AUTH_SOCK"} =~ m[\A/]u and -S $ENV{"SSH_AUTH_SOCK"} or die "SSH_AUTH_SOCK must name an absolute existing socket\n" 142 1 143
Condition66%2/3
$ENV{"SSH_AUTH_SOCK"} =~ m[\A/]u and -S $ENV{"SSH_AUTH_SOCK"}
!ll&&!rl&&r
01142
MC/DC50%1/2
$ENV{"SSH_AUTH_SOCK"} =~ m[\A/]u and -S $ENV{"SSH_AUTH_SOCK"}
$ENV{"SSH_AUTH_SOCK"} =~ m[\A/]u -S $ENV{"SSH_AUTH_SOCK"}
Truth table66%2/3
A and B
A= $ENV{"SSH_AUTH_SOCK"} =~ m[\A/]uB= -S $ENV{"SSH_AUTH_SOCK"}
ABresult
0X0
100
111
1440 142 my $source = $ENV{SSH_AUTH_SOCK};
1441 142 ▶ utf8::decode $source or die "SSH_AUTH_SOCK is not UTF-8\n";
Branch: 1 branch
BranchTrueFalseTotal
utf8::decode($source) or die "SSH_AUTH_SOCK is not UTF-8\n" 142 0 142
1442 142 $agent_socket = "/run/anyevent-mcp/ssh-agent";
1443 142 push @command, "--ro-bind", $source, $agent_socket;
1444 }
1445 push @command, "--ro-bind-try", "$home/.ssh/known_hosts", "$home/.ssh/known_hosts"
1446 144 ▶ unless $have->{"homedir-read"} || $have->{"world-read"};
Branch: 1 branch
BranchTrueFalseTotal
unless $have->{"homedir-read"} or $have->{"world-read"} 144 0 144
Condition33%1/3
$have->{"homedir-read"} or $have->{"world-read"}
l!l&&r!l&&!r
00144
MC/DC0%0/2
$have->{"homedir-read"} or $have->{"world-read"}
$have->{"homedir-read"} $have->{"world-read"}
Truth table33%1/3
A or B
A= $have->{"homedir-read"}B= $have->{"world-read"}
ABresult
1X1
011
000
1447 }
1448  
1449 push @command, "--remount-ro", "/"
1450 1534 ▶ unless $have->{"world-write"};
Branch: 1 branch
BranchTrueFalseTotal
unless $have->{"world-write"} 1530 4 1534
1451  
1452 1534 push @command,
1453 "--clearenv",
1454 "--setenv", "PATH", $sandbox_path,
1455 "--setenv", "LC_ALL", "C.UTF-8",
1456 "--setenv", "PERL_BADLANG", "0",
1457 "--setenv", "HOME", $home;
1458  
1459 1534 for my $name (qw(TERM COLORTERM TERMINFO TERMINFO_DIRS NO_COLOR CLICOLOR CLICOLOR_FORCE LINES COLUMNS)) {
1460 13806 ▶ push @command, "--setenv", $name, $ENV{$name} if defined $ENV{$name};
Branch: 1 branch
BranchTrueFalseTotal
if defined $ENV{$name} 1534 12272 13806
1461 }
1462  
1463 1534 for my $entry (@environment) {
1464 185 my ($name, $value) = @$entry;
1465 185 ▶ next if $name eq "SSH_AUTH_SOCK";
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "SSH_AUTH_SOCK" 55 130 185
1466 130 ▶ $value = $ENV{$name} unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 55 75 130
1467 130 ▶ push @command, "--setenv", $name, $value if defined $value;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 130 0 130
1468 }
1469 1534 ▶ push @command, "--setenv", "SSH_AUTH_SOCK", $agent_socket if defined $agent_socket;
Branch: 1 branch
BranchTrueFalseTotal
if defined $agent_socket 144 1390 1534
1470  
1471 push @command,
1472 1534 ▶ "--chdir", defined $exec_cmd ? $workdir : $have->{"workdir-read"} ? $workdir : "/tmp",
Branch: 2 branches
BranchTrueFalseTotal
defined $exec_cmd ? : 0 1534 1534
$have->{'workdir-read'} ? : 1406 128 1534
1473 "--";
1474  
1475 @command
1476 1534 }
1477  
1478 # pass a private synthetic user entry to bubblewrap without a host passwd mount.
1479 98 ▶sub fs_passwd_fd {
Subroutine fs_passwd_fd: called CC=8 SCAR=22.6
1480 98 ▶ my ($read, $write) = AnyEvent::Util::portable_pipe
Branch: 1 branch
BranchTrueFalseTotal
() = &AnyEvent::Util::portable_pipe() or die "passwd pipe: $!\n" 98 0 98
1481 or die "passwd pipe: $!\n";
1482 98 ▶ print {$write} "sandbox:x:$<:" . POSIX::getgid () . ":Sandbox:$home:/bin/sh\n"
Branch: 1 branch
BranchTrueFalseTotal
print {$write;} "sandbox:x:$<:" . POSIX::getgid() . ":Sandbox:${home}:/bin/sh\n" or die "passwd pipe: $!\n" 98 0 98
1483 or die "passwd pipe: $!\n";
1484 98 ▶ close $write or die "passwd pipe: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
close $write or die "passwd pipe: $!\n" 98 0 98
1485  
1486 98 ▶ if (fileno ($read) != 3) {
Branch: 1 branch
BranchTrueFalseTotal
if (fileno $read != 3) 98 0 98
1487 98 ▶ POSIX::dup2 (fileno ($read), 3) == 3 or die "passwd dup2: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
POSIX::dup2(fileno $read, 3) == 3 or die "passwd dup2: $!\n" 98 0 98
1488 98 close $read;
1489 98 ▶ open $read, "<&=3" or die "passwd fd: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open $read, "<&=3" or die "passwd fd: $!\n" 98 0 98
1490 }
1491  
1492 98 ▶ defined fcntl ($read, F_SETFD, 0) or die "passwd fcntl: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
defined fcntl($read, 2, 0) or die "passwd fcntl: $!\n" 98 0 98
1493 98 $read
1494 }
1495  
1496 156 ▶if (defined $exec_cmd) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $exec_cmd) 1 155 156
1497 1 ▶ my @sandbox_grants = length $exec_cmd ? split /,/, $exec_cmd, -1 : ();
Branch: 1 branch
BranchTrueFalseTotal
length $exec_cmd ? : 0 1 1
1498 my @command = ((fs_sandbox $workdir[0], \@sandbox_grants),
1499 1 ▶ (@ARGV ? @ARGV : ($ENV{SHELL} || "/bin/sh")));
Branch: 1 branch
BranchTrueFalseTotal
@ARGV ? : 1 0 1
Condition0%0/2
$ENV{"SHELL"} or "/bin/sh"
l!l
00
MC/DC0%0/1
$ENV{"SHELL"} or "/bin/sh"
$ENV{"SHELL"}
Truth table0%0/2
A
A= $ENV{"SHELL"}
Aresult
11
00
1500 1 ▶ my $passwd_fd = fs_passwd_fd () if $bwrap;
Branch: 1 branch
BranchTrueFalseTotal
if $bwrap 0 1 1
1501  
1502 1 exec {$command[0]} @command;
1503 0 die "exec $command[0]: $!\n";
1504 }
1505  
1506 # Perl is required in the worker namespace; discover the other tools there too.
1507 155 my $probe = q{#perl
1508 use 5.008004;
1509 use Cwd ();
1510  
1511 my %test = (
1512 find => [[qw(--version)], qr/^find \(GNU findutils\)/m],
1513 grep => [[qw(--version)], qr/^grep \(GNU grep\)/m],
1514 patch => [[qw(--version)], qr/^GNU patch /m],
1515 sed => [[qw(--version)], qr/\(GNU sed\)/],
1516 );
1517  
1518 sub find_executable {
1519 my ($name) = @_;
1520  
1521 return unless length $name && $name !~ /\0/;
1522 my @path = $name =~ m{/} ? ($name)
1523 : map { (length $_ ? $_ : ".") . "/$name" } split /:/, $ENV{PATH}, -1;
1524 for (@path) {
1525 next unless -f $_ && -x _;
1526 return m{\A/} ? $_ : Cwd::getcwd () . "/$_";
1527 }
1528 undef
1529 }
1530  
1531 while (@ARGV) {
1532 my ($name, $wanted, $explicit) = splice @ARGV, 0, 3;
1533 my $path = find_executable $wanted;
1534 if ($path && !$explicit && $test{$name}) {
1535 my ($args, $match) = @{$test{$name}};
1536 my $ok = open my $fh, "-|", $path, @$args;
1537 if ($ok) {
1538 my $output = do { local $/; <$fh> };
1539 $ok = close $fh && $output =~ $match;
1540 }
1541 undef $path unless $ok;
1542 }
1543 $path ||= "";
1544 print "$path\0";
1545 }
1546 };
1547  
1548 155 my @names = qw(perl find grep patch sed git svn cvs hg);
1549 155 ▶my $perl_name = $settings{"executable.perl"} || "perl";
Condition100%2/2
$settings{'executable.perl'} || 'perl'
l!l
5996
MC/DC100%1/1
$settings{'executable.perl'} || 'perl'
$settings{'executable.perl'}
Truth table100%2/2
A
A= $settings{'executable.perl'}
Aresult
11
00
1550 155 my %program = %remote_program;
1551 155 ▶unless ($remote) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($remote) 125 30 155
1552 my @command = ($bwrap ? (fs_sandbox $workdir[0], []) : (),
1553 $perl_name, "-e", $probe,
1554 125 ▶ map { ($_, $settings{"executable.$_"} || $_, length $settings{"executable.$_"} ? 1 : 0) } @names);
Branch: 2 branches
BranchTrueFalseTotal
$bwrap ? : 121 4 125
length $settings{"executable.$_"} ? : 29 1096 1125
Condition66%2/3
$settings{"executable.$_"} || $_
l!l&&r!l&&!r
2910960
MC/DC0%0/2
$settings{"executable.$_"} || $_
$settings{"executable.$_"} $_
Truth table66%2/3
A || B
A= $settings{"executable.$_"}B= $_
ABresult
1X1
011
000
1555 125 my $pid = open my $fh, "-|";
1556 125 ▶ defined $pid or die "Perl probe fork: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $pid or die "Perl probe fork: $!\n" 125 0 125
1557  
1558 125 ▶ unless ($pid) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pid) 27 98 125
1559 27 ▶ my $passwd_fd = fs_passwd_fd () if $bwrap;
Branch: 1 branch
BranchTrueFalseTotal
if $bwrap 25 2 27
1560 27 exec {$command[0]} @command;
1561 0 warn "exec $command[0]: $!\n";
1562 0 POSIX::_exit 126;
1563 }
1564  
1565 98 my $output = do { local $/; <$fh> };
1566 98 ▶ close $fh or die "Perl '$perl_name' cannot run in the worker environment\n";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or die "Perl '${perl_name}' cannot run in the worker environment\n" 95 3 98
1567 95 my @paths = split /\0/, $output, -1;
1568 95 ▶ @paths == @names + 1 && pop @paths eq ""
Branch: 1 branch
BranchTrueFalseTotal
@paths == @names + 1 and pop @paths eq "" or die "invalid Perl executable probe response\n" 95 0 95
Condition33%1/3
@paths == @names + 1 and pop @paths eq ""
!ll&&!rl&&r
0095
MC/DC0%0/2
@paths == @names + 1 and pop @paths eq ""
@paths == @names + 1 pop @paths eq ""
Truth table33%1/3
A and B
A= @paths == @names + 1B= pop @paths eq ""
ABresult
0X0
100
111
1569 or die "invalid Perl executable probe response\n";
1570 95 @program{@names} = @paths;
1571 }
1572 125 ▶$program{perl} or die "Perl interpreter not found inside the sandbox\n";
Branch: 1 branch
BranchTrueFalseTotal
$program{"perl"} or die "Perl interpreter not found inside the sandbox\n" 125 0 125
1573 125 ($find, $grep, $patch, $perl, $sed) = @program{qw(find grep patch perl sed)};
1574 warn "$_: not detected or wrong version\n"
1575 125 for grep !$program{$_}, qw(find grep patch sed);
1576 125 %vcs_program = map { ($_ => $program{$_}) } qw(git svn cvs hg);
1577  
1578 125 ▶AE::log warn => "bubblewrap unavailable, running without sandbox"
Branch: 1 branch
BranchTrueFalseTotal
if $sandbox_mode eq "auto" and not $bwrap 2 123 125
Condition100%3/3
$sandbox_mode eq "auto" and not $bwrap
!ll&&!rl&&r
11852
MC/DC100%2/2
$sandbox_mode eq "auto" and not $bwrap
$sandbox_mode eq "auto" not $bwrap
Truth table100%3/3
A and not(B)
A= $sandbox_mode eq "auto"B= not $bwrap
ABresult
0X0
100
111
1579 if $sandbox_mode eq "auto" && !$bwrap;
1580  
1581 125 AnyEvent::detect; # proc_spawn creates child watchers after they might have died
1582  
1583 # spawn stdin/stdout and stderr handles; proc_destroy closes them and terminates the child.
1584 # the independent child watcher remains alive until the child is reaped.
1585 1123 ▶sub proc_spawn {
Subroutine proc_spawn: called CC=15 SCAR=27.4
1586 1123 my ($program, @argv) = @_;
1587  
1588 1123 my $remote_input;
1589 1123 ▶ if ($remote) {
Branch: 1 branch
BranchTrueFalseTotal
if ($remote) 106 1017 1123
1590 106 ▶ $remote_input = $remote_launcher . fs_remote_frame ($bwrap ? $home : "", $program, @argv);
Branch: 1 branch
BranchTrueFalseTotal
$bwrap ? : 102 4 106
1591 106 ($program, @argv) = (@rsh, $host, $remote_command);
1592 }
1593  
1594 1123 ▶ my ($parent, $child) = AnyEvent::Util::portable_socketpair
Branch: 1 branch
BranchTrueFalseTotal
() = &AnyEvent::Util::portable_socketpair() or die "socketpair: $!\n" 1123 0 1123
1595 or die "socketpair: $!\n";
1596 1123 ▶ my ($error, $child_error) = AnyEvent::Util::portable_pipe
Branch: 1 branch
BranchTrueFalseTotal
() = &AnyEvent::Util::portable_pipe() or die "pipe: $!\n" 1123 0 1123
1597 or die "pipe: $!\n";
1598  
1599 1123 my $pid = fork;
1600 1123 ▶ defined $pid or die "fork: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $pid or die "fork: $!\n" 1123 0 1123
1601  
1602 1123 ▶ unless ($pid) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pid) 97 1026 1123
1603 97 ▶ open STDIN, "<&", $child or POSIX::_exit 126;
Branch: 1 branch
BranchTrueFalseTotal
open STDIN, "<&", $child or POSIX::_exit(126) 97 0 97
1604 97 ▶ open STDOUT, ">&", $child or POSIX::_exit 126;
Branch: 1 branch
BranchTrueFalseTotal
open STDOUT, ">&", $child or POSIX::_exit(126) 97 0 97
1605 97 ▶ open STDERR, ">&", $child_error or POSIX::_exit 126;
Branch: 1 branch
BranchTrueFalseTotal
open STDERR, ">&", $child_error or POSIX::_exit(126) 97 0 97
1606  
1607 97 close $parent;
1608 97 close $error;
1609 97 close $child;
1610 97 close $child_error;
1611  
1612 97 ▶ my $passwd_fd = fs_passwd_fd () if $bwrap && !$remote;
Branch: 1 branch
BranchTrueFalseTotal
if $bwrap and not $remote 72 25 97
Condition100%3/3
$bwrap and not $remote
!ll&&!rl&&r
71872
MC/DC100%2/2
$bwrap and not $remote
$bwrap not $remote
Truth table100%3/3
A and not(B)
A= $bwrapB= not $remote
ABresult
0X0
100
111
1613 97 ▶ AnyEvent::Util::close_all_fds_except (0, 1, 2, ($bwrap && !$remote ? 3 : ()));
Branch: 1 branch
BranchTrueFalseTotal
$bwrap && !$remote ? : 72 25 97
Condition100%3/3
$bwrap and not $remote
!ll&&!rl&&r
71872
MC/DC100%2/2
$bwrap and not $remote
$bwrap not $remote
Truth table100%3/3
A and not(B)
A= $bwrapB= not $remote
ABresult
0X0
100
111
1614  
1615 97 exec {$program} $program, @argv;
1616 0 print STDERR "exec $program: $!\n";
1617 0 POSIX::_exit 126;
1618 }
1619  
1620 1026 close $child;
1621 1026 close $child_error;
1622  
1623 1026 my $io = AnyEvent::Handle->new (fh => $parent);
1624 1026 my $err = AnyEvent::Handle->new (fh => $error);
1625 1026 my $proc = { pid => $pid };
1626  
1627 # keep the watcher alive independently so a fatal I/O error still reaps.
1628 939 ▶ $proc->{child} = AE::child $pid, sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1629 939 $proc->{status} = $_[1];
1630 939 delete $proc->{pid};
1631 939 delete $proc->{child};
1632 939 ▶ (delete $proc->{done})->($proc->{status}) if $proc->{done};
Branch: 1 branch
BranchTrueFalseTotal
if $proc->{"done"} 939 0 939
1633 1026 };
1634  
1635 1026 $io->{proc} = $proc;
1636 1026 $io->{proc_err} = $err;
1637 1026 ▶ $io->push_write ($remote_input) if $remote;
Branch: 1 branch
BranchTrueFalseTotal
if $remote 86 940 1026
1638  
1639 1026 $io
1640 }
1641  
1642 # signal a spawned process while its pid is still owned by us.
1643 951 ▶sub proc_kill {
Subroutine proc_kill: called CC=3 SCAR=11.0
1644 951 my ($proc, $signal) = @_;
1645  
1646 951 ▶ my $pid = $proc->{pid} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $pid = $proc->{"pid"} or return 158 793 951
1647  
1648 158 ▶ $signal //= "KILL";
Condition50%1/2
$signal //= "KILL"
l!l
0158
MC/DC0%0/1
$signal //= "KILL"
$signal
Truth table50%1/2
A
A= $signal
Aresult
11
00
1649 158 kill $signal => $pid
1650 }
1651  
1652 # abandon a process and release its streams; repeated cleanup is harmless.
1653 952 ▶sub proc_destroy {
Subroutine proc_destroy: called CC=3 SCAR=11.0
1654 952 my ($io) = @_;
1655  
1656 952 ▶ proc_kill (delete $io->{proc}) if $io->{proc};
Branch: 1 branch
BranchTrueFalseTotal
if $io->{"proc"} 951 1 952
1657 952 ▶ (delete $io->{proc_err})->destroy if $io->{proc_err};
Branch: 1 branch
BranchTrueFalseTotal
if $io->{"proc_err"} 951 1 952
1658 952 $io->destroy;
1659 }
1660  
1661 # register the process's exit callback, or call it immediately if reaped.
1662 1026 ▶sub proc_on_exit {
Subroutine proc_on_exit: called CC=2 SCAR=7.1
1663 1026 my ($proc, $done) = @_;
1664  
1665 return $done->($proc->{status})
1666 1026 ▶ if defined $proc->{status};
Branch: 1 branch
BranchTrueFalseTotal
if defined $proc->{"status"} 0 1026 1026
1667  
1668 1026 $proc->{done} = $done;
1669 }
1670  
1671 # run a one-shot subprocess, leaving output interpretation to the caller.
1672 # the stream callbacks consume rbuf and may return true to terminate the child.
1673 855 ▶sub proc_run {
Subroutine proc_run: called CC=4 SCAR=14.9
1674 855 my ($req, $command, $input, $timeout, $on_stdout, $on_stderr, $done) = @_;
1675  
1676 855 my $io = proc_spawn @$command;
1677 794 my $err = $io->{proc_err};
1678 794 my $proc = $io->{proc};
1679 794 my ($open, $timed_out, $failure, $timer) = (2);
1680  
1681 2381 ▶ my $complete = sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
1682 2381 ▶ return if $open || !defined $proc->{status};
Branch: 1 branch
BranchTrueFalseTotal
if $open or not defined $proc->{"status"} 1587 794 2381
Condition100%3/3
$open or not defined $proc->{"status"}
l!l&&r!l&&!r
845742794
MC/DC100%2/2
$open or not defined $proc->{"status"}
$open not defined $proc->{"status"}
Truth table100%3/3
A or not(B)
A= $openB= not defined $proc->{"status"}
ABresult
1X1
011
000
1683 794 ▶ my $cb = $done or return;
Branch: 1 branch
BranchTrueFalseTotal
my $cb = $done or return 794 0 794
1684 794 undef $done;
1685 794 undef $timer;
1686 794 proc_destroy $io;
1687 794 ▶ return if $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"finished"} 1 793 794
1688 793 delete $req->{on_cancel};
1689 793 $cb->($proc->{status}, $timed_out, $failure);
1690 794 };
1691  
1692 1 ▶ my $stop = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1693 1 undef $timer;
1694 1 delete $req->{on_cancel};
1695 1 $open = 0;
1696 1 proc_destroy $io;
1697 1 $complete->();
1698 794 };
1699 794 $req->{on_cancel} = $stop;
1700  
1701 794 for my $stream ([$io, $on_stdout], [$err, $on_stderr]) {
1702 1588 my ($handle, $consume) = @$stream;
1703 1588 my $closed;
1704 1586 ▶ my $finish = sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
1705 1586 ▶ return if $closed++;
Branch: 1 branch
BranchTrueFalseTotal
if $closed++ 0 1586 1586
1706 1586 --$open;
1707 1586 $complete->();
1708 1588 };
1709 2897 ▶ my $read = sub {
Subroutine __ANON__: called CC=4 SCAR=17.9
1710 2897 my ($handle, $eof) = @_;
1711 2897 my $stop = eval { $consume->($handle, $eof) };
1712 2897 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 2897 2897
1713 0 ▶ $failure ||= $@;
Condition0%0/3
$failure ||= $@
l!l&&r!l&&!r
000
MC/DC0%0/2
$failure ||= $@
$failure $@
Truth table0%0/3
A ||= B
A= $failureB= $@
ABresult
1X1
011
000
1714 0 $stop = 1;
1715 }
1716 2897 ▶ proc_kill $proc if $stop;
Branch: 1 branch
BranchTrueFalseTotal
if $stop 0 2897 2897
1717 1588 };
1718 1588 ▶ $handle->on_read (sub { $read->($_[0], 0) });
Subroutine __ANON__: called CC=1 SCAR=0.0
1719 1586 ▶ $handle->on_eof (sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1720 1586 $read->($_[0], 1);
1721 1586 $finish->();
1722 1588 });
1723 0 ▶ $handle->on_error (sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
1724 0 ▶ return unless $_[1];
Branch: 1 branch
BranchTrueFalseTotal
unless $_[1] 0 0 0
1725 0 $read->($_[0], 0);
1726 0 ▶ $failure ||= "subprocess I/O: $_[2]\n" unless $timed_out;
Branch: 1 branch
BranchTrueFalseTotal
unless $timed_out 0 0 0
Condition0%0/2
$failure ||= "subprocess I/O: $_[2]\n"
l!l
00
MC/DC0%0/1
$failure ||= "subprocess I/O: $_[2]\n"
$failure
Truth table0%0/2
A
A= $failure
Aresult
11
00
1727 0 proc_kill $proc;
1728 0 $finish->();
1729 1588 });
1730 }
1731  
1732 794 my $ok = eval {
1733 794 ▶ $io->push_write ($input) if length $input;
Branch: 1 branch
BranchTrueFalseTotal
if length $input 81 713 794
1734 794 $io->push_shutdown;
1735 794 1
1736 };
1737 794 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 794 794
1738 0 my $error = $@;
1739 0 proc_destroy $io;
1740 0 die $error;
1741 }
1742  
1743 0 ▶ $timer = AE::timer $timeout, 0, sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1744 0 $timed_out = 1;
1745 0 $stop->();
1746 794 };
1747  
1748 794 proc_on_exit $proc, $complete;
1749 }
1750  
1751 # run a subprocess and collect bounded output.
1752 15 ▶sub fs_run {
Subroutine fs_run: called CC=1 SCAR=0.3
1753 15 my ($req, $command, $input, $timeout, $byte_limit, $line_limit, $done) = @_;
1754  
1755 15 my ($truncated, $line_truncated);
1756 15 my ($stdout, $stderr) = ("", "");
1757  
1758 39 ▶ my $capture = sub {
Subroutine __ANON__: called CC=10 SCAR=27.0
1759 39 my ($target, $data, $lines) = @_;
1760  
1761 39 ▶ return if $lines and $line_truncated;
Branch: 1 branch
BranchTrueFalseTotal
if $lines and $line_truncated 0 39 39
Condition66%2/3
$lines and $line_truncated
!ll&&!rl&&r
13260
MC/DC0%0/2
$lines and $line_truncated
$lines $line_truncated
Truth table66%2/3
A and B
A= $linesB= $line_truncated
ABresult
0X0
100
111
1762 39 ▶ return unless length $data;
Branch: 1 branch
BranchTrueFalseTotal
unless length $data 26 13 39
1763 13 my $remaining = $byte_limit - (length $stdout) - (length $stderr);
1764 13 ▶ $truncated = 1 if length $data > $remaining;
Branch: 1 branch
BranchTrueFalseTotal
if length $data > $remaining 0 13 13
1765 13 ▶ $$target .= substr $data, 0, $remaining
Branch: 1 branch
BranchTrueFalseTotal
if $remaining > 0 13 0 13
1766 if $remaining > 0;
1767  
1768 13 ▶ if ($lines and $line_limit and ($$target =~ tr/\n//) > $line_limit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lines and $line_limit and $$target =~ tr/\n// > $line_limit) 0 13 13
Condition66%4/6
$lines and $line_limit and $$target =~ tr/\n// > $line_limit
!ll&&!rl&&r
760
$lines and $line_limit
!ll&&!rl&&r
076
MC/DC0%0/3
$lines and $line_limit and $$target =~ tr/\n// > $line_limit
$lines $line_limit $$target =~ tr/\n// > $line_limit
Truth table50%2/4
A and B and C
A= $linesB= $line_limitC= $$target =~ tr/\n// > $line_limit
ABCresult
0XX0
10X0
1100
1111
1769 0 my $end = -1;
1770 $end = index $$target, "\n", $end + 1
1771 0 for 1 .. $line_limit;
1772 0 substr $$target, $end + 1, length $$target, "";
1773 0 $truncated = $line_truncated = 1;
1774 0 return 1
1775 }
1776  
1777 0
1778 15 };
1779  
1780 proc_run $req, $command, $input, $timeout,
1781 26 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1782 26 my ($handle) = @_;
1783 26 my $stop = $capture->(\$stdout, $handle->{rbuf}, 1);
1784 26 $handle->{rbuf} = "";
1785 26 $stop
1786 },
1787 13 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1788 13 my ($handle) = @_;
1789 13 $capture->(\$stderr, $handle->{rbuf}, 0);
1790 13 $handle->{rbuf} = "";
1791 13 0
1792 },
1793 13 ▶ sub {
Subroutine __ANON__: called CC=5 SCAR=19.2
1794 13 my ($status, $timed_out, $failure) = @_;
1795 13 ▶ return $done->(0, $failure) if $failure;
Branch: 1 branch
BranchTrueFalseTotal
if $failure 0 13 13
1796 13 ▶ $done->(1, +{
Branch: 2 branches
BranchTrueFalseTotal
$timed_out ? : 0 13 13
$truncated || $timed_out ? : 0 13 13
Condition33%1/3
$truncated or $timed_out
l!l&&r!l&&!r
0013
MC/DC0%0/2
$truncated or $timed_out
$truncated $timed_out
Truth table33%1/3
A or B
A= $truncatedB= $timed_out
ABresult
1X1
011
000
1797 stdout => $stdout,
1798 stderr => $stderr,
1799 exit => $status >> 8,
1800 signal => $status & 127,
1801 timed_out => $timed_out ? JSON::XS::true : JSON::XS::false,
1802 truncated => $truncated || $timed_out ? JSON::XS::true : JSON::XS::false,
1803 });
1804 15 };
1805 }
1806  
1807 125 my $perl_slave = q{#perl
1808 binmode STDIN;
1809 binmode STDOUT;
1810 $SIG{PIPE} = "IGNORE";
1811 $| = 1;
1812  
1813 for (;;) {
1814 4 == read STDIN, my $buf, 4
1815 or last;
1816 my $len = unpack "N", $buf;
1817 $len == read STDIN, $buf, $len
1818 or die "short perl frame\n";
1819  
1820 my @result = do {
1821 (my $source, local @ARGV) = unpack "(w/a*)*", $buf;
1822 ("+", eval $source)
1823 };
1824  
1825 @result = ("-", $@)
1826 if $@;
1827  
1828 print pack "N/a*", pack "(w/a*)*", @result
1829 or die "stdout: $!\n"
1830 }
1831 };
1832  
1833 535 ▶sub perl_frame {
Subroutine perl_frame: called CC=1 SCAR=0.0
1834 535 pack "N/a*", pack "(w/a*)*", @_
1835 }
1836  
1837 125 my $perl_worker;
1838  
1839 571 ▶sub perl_eval {
Subroutine perl_eval: called CC=6 SCAR=19.4
1840 571 my ($req, $workdir, $sandbox_grants, $source, $args, $timeout, $done) = @_;
1841  
1842 571 my @command = ((fs_sandbox $workdir, $sandbox_grants), $perl, "-e", $perl_slave);
1843 571 my $key = pack "(w/a*)*", @command;
1844 571 my $io = $perl_worker;
1845 571 undef $perl_worker;
1846  
1847 571 ▶ if ($io && ($io->{perl_key} ne $key || !$io->{proc}{pid})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($io and $io->{"perl_key"} ne $key || !$io->{"proc"}{"pid"}) 148 423 571
Condition83%5/6
$io and $io->{"perl_key"} ne $key || !$io->{"proc"}{"pid"}
!ll&&!rl&&r
120303148
$io->{"perl_key"} ne $key or not $io->{"proc"}{"pid"}
l!l&&r!l&&!r
1480303
MC/DC66%2/3
$io and $io->{"perl_key"} ne $key || !$io->{"proc"}{"pid"}
$io $io->{"perl_key"} ne $key not $io->{"proc"}{"pid"}
Truth table75%3/4
A and B or not(C)
A= $ioB= $io->{"perl_key"} ne $keyC= not $io->{"proc"}{"pid"}
ABCresult
0XX0
1000
11X1
1011
1848 148 proc_destroy $io;
1849 148 undef $io;
1850 }
1851  
1852 571 ▶ unless ($io) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($io) 268 303 571
1853 268 $io = proc_spawn @command;
1854 232 $io->{rbuf_max} = (1 << 20) + 4096;
1855 232 $io->{perl_key} = $key;
1856 232 weaken (my $this = $io);
1857  
1858 0 ▶ my $idle_destroy = sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
1859 0 ▶ my $io = $this or return;
Branch: 1 branch
BranchTrueFalseTotal
my $io = $this or return 0 0 0
1860  
1861 0 ▶ undef $perl_worker if $perl_worker && $perl_worker == $io;
Branch: 1 branch
BranchTrueFalseTotal
if $perl_worker and $perl_worker == $io 0 0 0
Condition0%0/3
$perl_worker and $perl_worker == $io
!ll&&!rl&&r
000
MC/DC0%0/2
$perl_worker and $perl_worker == $io
$perl_worker $perl_worker == $io
Truth table0%0/3
A and B
A= $perl_workerB= $perl_worker == $io
ABresult
0X0
100
111
1862 0 proc_destroy $io;
1863 232 };
1864 0 ▶ my $idle_stderr = sub { $_[0]{rbuf} = "" };
Subroutine __ANON__: not called CC=1 SCAR=1.2
1865  
1866 526 ▶ $io->{perl_idle} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1867 526 my ($io) = @_;
1868 526 my $err = $io->{proc_err};
1869  
1870 526 $io ->on_eof ($idle_destroy);
1871 526 $io ->on_error ($idle_destroy);
1872 526 $err->on_eof ($idle_destroy);
1873 526 $err->on_error ($idle_destroy);
1874 526 $err->on_read ($idle_stderr );
1875 526 $io ->on_read ($idle_destroy);
1876 232 };
1877  
1878 145 ▶ proc_on_exit $io->{proc}, sub {
Subroutine __ANON__: called CC=5 SCAR=29.7
1879 145 ▶ my $io = $this or return;
Branch: 1 branch
BranchTrueFalseTotal
my $io = $this or return 0 145 145
1880  
1881 0 ▶ $io->{perl_on_exit}->($_[0]) if $io->{perl_on_exit};
Branch: 1 branch
BranchTrueFalseTotal
if $io->{"perl_on_exit"} 0 0 0
1882 0 ▶ $idle_destroy->() if $perl_worker && $perl_worker == $io;
Branch: 1 branch
BranchTrueFalseTotal
if $perl_worker and $perl_worker == $io 0 0 0
Condition0%0/3
$perl_worker and $perl_worker == $io
!ll&&!rl&&r
000
MC/DC0%0/2
$perl_worker and $perl_worker == $io
$perl_worker $perl_worker == $io
Truth table0%0/3
A and B
A= $perl_workerB= $perl_worker == $io
ABresult
0X0
100
111
1883 232 };
1884 }
1885  
1886 535 my $err = $io->{proc_err};
1887 535 my $timer;
1888 535 my $stderr = "";
1889  
1890 535 ▶ my $finish = sub {
Subroutine __ANON__: called CC=17 SCAR=29.5
1891 535 my ($failure, $payload) = @_;
1892 535 ▶ my $cb = $done or return;
Branch: 1 branch
BranchTrueFalseTotal
my $cb = $done or return 535 0 535
1893 535 undef $done;
1894 535 undef $timer;
1895 535 delete $req->{on_cancel};
1896 535 delete $io->{perl_on_exit};
1897  
1898 535 ▶ if ($failure || defined $io->{proc}{status}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($failure or defined $io->{"proc"}{"status"}) 5 530 535
Condition66%2/3
$failure or defined $io->{"proc"}{"status"}
l!l&&r!l&&!r
50530
MC/DC50%1/2
$failure or defined $io->{"proc"}{"status"}
$failure defined $io->{"proc"}{"status"}
Truth table66%2/3
A or B
A= $failureB= defined $io->{"proc"}{"status"}
ABresult
1X1
011
000
1899 5 my $status = $io->{proc}{status};
1900 5 ▶ my $reason = $failure || "exited (exit " . ($status >> 8)
Condition50%1/2
$failure || 'exited (exit ' . ($status >> 8) . ', signal ' . ($status & 127) . ')'
l!l
50
MC/DC0%0/1
$failure || 'exited (exit ' . ($status >> 8) . ', signal ' . ($status & 127) . ')'
$failure
Truth table50%1/2
A
A= $failure
Aresult
11
00
1901 . ", signal " . ($status & 127) . ")";
1902 5 ▶ AE::log warn => "sandbox perl worker: $reason"
Branch: 1 branch
BranchTrueFalseTotal
unless $failure and $failure =~ /\Asandbox perl (?:cancelled|timed out)\n\z/u 5 0 5
Condition33%1/3
$failure and $failure =~ /\Asandbox perl (?:cancelled|timed out)\n\z/u
!ll&&!rl&&r
050
MC/DC0%0/2
$failure and $failure =~ /\Asandbox perl (?:cancelled|timed out)\n\z/u
$failure $failure =~ /\Asandbox perl (?:cancelled|timed out)\n\z/u
Truth table33%1/3
A and B
A= $failureB= $failure =~ /\Asandbox perl (?:cancelled|timed out)\n\z/u
ABresult
0X0
100
111
1903 unless $failure && $failure =~ /\Asandbox perl (?:cancelled|timed out)\n\z/;
1904 5 proc_destroy $io;
1905 return $cb->(0, $failure || "sandbox perl exited\n")
1906 5 ▶ unless $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
unless $req->{"finished"} 5 0 5
Condition50%1/2
$failure || "sandbox perl exited\n"
l!l
50
MC/DC0%0/1
$failure || "sandbox perl exited\n"
$failure
Truth table50%1/2
A
A= $failure
Aresult
11
00
1907 0 return;
1908 }
1909  
1910 530 my (@response, $error);
1911 530 my $ok = eval {
1912 530 @response = unpack "(w/a*)*", $payload;
1913 530 my $status = shift @response;
1914 530 ▶ defined $status or die "missing perl response status\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $status or die "missing perl response status\n" 528 2 530
1915 528 ▶ if ($status eq "-") {
Branch: 2 branches
BranchTrueFalseTotal
if ($status eq '-') { } 80 448 528
elsif ($status ne '+') { } 2 446 448
1916 80 $error = AnyEvent::MCP::utf8dec $response[0];
1917 } elsif ($status ne "+") {
1918 2 die "invalid perl response status\n";
1919 }
1920 1
1921 526 };
1922  
1923 530 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 4 526 530
1924 4 my $error = $@;
1925 4 AE::log warn => "sandbox perl worker: $error";
1926 4 proc_destroy $io;
1927 4 ▶ return $cb->(0, $error) unless $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
unless $req->{"finished"} 4 0 4
1928 0 return;
1929 }
1930  
1931 # the response completes the request; the interpreter remains idle.
1932 526 ▶ proc_destroy $perl_worker if $perl_worker;
Branch: 1 branch
BranchTrueFalseTotal
if $perl_worker 0 526 526
1933 526 $perl_worker = $io;
1934 526 $io->{perl_idle}->($io);
1935 526 ▶ return if $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"finished"} 0 526 526
1936 526 ▶ return $cb->(0, $error) if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 80 446 526
1937 446 $cb->(1, \@response);
1938 535 };
1939  
1940 0 ▶ $io->{perl_on_exit} = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1941 0 my ($status) = @_;
1942 0 $finish->("sandbox perl failed (exit " . ($status >> 8)
1943 . ", signal " . ($status & 127) . "): $stderr\n");
1944 535 };
1945  
1946 0 ▶ $req->{on_cancel} = sub { $finish->("sandbox perl cancelled\n") };
Subroutine __ANON__: not called CC=1 SCAR=1.2
1947 0 ▶ $io->on_eof (sub { $finish->("short perl response\n") });
Subroutine __ANON__: not called CC=1 SCAR=1.2
1948 535 ▶ $io->on_error (sub { $finish->("sandbox perl stdout: $_[2]\n") if $_[1] });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
if $_[1] 3 0 3
1949 0 ▶ $err->on_read (sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1950 0 ▶ $stderr .= substr $_[0]{rbuf}, 0, 65536 - length $stderr
Branch: 1 branch
BranchTrueFalseTotal
if length $stderr < 65536 0 0 0
1951 if length $stderr < 65536;
1952 0 $_[0]{rbuf} = "";
1953 535 });
1954 0 ▶ $err->on_eof (sub { $finish->("sandbox perl stderr closed\n") });
Subroutine __ANON__: not called CC=1 SCAR=1.2
1955 0 ▶ $err->on_error (sub { $finish->("sandbox perl stderr: $_[2]\n") if $_[1] });
Subroutine __ANON__: not called CC=2 SCAR=13.0
Branch: 1 branch
BranchTrueFalseTotal
if $_[1] 0 0 0
1956  
1957 0 ▶ $timer = AE::timer $timeout, 0, sub { $finish->("sandbox perl timed out\n") };
Subroutine __ANON__: not called CC=1 SCAR=1.2
1958 535 my $ok = eval {
1959 532 ▶ $io->push_read (packstring => "N", sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1960 532 my ($io, $payload) = @_;
1961  
1962 return $finish->("unexpected sandbox perl output\n")
1963 532 ▶ if length $io->{rbuf};
Branch: 1 branch
BranchTrueFalseTotal
if length $io->{"rbuf"} 2 530 532
1964 530 $finish->(undef, $payload);
1965 535 });
1966 535 $io->push_write (perl_frame $source, @$args);
1967 535 1
1968 };
1969 535 ▶ $finish->($@) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 535 535
1970 }
1971  
1972 # resolve a configured workdir by persistent ID or exact path.
1973 3065 ▶sub fs_workdir {
Subroutine fs_workdir: called CC=11 SCAR=24.5
1974 3065 my ($id) = @_;
1975  
1976 3065 ▶ $id = $workdir_ids->{ids}[0] if !defined $id and @workdir == 1;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $id and @workdir == 1 2941 124 3065
Condition66%2/3
not defined $id and @workdir == 1
!ll&&!rl&&r
12402941
MC/DC50%1/2
not defined $id and @workdir == 1
not defined $id @workdir == 1
Truth table66%2/3
not(A) and B
A= not defined $idB= @workdir == 1
ABresult
0X0
100
111
1977  
1978 3065 ▶ defined $id && !ref $id
Branch: 1 branch
BranchTrueFalseTotal
defined $id and not ref $id or die "select a configured workdir by ID or exact path\n" 3065 0 3065
Condition33%1/3
defined $id and not ref $id
!ll&&!rl&&r
003065
MC/DC0%0/2
defined $id and not ref $id
defined $id not ref $id
Truth table33%1/3
A and not(B)
A= defined $idB= not ref $id
ABresult
0X0
100
111
1979 or die "select a configured workdir by ID or exact path\n";
1980  
1981 3065 my $i;
1982 3065 ▶ if ($id =~ /\A[0-9]+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($id =~ /\A[0-9]+\z/u) { } 3030 35 3065
1983 3030 ($i) = grep $workdir_ids->{ids}[$_] == $id, 0 .. $#workdir;
1984 3030 ▶ defined $i or die "Unknown workdir ID '$id'\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $i or die "Unknown workdir ID '${id}'\n" 3029 1 3030
1985 } else {
1986 35 ▶ my @match = grep { $id eq $workdir_identity[$_] || $id eq $workdir[$_] } 0 .. $#workdir;
Condition100%3/3
$id eq $workdir_identity[$_] || $id eq $workdir[$_]
l!l&&r!l&&!r
141442
MC/DC100%2/2
$id eq $workdir_identity[$_] || $id eq $workdir[$_]
$id eq $workdir_identity[$_] $id eq $workdir[$_]
Truth table100%3/3
A || B
A= $id eq $workdir_identity[$_]B= $id eq $workdir[$_]
ABresult
1X1
011
000
1987 35 ▶ @match == 1 or die @match
Branch: 2 branches
BranchTrueFalseTotal
@match == 1 or die @match ? "Ambiguous configured workdir '${id}'\n" : "Unknown configured workdir '${id}'\n" 28 7 35
@match ? : 0 7 7
1988 ? "Ambiguous configured workdir '$id'\n"
1989 : "Unknown configured workdir '$id'\n";
1990 28 $i = $match[0];
1991 }
1992  
1993 3057 ▶ wantarray ? ($workdir[$i], $workdir_identity[$i]) : $workdir[$i]
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 3057 0 3057
1994 }
1995  
1996 125 my $workdir_schema = {
1997 description => "Workdir ID or configured absolute path. Get IDs/paths from cerebro-fs.workdirs. IDs are persistent.",
1998 anyOf => [
1999 { type => "integer", minimum => 1 },
2000 { type => "string", minLength => 1 },
2001 ],
2002 };
2003  
2004 sub fs_result;
2005  
2006 # command output options affect presentation, never argv or permission scope.
2007 125 my %output_schema = (
2008 grep => { type => "string", description => "Optional PCRE stdout line filter after capture; no shell." },
2009 max_lines => { type => "integer", minimum => 1, maximum => 100000, default => 2000,
2010 description => "Max stdout lines after filtering." },
2011 max_bytes => { type => "integer", minimum => 1, maximum => 1048576, default => 65536,
2012 description => "Max returned UTF-8 bytes per stream; stderr unfiltered." },
2013 );
2014  
2015 1848 ▶sub fs_output_options {
Subroutine fs_output_options: called CC=13 SCAR=36.3
2016 1848 my ($args) = @_;
2017  
2018 1848 ▶ my %options = (max_lines => $args->{max_lines} // 2000, max_bytes => $args->{max_bytes} // 65536);
Condition100%4/4
$args->{"max_lines"} // 2000
l!l
4801368
$args->{"max_bytes"} // 65536
l!l
1861662
MC/DC100%1/1
$args->{"max_lines"} // 2000
$args->{"max_lines"}
MC/DC100%1/1
$args->{"max_bytes"} // 65536
$args->{"max_bytes"}
Truth table100%2/2
A
A= $args->{"max_lines"}
Aresult
11
00
Truth table100%2/2
A
A= $args->{"max_bytes"}
Aresult
11
00
2019 1848 for my $name (qw(max_lines max_bytes)) {
2020 $options{$name} =~ /\A[0-9]+\z/ && $options{$name} >= 1
2021 && $options{$name} <= $output_schema{$name}{maximum}
2022 3696 ▶ or die "invalid $name\n";
Branch: 1 branch
BranchTrueFalseTotal
$options{$name} =~ /\A[0-9]+\z/u and $options{$name} >= 1 and $options{$name} <= $output_schema{$name}{"maximum"} or die "invalid $name\n" 3660 36 3696
Condition66%4/6
$options{$name} =~ /\A[0-9]+\z/u and $options{$name} >= 1 and $options{$name} <= $output_schema{$name}{"maximum"}
!ll&&!rl&&r
3603660
$options{$name} =~ /\A[0-9]+\z/u and $options{$name} >= 1
!ll&&!rl&&r
0363660
MC/DC33%1/3
$options{$name} =~ /\A[0-9]+\z/u and $options{$name} >= 1 and $options{$name} <= $output_schema{$name}{"maximum"}
$options{$name} =~ /\A[0-9]+\z/u $options{$name} >= 1 $options{$name} <= $output_schema{$name}{"maximum"}
Truth table50%2/4
A and B and C
A= $options{$name} =~ /\A[0-9]+\z/uB= $options{$name} >= 1C= $options{$name} <= $output_schema{$name}{"maximum"}
ABCresult
0XX0
10X0
1100
1111
2023 }
2024  
2025 1812 ▶ if (exists $args->{grep}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args->{"grep"}) 0 1812 1812
2026 defined $args->{grep} && !ref $args->{grep} && $args->{grep} !~ /\0/
2027 0 ▶ && length $args->{grep} <= 65536
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{"grep"} and not ref $args->{"grep"} and not $args->{"grep"} =~ /\0/u and length $args->{"grep"} <= 65536 or die "grep must be a string without NUL, at most 65536 characters\n" 0 0 0
Condition0%0/9
defined $args->{"grep"} and not ref $args->{"grep"} and not $args->{"grep"} =~ /\0/u and length $args->{"grep"} <= 65536
!ll&&!rl&&r
000
defined $args->{"grep"} and not ref $args->{"grep"} and not $args->{"grep"} =~ /\0/u
!ll&&!rl&&r
000
defined $args->{"grep"} and not ref $args->{"grep"}
!ll&&!rl&&r
000
MC/DC0%0/4
defined $args->{"grep"} and not ref $args->{"grep"} and not $args->{"grep"} =~ /\0/u and length $args->{"grep"} <= 65536
defined $args->{"grep"} not ref $args->{"grep"} not $args->{"grep"} =~ /\0/u length $args->{"grep"} <= 65536
Truth table0%0/5
A and not(B) and not(C) and D
A= defined $args->{"grep"}B= not ref $args->{"grep"}C= not $args->{"grep"} =~ /\0/uD= length $args->{"grep"} <= 65536
ABCDresult
0XXX0
10XX0
110X0
11100
11111
2028 or die "grep must be a string without NUL, at most 65536 characters\n";
2029 0 ▶ $grep or die "output filtering needs GNU grep\n";
Branch: 1 branch
BranchTrueFalseTotal
$grep or die "output filtering needs GNU grep\n" 0 0 0
2030 0 $options{grep} = AnyEvent::MCP::utf8enc $args->{grep};
2031 }
2032  
2033 1812 \%options
2034 }
2035  
2036 # clipping a UTF-8 stream may leave at most three bytes of an incomplete character.
2037 1544 ▶sub fs_output_text {
Subroutine fs_output_text: called CC=4 SCAR=13.9
2038 1544 my ($bytes, $cut) = @_;
2039  
2040 1544 ▶ for (0 .. ($cut ? 3 : 0)) {
Branch: 1 branch
BranchTrueFalseTotal
$cut ? : 110 1434 1544
2041 1580 my $text = $bytes;
2042 1580 ▶ return $text if utf8::decode $text;
Branch: 1 branch
BranchTrueFalseTotal
if utf8::decode($text) 1544 36 1580
2043 36 chop $bytes;
2044 }
2045  
2046 0 die "command output is not UTF-8\n";
2047 }
2048  
2049 # preserve child status while bounding capture and, separately, returned output.
2050 834 ▶sub fs_command {
Subroutine fs_command: called CC=4 SCAR=16.7
2051 834 my ($req, $workdir, $grants, $argv, $input, $timeout, $options, $cwd) = @_;
2052  
2053 # check the actual directory inside the worker, after resolving symlinks.
2054 834 ▶ $argv = [$perl, "-MCwd", "-e", q{
Branch: 1 branch
BranchTrueFalseTotal
if defined $cwd 532 302 834
2055 my $workdir = shift;
2056 chdir shift or die "VCS chdir: $!\n";
2057 my $cwd = Cwd::getcwd ();
2058 defined $cwd && ($workdir eq "/" || $cwd eq $workdir || (index $cwd, "$workdir/") == 0)
2059 or die "VCS cwd must resolve within the selected workdir\n";
2060 exec {$ARGV[0]} @ARGV;
2061 die "VCS exec: $!\n";
2062 }, $workdir, $cwd, @$argv] if defined $cwd;
2063  
2064 834 ▶ my @command = ((fs_sandbox $workdir, $grants),
Branch: 2 branches
BranchTrueFalseTotal
$bwrap ? : 825 6 831
$remote ? : 0 6 6
2065 $bwrap ? @$argv
2066 : ($remote ? $perl : $^X, "-e", 'chdir shift or die "chdir: $!"; exec @ARGV; die "exec: $!";', $workdir, @$argv));
2067 831 my ($stdout, $stderr) = ("", "");
2068 831 my ($stdout_cut, $stderr_cut);
2069  
2070 2834 ▶ my $capture = sub {
Subroutine __ANON__: called CC=3 SCAR=11.2
2071 2834 my ($handle, $out, $cut) = @_;
2072 2834 my $remaining = 1048576 - length $$out;
2073 2834 ▶ $$cut = 1 if length $handle->{rbuf} > $remaining;
Branch: 1 branch
BranchTrueFalseTotal
if length $handle->{"rbuf"} > $remaining 0 2834 2834
2074 2834 ▶ $$out .= substr $handle->{rbuf}, 0, $remaining if $remaining > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $remaining > 0 2834 0 2834
2075 2834 $handle->{rbuf} = "";
2076 2834 0
2077 831 };
2078  
2079 proc_run $req, \@command, $input, $timeout,
2080 1501 ▶ sub { $capture->($_[0], \$stdout, \$stdout_cut) },
Subroutine __ANON__: called CC=1 SCAR=0.0
2081 1333 ▶ sub { $capture->($_[0], \$stderr, \$stderr_cut) },
Subroutine __ANON__: called CC=1 SCAR=0.0
2082 772 ▶ sub {
Subroutine __ANON__: called CC=8 SCAR=28.0
2083 772 my ($status, $timed_out, $failure) = @_;
2084 772 ▶ return $req->error ($failure) if $failure;
Branch: 1 branch
BranchTrueFalseTotal
if $failure 0 772 772
2085  
2086 772 ▶ my $result = {
Branch: 2 branches
BranchTrueFalseTotal
$timed_out ? : 0 772 772
$stdout_cut || $stderr_cut || $timed_out ? : 0 772 772
Condition33%2/6
$stdout_cut or $stderr_cut or $timed_out
l!l&&r!l&&!r
00772
$stdout_cut or $stderr_cut
l!l&&r!l&&!r
00772
MC/DC0%0/3
$stdout_cut or $stderr_cut or $timed_out
$stdout_cut $stderr_cut $timed_out
Truth table25%1/4
A or B or C
A= $stdout_cutB= $stderr_cutC= $timed_out
ABCresult
1XX1
01X1
0011
0000
2087 exit => $status >> 8, signal => $status & 127,
2088 timed_out => $timed_out ? JSON::XS::true : JSON::XS::false,
2089 capture_truncated => $stdout_cut || $stderr_cut || $timed_out ? JSON::XS::true : JSON::XS::false,
2090 };
2091  
2092 772 ▶ my $finish = sub {
Subroutine __ANON__: called CC=12 SCAR=25.0
2093 772 my $ok = eval {
2094 772 ▶ $stdout_cut = 1 if length $stdout > $options->{max_bytes};
Branch: 1 branch
BranchTrueFalseTotal
if length $stdout > $options->{"max_bytes"} 73 699 772
2095 772 ▶ $stderr_cut = 1 if length $stderr > $options->{max_bytes};
Branch: 1 branch
BranchTrueFalseTotal
if length $stderr > $options->{"max_bytes"} 37 735 772
2096 772 my $out = fs_output_text (substr ($stdout, 0, $options->{max_bytes}), $stdout_cut);
2097 772 my $err = fs_output_text (substr ($stderr, 0, $options->{max_bytes}), $stderr_cut);
2098 772 my @lines = split /(?<=\n)/, $out;
2099 772 ▶ if (@lines > $options->{max_lines}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@lines > $options->{"max_lines"}) 232 540 772
2100 232 splice @lines, $options->{max_lines};
2101 232 $out = join "", @lines;
2102 232 $stdout_cut = 1;
2103 }
2104 772 @$result{qw(stdout stderr)} = ($out, $err);
2105 772 ▶ $result->{stdout_truncated} = $stdout_cut || $timed_out ? JSON::XS::true : JSON::XS::false;
Branch: 1 branch
BranchTrueFalseTotal
$stdout_cut || $timed_out ? : 305 467 772
Condition66%2/3
$stdout_cut or $timed_out
l!l&&r!l&&!r
3050467
MC/DC50%1/2
$stdout_cut or $timed_out
$stdout_cut $timed_out
Truth table66%2/3
A or B
A= $stdout_cutB= $timed_out
ABresult
1X1
011
000
2106 772 ▶ $result->{stderr_truncated} = $stderr_cut || $timed_out ? JSON::XS::true : JSON::XS::false;
Branch: 1 branch
BranchTrueFalseTotal
$stderr_cut || $timed_out ? : 37 735 772
Condition66%2/3
$stderr_cut or $timed_out
l!l&&r!l&&!r
370735
MC/DC50%1/2
$stderr_cut or $timed_out
$stderr_cut $timed_out
Truth table66%2/3
A or B
A= $stderr_cutB= $timed_out
ABresult
1X1
011
000
2107 772 ▶ $result->{truncated} = $stdout_cut || $stderr_cut || $timed_out ? JSON::XS::true : JSON::XS::false;
Branch: 1 branch
BranchTrueFalseTotal
$stdout_cut || $stderr_cut || $timed_out ? : 305 467 772
Condition66%4/6
$stdout_cut or $stderr_cut or $timed_out
l!l&&r!l&&!r
3050467
$stdout_cut or $stderr_cut
l!l&&r!l&&!r
3050467
MC/DC33%1/3
$stdout_cut or $stderr_cut or $timed_out
$stdout_cut $stderr_cut $timed_out
Truth table50%2/4
A or B or C
A= $stdout_cutB= $stderr_cutC= $timed_out
ABCresult
1XX1
01X1
0011
0000
2108 772 1
2109 };
2110 772 ▶ return $req->error ($@) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 772 772
2111 772 $req->reply (fs_result $result, exists $result->{filter_error});
2112 772 };
2113  
2114 772 ▶ return $finish->() unless exists $options->{grep};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $options->{"grep"} 772 0 772
2115  
2116 {
2117 0 my $ok = eval { $stdout = AnyEvent::MCP::utf8enc (fs_output_text $stdout, $stdout_cut); 1 };
2118 0 ▶ return $req->error ($@) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
2119 }
2120  
2121 # regex execution stays in a timed worker, outside the broker's event loop.
2122 0 my @filter = ((fs_sandbox $workdir, $grants), $grep, "-aP", "--", $options->{grep});
2123 0 ▶ fs_run $req, \@filter, $stdout, 5, 1048576, 0, sub {
Subroutine __ANON__: not called CC=8 SCAR=42.8
2124 0 my ($success, $filtered) = @_;
2125 0 ▶ if (!$success || $filtered->{exit} > 1 || $filtered->{signal} || $filtered->{timed_out}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $success or $filtered->{'exit'} > 1 or $filtered->{'signal'} or $filtered->{'timed_out'}) { } 0 0 0
Condition0%0/9
not $success or $filtered->{"exit"} > 1 or $filtered->{"signal"} or $filtered->{"timed_out"}
l!l&&r!l&&!r
000
not $success or $filtered->{"exit"} > 1 or $filtered->{"signal"}
l!l&&r!l&&!r
000
not $success or $filtered->{"exit"} > 1
l!l&&r!l&&!r
000
MC/DC0%0/4
not $success or $filtered->{"exit"} > 1 or $filtered->{"signal"} or $filtered->{"timed_out"}
not $success $filtered->{"exit"} > 1 $filtered->{"signal"} $filtered->{"timed_out"}
Truth table0%0/5
not(A) or B or C or D
A= not $successB= $filtered->{"exit"} > 1C= $filtered->{"signal"}D= $filtered->{"timed_out"}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
2126 0 ▶ my $error = $success ? $filtered->{stderr} : $filtered;
Branch: 1 branch
BranchTrueFalseTotal
$success ? : 0 0 0
2127 0 ▶ $error = eval { fs_output_text (substr ($error, 0, 4096), 1) } || "no diagnostic";
Condition0%0/2
eval { do { fs_output_text(substr($error, 0, 4096), 1) } } || 'no diagnostic'
l!l
00
MC/DC0%0/1
eval { do { fs_output_text(substr($error, 0, 4096), 1) } } || 'no diagnostic'
eval { do { fs_output_text(substr($error, 0, 4096), 1) } }
Truth table0%0/2
A
A= eval { do { fs_output_text(substr($error, 0, 4096), 1) } }
Aresult
11
00
2128 0 $result->{filter_error} = "stdout filter failed: $error";
2129 0 $stdout = "";
2130 0 $stdout_cut = 1;
2131 } else {
2132 0 $stdout = $filtered->{stdout};
2133 0 ▶ $stdout_cut ||= $filtered->{truncated};
Condition0%0/3
$stdout_cut ||= $filtered->{"truncated"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$stdout_cut ||= $filtered->{"truncated"}
$stdout_cut $filtered->{"truncated"}
Truth table0%0/3
A ||= B
A= $stdout_cutB= $filtered->{"truncated"}
ABresult
1X1
011
000
2134 }
2135 0 $finish->();
2136 0 };
2137 831 };
2138 }
2139  
2140 # wrap raw text as an MCP text result.
2141 1500 ▶sub fs_text_result {
Subroutine fs_text_result: called CC=2 SCAR=7.0
2142 1500 my ($text, $failed) = @_;
2143  
2144 1500 my $response = {
2145 content => [{
2146 type => "text",
2147 text => $text,
2148 }],
2149 };
2150  
2151 1500 ▶ $response->{isError} = JSON::XS::true if $failed;
Branch: 1 branch
BranchTrueFalseTotal
if $failed 0 1500 1500
2152  
2153 1500 $response
2154 }
2155  
2156 # wrap a Perl value as an MCP text result.
2157 1291 ▶sub fs_result {
Subroutine fs_result: called CC=1 SCAR=0.0
2158 1291 my ($result, $failed) = @_;
2159  
2160 1291 my $response = fs_text_result (JSON::XS->new->encode ($result), $failed);
2161 1291 $response->{structuredContent} = $result;
2162  
2163 1291 $response
2164 }
2165  
2166 mcp_tool workdirs =>
2167 "List workdirs, VCS markers (remote snapshot at startup), available VCS clients, sandbox grants, trusted mounts, runtime paths.",
2168 {
2169 type => "object",
2170 properties => {},
2171 additionalProperties => JSON::XS::false,
2172 },
2173 268 ▶ sub {
Subroutine __ANON__: called CC=7 SCAR=19.9
2174 268 my ($req, $args) = @_;
2175  
2176 268 AE::log debug => "fs workdirs";
2177  
2178 # report metadata markers, not an inferred repository for the tree.
2179 268 my %marker = (cvs => "CVS", git => ".git", hg => ".hg", svn => ".svn");
2180 my %workdir_vcs = map {
2181 268 my $i = $_;
2182 ($workdir_identity[$i] => $remote ? $remote_vcs_marker[$i] : [grep {
2183 278 ▶ lstat "$workdir[$i]/$marker{$_}" && (-d _ || -l _ || ($_ eq "git" && -f _))
Branch: 1 branch
BranchTrueFalseTotal
$remote ? : 31 247 278
Condition58%7/12
lstat "$workdir[$i]/$marker{$_}" && (-d _ || -l _ || $_ eq 'git' && -f _)
!ll&&!rl&&r
6520336
-d _ or -l _ or $_ eq "git" and -f _
l!l&&r!l&&!r
294420
-d _ or -l _
l!l&&r!l&&!r
294042
$_ eq "git" and -f _
!ll&&!rl&&r
0042
MC/DC20%1/5
lstat "$workdir[$i]/$marker{$_}" && (-d _ || -l _ || $_ eq 'git' && -f _)
lstat "$workdir[$i]/$marker{$_}" -d _ -l _ $_ eq "git" -f _
Truth table50%3/6
A && B or C or D and E
A= lstat "$workdir[$i]/$marker{$_}"B= -d _C= -l _D= $_ eq "git"E= -f _
ABCDEresult
0XXXX0
1000X0
100100
11XXX1
101XX1
100111
2184 } sort keys %marker])
2185 } 0 .. $#workdir;
2186  
2187 $req->reply (fs_result +{
2188 ($remote ? (host => $host, rsh => $rsh) : ()),
2189 278 workdirs => { map { $workdir_ids->{ids}[$_] => $workdir_identity[$_] } reverse 0 .. $#workdir },
2190 278 resolved_workdirs => { map { $workdir_ids->{ids}[$_] => $workdir[$_] } 0 .. $#workdir },
2191 workdir_vcs => \%workdir_vcs,
2192 268 ▶ vcs_backends => [sort grep defined $vcs_program{$_}, keys %vcs_program],
Branch: 1 branch
BranchTrueFalseTotal
$remote ? : 31 237 268
2193 umask => (sprintf "%04o", $umask),
2194 runtime_paths => \@runtime_path,
2195 mounts => \@mount,
2196 sandbox_grants => \%sandbox_grant,
2197 exec_default_sandbox_grants => \@exec_default_sandbox_grants,
2198 unavailable_sandbox_grants => ["host-proc"],
2199 });
2200 }
2201 125 ;
2202  
2203 # escape a pathname for compact line-oriented text output.
2204 24 ▶sub escape_path {
Subroutine escape_path: called CC=1 SCAR=0.0
2205 24 my ($text) = @_;
2206  
2207 24 $text =~ s/\\/\\\\/g;
2208 24 $text =~ s/\n/\\n/g;
2209 24 $text
2210 }
2211  
2212 16 ▶sub format_iec_number {
Subroutine format_iec_number: called CC=4 SCAR=16.9
2213 16 my ($number) = @_;
2214  
2215 16 for my $suffix ("", qw(k M G T P)) {
2216 16 ▶ return "$number$suffix" if $number < 1024 or $suffix eq "P";
Branch: 1 branch
BranchTrueFalseTotal
if $number < 1024 or $suffix eq "P" 16 0 16
Condition33%1/3
$number < 1024 or $suffix eq "P"
l!l&&r!l&&!r
1600
MC/DC0%0/2
$number < 1024 or $suffix eq "P"
$number < 1024 $suffix eq "P"
Truth table33%1/3
A or B
A= $number < 1024B= $suffix eq "P"
ABresult
1X1
011
000
2217 0 $number = int (($number + 512) / 1024);
2218 }
2219 }
2220  
2221 24 ▶sub fs_find_relative {
Subroutine fs_find_relative: called CC=3 SCAR=11.1
2222 24 my ($base, $path) = @_;
2223  
2224 24 ▶ return "" if $path eq $base;
Branch: 1 branch
BranchTrueFalseTotal
if $path eq $base 8 16 24
2225 16 ▶ substr $path, (length $base) + ($base eq "/" ? 0 : 1)
Branch: 1 branch
BranchTrueFalseTotal
$base eq '/' ? : 0 16 16
2226 }
2227  
2228 8 ▶sub format_path_listing {
Subroutine format_path_listing: called CC=9 SCAR=23.6
2229 8 my ($base, $record, $truncated) = @_;
2230  
2231 8 my (@line, $directory);
2232  
2233 8 for my $record (sort { $a->[2] cmp $b->[2] } @$record) {
2234 24 my ($type, $size, $full_path) = @$record;
2235 24 my $relative = fs_find_relative $base, $full_path;
2236  
2237 24 ▶ if ($type eq "d") {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "d") 8 16 24
2238 8 push @line, "/" . (escape_path $relative);
2239 8 $directory = $relative;
2240 8 next;
2241 }
2242  
2243 16 my ($dir, $name);
2244  
2245 16 ▶ if (!length $relative) {
Branch: 1 branch
BranchTrueFalseTotal
if (not length $relative) { } 0 16 16
2246 0 ($name) = $full_path =~ m{([^/]*)\z};
2247 } else {
2248 16 ($dir, $name) = $relative =~ m{\A(?:(.*)/)?([^/]*)\z};
2249 16 ▶ $dir //= "";
Condition50%1/2
$dir //= ""
l!l
016
MC/DC0%0/1
$dir //= ""
$dir
Truth table50%1/2
A
A= $dir
Aresult
11
00
2250  
2251 16 ▶ if (!defined $directory or $directory ne $dir) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $directory or $directory ne $dir) 0 16 16
Condition33%1/3
not defined $directory or $directory ne $dir
l!l&&r!l&&!r
0016
MC/DC0%0/2
not defined $directory or $directory ne $dir
not defined $directory $directory ne $dir
Truth table33%1/3
not(A) or B
A= not defined $directoryB= $directory ne $dir
ABresult
1X1
011
000
2252 0 push @line, "/" . (escape_path $dir);
2253 0 $directory = $dir;
2254 }
2255 }
2256  
2257 16 $name = escape_path $name;
2258 16 ▶ push @line, $type eq "f"
Branch: 1 branch
BranchTrueFalseTotal
$type eq 'f' ? : 16 0 16
2259 ? (join "\t", $type, (format_iec_number $size), $name)
2260 : (join "\t", $type, $name);
2261 }
2262  
2263 8 ▶ push @line, "!truncated" if $truncated;
Branch: 1 branch
BranchTrueFalseTotal
if $truncated 0 8 8
2264  
2265 8 join "", map "$_\n", @line
2266 }
2267  
2268 9 ▶sub fs_list_find {
Subroutine fs_list_find: called CC=8 SCAR=25.3
2269 9 my ($req, $args, $recurse) = @_;
2270  
2271 9 ▶ my $tool = $recurse ? "find" : "list";
Branch: 1 branch
BranchTrueFalseTotal
$recurse ? : 0 9 9
2272  
2273 9 my ($workdir, $identity) = fs_workdir $args->{workdir};
2274 9 ▶ my $path = fs_path $workdir, length $args->{path} ? $args->{path} : ".";
Branch: 1 branch
BranchTrueFalseTotal
length $args->{'path'} ? : 9 0 9
2275 9 ▶ my $limit = $args->{limit} // 200;
Condition50%1/2
$args->{"limit"} // 200
l!l
09
MC/DC0%0/1
$args->{"limit"} // 200
$args->{"limit"}
Truth table50%1/2
A
A= $args->{"limit"}
Aresult
11
00
2276 9 ▶ $limit <= 1000
Branch: 1 branch
BranchTrueFalseTotal
$limit <= 1000 or die "invalid limit\n" 9 0 9
2277 or die "invalid limit\n";
2278  
2279 my $granted = fs_require_paths ($req, $workdir, $identity, [$path], "read",
2280 9 ▶ $args->{reason} // "$tool $path");
Condition50%1/2
$args->{"reason"} // "$tool $path"
l!l
09
MC/DC0%0/1
$args->{"reason"} // "$tool $path"
$args->{"reason"}
Truth table50%1/2
A
A= $args->{"reason"}
Aresult
11
00
2281  
2282 9 ▶ if ($recurse) {
Branch: 1 branch
BranchTrueFalseTotal
if ($recurse) { } 0 9 9
2283 0 AE::log debug => join " ", "fs", $tool, $path, (substr $args->{name}, 0, 40);
2284 } else {
2285 9 AE::log debug => "fs $tool $path";
2286 }
2287  
2288 9 my $find_path = AnyEvent::MCP::utf8enc $path;
2289 9 my @command = ((fs_sandbox $workdir, $granted), $find, $find_path);
2290  
2291 9 ▶ if ($recurse) {
Branch: 1 branch
BranchTrueFalseTotal
if ($recurse) { } 0 9 9
2292 0 my $needle = AnyEvent::MCP::utf8enc $args->{name};
2293 0 $needle =~ s/([\\*?\[])/\\$1/g;
2294 0 push @command, "!", "-type", "d", "-name", "*$needle*";
2295 } else {
2296 9 push @command, "-maxdepth", "1";
2297 }
2298  
2299 9 push @command, "-printf", q{%y\0%s\0%p\0};
2300  
2301 9 my (@record, $seen, $truncated, $failure);
2302 9 my $stderr = "";
2303  
2304 proc_run $req, \@command, "", 30,
2305 16 ▶ sub {
Subroutine __ANON__: called CC=13 SCAR=32.8
2306 16 my ($handle, $eof) = @_;
2307  
2308 16 ▶ while (!$failure and !$truncated
Branch: 1 branch
BranchTrueFalseTotal
if (not $failure || $truncated and $handle->{"rbuf"} =~ s/\A([^\0]*)\0([^\0]*)\0([^\0]*)\0//su) 24 16 40
Condition50%3/6
not $failure || $truncated and $handle->{"rbuf"} =~ s/\A([^\0]*)\0([^\0]*)\0([^\0]*)\0//su
!ll&&!rl&&r
01624
$failure || $truncated
l!l&&r!l&&!r
0040
MC/DC33%1/3
not $failure || $truncated and $handle->{"rbuf"} =~ s/\A([^\0]*)\0([^\0]*)\0([^\0]*)\0//su
$failure $truncated $handle->{"rbuf"} =~ s/\A([^\0]*)\0([^\0]*)\0([^\0]*)\0//su
Truth table50%2/4
not(A || B) and C
A= $failureB= $truncatedC= $handle->{"rbuf"} =~ s/\A([^\0]*)\0([^\0]*)\0([^\0]*)\0//su
ABCresult
1XX0
01X0
0000
0011
2309 and $handle->{rbuf} =~ s/\A([^\0]*)\0([^\0]*)\0([^\0]*)\0//s) {
2310 24 my ($type, $size, $raw_path) = ($1, $2, $3);
2311 24 my $full_path = eval { AnyEvent::MCP::utf8dec $raw_path };
2312  
2313 24 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 24 24
2314 0 $failure = "$tool returned a non-UTF-8 pathname\n";
2315 0 last;
2316 }
2317  
2318 24 ▶ if (++$seen > $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (++$seen > $limit) 0 24 24
2319 0 $truncated = 1;
2320 0 last;
2321 }
2322  
2323 24 push @record, [$type, $size, $full_path];
2324 }
2325  
2326 $failure ||= "incomplete $tool output\n"
2327 16 ▶ if $eof && length $handle->{rbuf} && !$truncated;
Branch: 1 branch
BranchTrueFalseTotal
if $eof and length $handle->{"rbuf"} and not $truncated 0 16 16
Condition37%3/8
$eof and length $handle->{"rbuf"} and not $truncated
!ll&&!rl&&r
1600
$eof and length $handle->{"rbuf"}
!ll&&!rl&&r
880
$failure ||= "incomplete $tool output\n"
l!l
00
MC/DC0%0/3
$eof and length $handle->{"rbuf"} and not $truncated
$eof length $handle->{"rbuf"} not $truncated
MC/DC0%0/1
$failure ||= "incomplete $tool output\n"
$failure
Truth table50%2/4
A and B and not(C)
A= $eofB= length $handle->{"rbuf"}C= not $truncated
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/2
A
A= $failure
Aresult
11
00
2328 16 ▶ $handle->{rbuf} = "" if $failure or $truncated;
Branch: 1 branch
BranchTrueFalseTotal
if $failure or $truncated 0 16 16
Condition33%1/3
$failure or $truncated
l!l&&r!l&&!r
0016
MC/DC0%0/2
$failure or $truncated
$failure $truncated
Truth table33%1/3
A or B
A= $failureB= $truncated
ABresult
1X1
011
000
2329 16 ▶ $failure || $truncated
Branch: 1 branch
BranchTrueFalseTotal
$failure or $truncated 0 16 16
2330 },
2331 8 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
2332 8 my ($handle) = @_;
2333 8 my $remaining = 65536 - length $stderr;
2334 8 ▶ $stderr .= substr $handle->{rbuf}, 0, $remaining if $remaining > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $remaining > 0 8 0 8
2335 8 $handle->{rbuf} = "";
2336 8 0
2337 },
2338 8 ▶ sub {
Subroutine __ANON__: called CC=11 SCAR=33.5
2339 8 my ($status, $timed_out, $io_failure) = @_;
2340 8 ▶ return if $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"finished"} 0 8 8
2341  
2342 8 my $result;
2343 8 my $ok = eval {
2344 8 ▶ die "$tool timed out\n" if $timed_out;
Branch: 1 branch
BranchTrueFalseTotal
if $timed_out 0 8 8
2345 8 ▶ die $failure || $io_failure if $failure || $io_failure;
Branch: 1 branch
BranchTrueFalseTotal
if $failure or $io_failure 0 8 8
Condition16%1/6
$failure or $io_failure
l!l&&r!l&&!r
008
$failure || $io_failure
l!l&&r!l&&!r
000
MC/DC0%0/2
$failure or $io_failure
$failure $io_failure
MC/DC0%0/2
$failure || $io_failure
$failure $io_failure
Truth table33%1/3
A or B
A= $failureB= $io_failure
ABresult
1X1
011
000
Truth table0%0/3
A || B
A= $failureB= $io_failure
ABresult
1X1
011
000
2346  
2347 8 ▶ if (($status >> 8 or $status & 127) and !$truncated) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status >> 8 || $status & 127 and not $truncated) 0 8 8
Condition33%2/6
$status >> 8 || $status & 127 and not $truncated
!ll&&!rl&&r
800
$status >> 8 or $status & 127
l!l&&r!l&&!r
008
MC/DC0%0/3
$status >> 8 || $status & 127 and not $truncated
$status >> 8 $status & 127 not $truncated
Truth table20%1/5
A or B and not(C)
A= $status >> 8B= $status & 127C= not $truncated
ABCresult
00X0
1X00
0100
1X11
0111
2348 0 my $error = eval { AnyEvent::MCP::utf8dec $stderr };
2349 0 ▶ $error = "non-UTF-8 error output" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
2350 0 die "$tool failed (exit " . ($status >> 8) . ", signal " . ($status & 127) . "): $error\n";
2351 }
2352  
2353 8 $result = fs_text_result (format_path_listing $path, \@record, $truncated);
2354 8 1
2355 };
2356  
2357 8 ▶ if ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ok) { } 8 0 8
2358 8 $req->reply ($result);
2359 } else {
2360 0 $req->error ($@);
2361 }
2362 9 };
2363 }
2364  
2365 $find && mcp_tool list =>
2366 "List immediate entries; no symlink following. "
2367 . "Text format: /relative-directory headers; f<TAB>approx-size<TAB>name for files; "
2368 . "TYPE<TAB>name for l/p/s/b/c/? nodes. "
2369 . "Size suffixes k/M/G/T/P use IEC powers (1024); "
2370 . "!truncated means limit exceeded. Names escape backslash/newline.",
2371 {
2372 type => "object",
2373 properties => {
2374 path => {
2375 type => "string",
2376 description => "Directory; omitted/empty = .",
2377 },
2378 limit => {
2379 type => "integer",
2380 minimum => 1,
2381 maximum => 1000,
2382 default => 200,
2383 },
2384 workdir => $workdir_schema,
2385 reason => {
2386 type => "string",
2387 description => "Why access needed.",
2388 },
2389 },
2390 additionalProperties => JSON::XS::false,
2391 },
2392 9 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2393 9 fs_list_find $_[0], $_[1], 0
2394 }
2395 125 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$find and mcp_tool("list", "List immediate entries; no symlink following. Text format: /relative-directory headers; f<TAB>approx-size<TAB>name for files; TYPE<TAB>name for l/p/s/b/c/? nodes. Size suffixes k/M/G/T/P use IEC powers (1024); !truncated means limit exceeded. Names escape backslash/newline.", {"type", "object", "properties", {"path", {"type", "string", "description", "Directory; omitted/empty = ."}, "limit", {"type", "integer", "minimum", 1, "maximum", 1000, "default", 200}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "additionalProperties", &JSON::XS::false()}, sub { fs_list_find($_[0], $_[1], 0); } ) 125 0 125
2396  
2397 $find && mcp_tool find =>
2398 "Find non-directory entries recursively by literal basename substring; no symlink following. Output as list.",
2399 {
2400 type => "object",
2401 properties => {
2402 path => {
2403 type => "string",
2404 description => "Search root; omitted/empty = .",
2405 },
2406 name => {
2407 type => "string",
2408 minLength => 1,
2409 description => "Literal basename substring.",
2410 },
2411 limit => {
2412 type => "integer",
2413 minimum => 1,
2414 maximum => 1000,
2415 default => 200,
2416 },
2417 workdir => $workdir_schema,
2418 reason => {
2419 type => "string",
2420 description => "Why access needed.",
2421 },
2422 },
2423 required => ["name"],
2424 additionalProperties => JSON::XS::false,
2425 },
2426 0 ▶ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2427 0 fs_list_find $_[0], $_[1], 1
2428 }
2429 125 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$find and mcp_tool("find", "Find non-directory entries recursively by literal basename substring; no symlink following. Output as list.", {"type", "object", "properties", {"path", {"type", "string", "description", "Search root; omitted/empty = ."}, "name", {"type", "string", "minLength", 1, "description", "Literal basename substring."}, "limit", {"type", "integer", "minimum", 1, "maximum", 1000, "default", 200}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "required", ["name"], "additionalProperties", &JSON::XS::false()}, sub { fs_list_find($_[0], $_[1], 1); } ) 125 0 125
2430  
2431 125 my $file_read = q{#perl
2432 my ($path, $offset, $length) = @ARGV;
2433  
2434 open my $fh, "<:raw", $path or return 0, "open: $!";
2435 defined sysseek $fh, $offset, 0 or return 0, "seek: $!";
2436 my $n = sysread $fh, my $data, $length;
2437 defined $n or return 0, "read: $!";
2438  
2439 (1, $data)
2440 };
2441  
2442 $perl && mcp_tool file_read =>
2443 "Read up to 1 MiB at byte offset. Returns {data: BASE64}, even for text; {error: STRING} on filesystem failure. Prefer read-lines for source/text.",
2444 {
2445 type => "object",
2446 properties => {
2447 path => {
2448 type => "string",
2449 },
2450 offset => {
2451 type => "integer",
2452 minimum => 0,
2453 default => 0,
2454 },
2455 length => {
2456 type => "integer",
2457 minimum => 1,
2458 maximum => 1<<20,
2459 default => 1<<16,
2460 },
2461 workdir => $workdir_schema,
2462 reason => {
2463 type => "string",
2464 description => "Why access needed.",
2465 },
2466 },
2467 required => ["path"],
2468 additionalProperties => JSON::XS::false,
2469 },
2470 264 ▶ sub {
Subroutine __ANON__: called CC=5 SCAR=17.4
2471 264 my ($req, $args) = @_;
2472  
2473 264 my ($workdir, $identity) = fs_workdir $args->{workdir};
2474 256 ▶ my $offset = $args->{offset} // 0;
Condition50%1/2
$args->{"offset"} // 0
l!l
0256
MC/DC0%0/1
$args->{"offset"} // 0
$args->{"offset"}
Truth table50%1/2
A
A= $args->{"offset"}
Aresult
11
00
2475 256 ▶ my $length = $args->{length} // 65536;
Condition50%1/2
$args->{"length"} // 65536
l!l
0256
MC/DC0%0/1
$args->{"length"} // 65536
$args->{"length"}
Truth table50%1/2
A
A= $args->{"length"}
Aresult
11
00
2476 256 ▶ $length <= 1<<20
Branch: 1 branch
BranchTrueFalseTotal
$length <= 1048576 or die "invalid read range\n" 256 0 256
2477 or die "invalid read range\n";
2478 256 my $path = fs_path $workdir, $args->{path};
2479  
2480 my $granted = fs_require_paths ($req, $workdir, $identity, [$path], "read",
2481 214 ▶ $args->{reason} // "read $path");
Condition50%1/2
$args->{"reason"} // "read $path"
l!l
0214
MC/DC0%0/1
$args->{"reason"} // "read $path"
$args->{"reason"}
Truth table50%1/2
A
A= $args->{"reason"}
Aresult
11
00
2482  
2483 176 AE::log debug => join " ", "fs file-read", $path, $offset, $length;
2484  
2485 perl_eval $req, $workdir, $granted, $file_read,
2486 151 ▶ [AnyEvent::MCP::utf8enc $path, $offset, $length], 30, sub {
Subroutine __ANON__: called CC=5 SCAR=18.4
2487 151 my ($success, $result) = @_;
2488  
2489 151 ▶ return $req->error ($result)
Branch: 1 branch
BranchTrueFalseTotal
unless $success 9 142 151
2490 unless $success;
2491  
2492 142 ▶ @$result == 2
Branch: 1 branch
BranchTrueFalseTotal
@$result == 2 or return $req->error("invalid file-read response\n") 142 0 142
2493 or return $req->error ("invalid file-read response\n");
2494 142 my ($ok, $value) = @$result;
2495 142 ▶ if ($ok eq "1") {
Branch: 2 branches
BranchTrueFalseTotal
if ($ok eq '1') { } 142 0 142
elsif ($ok eq '0') { } 0 0 0
2496 142 $req->reply (fs_result {
2497 data => MIME::Base64::encode_base64 ($value, ""),
2498 });
2499 } elsif ($ok eq "0") {
2500 0 $req->reply (fs_result {
2501 error => AnyEvent::MCP::utf8dec $value,
2502 });
2503 } else {
2504 0 $req->error ("invalid file-read status\n");
2505 }
2506 176 };
2507 }
2508 125 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$perl and mcp_tool("file_read", "Read up to 1 MiB at byte offset. Returns {data: BASE64}, even for text; {error: STRING} on filesystem failure. Prefer read-lines for source/text.", {"type", "object", "properties", {"path", {"type", "string"}, "offset", {"type", "integer", "minimum", 0, "default", 0}, "length", {"type", "integer", "minimum", 1, "maximum", 1048576, "default", 65536}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "required", ["path"], "additionalProperties", &JSON::XS::false()}, sub { my($req, $args) = @_; my($workdir, $identity) = fs_workdir($args->{"workdir"}); my $offset = $args->{"offset"} // 0; my $length = $args->{"length"} // 65536; $length <= 1048576 or die "invalid read range\n"; my $path = fs_path($workdir, $args->{"path"}); my $granted = fs_require_paths($req, $workdir, $identity, [$path], "read", $args->{"reason"} // "read $path"); &AE::log("debug", join(" ", "fs file-read", $path, $offset, $length)); perl_eval($req, $workdir, $granted, $file_read, [&AnyEvent::MCP::utf8enc($path), $offset, $length], 30, sub { my($success, $result) = @_; return $req->error($result) unless $success; @$result == 2 or return $req->error("invalid file-read response\n"); my($ok, $value) = @$result; if ($ok eq 1) { $req->reply(fs_result({"data", &MIME::Base64::encode_base64($value, "")})); } elsif ($ok eq 0) { $req->reply(fs_result({"error", &AnyEvent::MCP::utf8dec($value)})); } else { $req->error("invalid file-read status\n"); } ; } ); } ) 125 0 125
2509  
2510 $sed && mcp_tool read_lines =>
2511 "Read byte-LF (0x0A) lines by positive line ranges. "
2512 . "encoding: strict utf-8 (default), latin1 (raw bytes as text), base64 (exact range bytes). "
2513 . "linenums=true prefixes absolute line number plus colon (before base64 encoding). "
2514 . "Per range: two MCP text items, [range=N,M] metadata (truncated=1 if cut), then lines without added newlines. Preserves order, overlaps, duplicates; max 1 MiB raw output.",
2515 {
2516 type => "object",
2517 properties => {
2518 path => {
2519 type => "string",
2520 },
2521 ranges => {
2522 type => "array",
2523 description => 'Inclusive line ranges as strings, e.g. ["1,60", "80"]. Comma, not dash.',
2524 items => {
2525 type => "string",
2526 pattern => q{^[1-9][0-9]*(?:,[1-9][0-9]*)?$},
2527 },
2528 minItems => 1,
2529 maxItems => 20,
2530 },
2531 encoding => {
2532 type => "string",
2533 description => "Range format: strict utf-8 (default), latin1, base64. Lines split at byte LF (0x0A).",
2534 enum => ["utf-8", "latin1", "base64"],
2535 default => "utf-8",
2536 },
2537 linenums => {
2538 type => "boolean",
2539 description => "Prefix all lines, including blanks, with absolute number and colon.",
2540 default => JSON::XS::false,
2541 },
2542 workdir => $workdir_schema,
2543 reason => {
2544 type => "string",
2545 description => "Why access needed.",
2546 },
2547 },
2548 required => ["path", "ranges"],
2549 additionalProperties => JSON::XS::false,
2550 },
2551 8 ▶ sub {
Subroutine __ANON__: called CC=7 SCAR=22.6
2552 8 my ($req, $args) = @_;
2553  
2554 8 ▶ my $encoding = $args->{encoding} // "utf-8";
Condition50%1/2
$args->{"encoding"} // "utf-8"
l!l
08
MC/DC0%0/1
$args->{"encoding"} // "utf-8"
$args->{"encoding"}
Truth table50%1/2
A
A= $args->{"encoding"}
Aresult
11
00
2555 8 ▶ $encoding =~ /\A(?:utf-8|latin1|base64)\z/ or die "invalid read-lines encoding\n";
Branch: 1 branch
BranchTrueFalseTotal
$encoding =~ /\A(?:utf-8|latin1|base64)\z/u or die "invalid read-lines encoding\n" 8 0 8
2556  
2557 8 my ($workdir, $identity) = fs_workdir $args->{workdir};
2558 8 my $path = fs_path $workdir, $args->{path};
2559 my @range = map {
2560 8 ▶ my ($start, $end) = /\A([1-9]\d*)(?:,([1-9]\d*))?\z/
Branch: 1 branch
BranchTrueFalseTotal
() = /\A([1-9]\d*)(?:,([1-9]\d*))?\z/u or die "invalid line range\n" 8 0 8
2561 or die "invalid line range\n";
2562 8 ▶ $end //= $start;
Condition33%1/3
$end //= $start
l!l&&r!l&&!r
080
MC/DC0%0/2
$end //= $start
$end $start
Truth table33%1/3
A //= B
A= $endB= $start
ABresult
1X1
011
000
2563 8 ▶ $start <= $end
Branch: 1 branch
BranchTrueFalseTotal
$start <= $end or die "invalid line range\n" 8 0 8
2564 or die "invalid line range\n";
2565 8 [$_, $start, $end]
2566 8 } @{$args->{ranges}};
2567  
2568 my $granted = fs_require_paths ($req, $workdir, $identity, [$path], "read",
2569 8 ▶ $args->{reason} // "read lines $path");
Condition50%1/2
$args->{"reason"} // "read lines $path"
l!l
08
MC/DC0%0/1
$args->{"reason"} // "read lines $path"
$args->{"reason"}
Truth table50%1/2
A
A= $args->{"reason"}
Aresult
11
00
2570  
2571 8 AE::log debug => join " ", "fs read-lines", $path, map $_->[0], @range;
2572  
2573 8 my (@result, $truncated);
2574 8 my $remaining = 1 << 20;
2575 8 my $next;
2576 15 ▶ $next = sub {
Subroutine __ANON__: called CC=8 SCAR=25.8
2577 15 ▶ unless (@range) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@range) 7 8 15
2578 7 undef $next;
2579 7 my @content;
2580 7 for my $i (0 .. $#result) {
2581 7 my ($range, $body) = @{$result[$i]};
2582 7 my $header = "[range=$range";
2583 7 ▶ $header .= " truncated=1" if $truncated && $i == $#result;
Branch: 1 branch
BranchTrueFalseTotal
if $truncated and $i == $#result 0 7 7
Condition33%1/3
$truncated and $i == $#result
!ll&&!rl&&r
700
MC/DC0%0/2
$truncated and $i == $#result
$truncated $i == $#result
Truth table33%1/3
A and B
A= $truncatedB= $i == $#result
ABresult
0X0
100
111
2584 7 push @content,
2585 { type => "text", text => "$header]" },
2586 { type => "text", text => $body };
2587 }
2588 7 ▶ push @content, { type => "text", text => "[truncated=1]" }
Branch: 1 branch
BranchTrueFalseTotal
if $truncated and not @content 0 7 7
Condition33%1/3
$truncated and not @content
!ll&&!rl&&r
700
MC/DC0%0/2
$truncated and not @content
$truncated not @content
Truth table33%1/3
A and not(B)
A= $truncatedB= not @content
ABresult
0X0
100
111
2589 if $truncated && !@content;
2590 7 return $req->reply ({ content => \@content });
2591 }
2592  
2593 8 my ($range, $start, $end) = @{shift @range};
2594 8 ▶ my @command = (
Branch: 1 branch
BranchTrueFalseTotal
$start == $end ? : 8 0 8
2595 (fs_sandbox $workdir, $granted),
2596 $sed, "-n",
2597 "-e", ($start == $end ? "${start}p" : "${start},${end}p"),
2598 "-e", "${end}Q", # Preserve unterminated final line (GNU sed).
2599 AnyEvent::MCP::utf8enc $path,
2600 );
2601  
2602 7 ▶ fs_run $req, \@command, "", 30, $remaining, 0, sub {
Subroutine __ANON__: called CC=14 SCAR=37.9
2603 7 my ($success, $value) = @_;
2604  
2605 7 ▶ return $req->error ($value)
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 7 7
2606 unless $success;
2607  
2608 7 my $body;
2609 7 my $ok = eval {
2610 7 ▶ die "read-lines timed out\n" if $value->{timed_out};
Branch: 1 branch
BranchTrueFalseTotal
if $value->{"timed_out"} 0 7 7
2611 7 ▶ if ($value->{exit} or $value->{signal}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value->{"exit"} or $value->{"signal"}) 0 7 7
Condition33%1/3
$value->{"exit"} or $value->{"signal"}
l!l&&r!l&&!r
007
MC/DC0%0/2
$value->{"exit"} or $value->{"signal"}
$value->{"exit"} $value->{"signal"}
Truth table33%1/3
A or B
A= $value->{"exit"}B= $value->{"signal"}
ABresult
1X1
011
000
2612 0 my $stderr = AnyEvent::MCP::utf8dec $value->{stderr};
2613 0 die "read-lines failed (exit $value->{exit}, signal $value->{signal}): $stderr\n";
2614 }
2615 7 ▶ if ($args->{linenums} && length $value->{stdout}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"linenums"} and length $value->{"stdout"}) 0 7 7
Condition33%1/3
$args->{"linenums"} and length $value->{"stdout"}
!ll&&!rl&&r
700
MC/DC0%0/2
$args->{"linenums"} and length $value->{"stdout"}
$args->{"linenums"} length $value->{"stdout"}
Truth table33%1/3
A and B
A= $args->{"linenums"}B= length $value->{"stdout"}
ABresult
0X0
100
111
2616 0 my $line = $start;
2617 0 $value->{stdout} =~ s/^/$line++ . ":"/gme;
2618 0 ▶ if (length $value->{stdout} > $remaining) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $value->{"stdout"} > $remaining) 0 0 0
2619 0 substr ($value->{stdout}, $remaining) = "";
2620 0 $value->{truncated} = 1;
2621 }
2622 }
2623 $body = $encoding eq "utf-8" ? AnyEvent::MCP::utf8dec $value->{stdout}
2624 : $encoding eq "base64" ? MIME::Base64::encode_base64 ($value->{stdout}, "")
2625 7 ▶ : $value->{stdout}; # Unflagged byte strings are Latin-1 to Perl/JSON::XS.
Branch: 2 branches
BranchTrueFalseTotal
$encoding eq 'utf-8' ? : 7 0 7
$encoding eq 'base64' ? : 0 0 0
2626 7 1
2627 };
2628 7 ▶ return $req->error ($@)
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 7 7
2629 unless $ok;
2630  
2631 7 push @result, [$range, $body];
2632 7 $remaining -= length $value->{stdout};
2633 7 ▶ if ($value->{truncated} or ($remaining <= 0 and @range)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value->{"truncated"} or $remaining <= 0 and @range) 0 7 7
Condition33%2/6
$value->{"truncated"} or $remaining <= 0 and @range
l!l&&r!l&&!r
007
$remaining <= 0 and @range
!ll&&!rl&&r
700
MC/DC0%0/3
$value->{"truncated"} or $remaining <= 0 and @range
$value->{"truncated"} $remaining <= 0 @range
Truth table25%1/4
A or B and C
A= $value->{"truncated"}B= $remaining <= 0C= @range
ABCresult
1XX1
0111
00X0
0100
2634 0 $truncated = 1;
2635 0 @range = ();
2636 }
2637 7 $next->();
2638 8 };
2639 8 };
2640  
2641 8 $next->();
2642 }
2643 125 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$sed and mcp_tool("read_lines", "Read byte-LF (0x0A) lines by positive line ranges. encoding: strict utf-8 (default), latin1 (raw bytes as text), base64 (exact range bytes). linenums=true prefixes absolute line number plus colon (before base64 encoding). Per range: two MCP text items, [range=N,M] metadata (truncated=1 if cut), then lines without added newlines. Preserves order, overlaps, duplicates; max 1 MiB raw output.", {"type", "object", "properties", {"path", {"type", "string"}, "ranges", {"type", "array", "description", "Inclusive line ranges as strings, e.g. [\"1,60\", \"80\"]. Comma, not dash.", "items", {"type", "string", "pattern", "^[1-9][0-9]*(?:,[1-9][0-9]*)?\$"}, "minItems", 1, "maxItems", 20}, "encoding", {"type", "string", "description", "Range format: strict utf-8 (default), latin1, base64. Lines split at byte LF (0x0A).", "enum", ["utf-8", "latin1", "base64"], "default", "utf-8"}, "linenums", {"type", "boolean", "description", "Prefix all lines, including blanks, with absolute number and colon.", "default", &JSON::XS::false()}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "required", ["path", "ranges"], "additionalProperties", &JSON::XS::false()}, sub { my($req, $args) = @_; my $encoding = $args->{"encoding"} // "utf-8"; $encoding =~ /\A(?:utf-8|latin1|base64)\z/u or die "invalid read-lines encoding\n"; my($workdir, $identity) = fs_workdir($args->{"workdir"}); my $path = fs_path($workdir, $args->{"path"}); my(@range) = map({my($start, $end) = /\A([1-9]\d*)(?:,([1-9]\d*))?\z/u or die "invalid line range\n"; $end //= $start; $start <= $end or die "invalid line range\n"; [$_, $start, $end];} @{$$args{"ranges"};}); my $granted = fs_require_paths($req, $workdir, $identity, [$path], "read", $args->{"reason"} // "read lines $path"); &AE::log("debug", join(" ", "fs read-lines", $path, map($_->[0], @range))); my(@result, $truncated); my $remaining = 1048576; my $next; $next = sub { unless (@range) { undef $next; my @content; foreach my $i (0 .. $#result) { my($range, $body) = @{$result[$i];}; my $header = "[range=$range"; $header .= ' truncated=1' if $truncated and $i == $#result; push @content, {"type", "text", "text", "$header]"}, {"type", "text", "text", $body}; } ; push @content, {"type", "text", "text", "[truncated=1]"} if $truncated and not @content; return $req->reply({"content", \@content}); } ; my($range, $start, $end) = @{shift @range;}; my(@command) = (fs_sandbox($workdir, $granted), $sed, "-n", "-e", $start == $end ? "${start}p" : "$start,${end}p", "-e", "${end}Q", &AnyEvent::MCP::utf8enc($path)); fs_run($req, \@command, "", 30, $remaining, 0, sub { my($success, $value) = @_; return $req->error($value) unless $success; my $body; my $ok = eval { do { die "read-lines timed out\n" if $value->{"timed_out"}; if ($value->{"exit"} or $value->{"signal"}) { my $stderr = &AnyEvent::MCP::utf8dec($value->{"stderr"}); die qq[read-lines failed (exit $value->{"exit"}, signal $value->{"signal"}): $stderr\n]; } ; if ($args->{"linenums"} and length $value->{"stdout"}) { my $line = $start; $value->{"stdout"} =~ s/^/$line++ . ':';/egmu; if (length $value->{"stdout"} > $remaining) { substr($value->{"stdout"}, $remaining) = ""; $value->{"truncated"} = 1; } ; } ; $body = $encoding eq "utf-8" ? &AnyEvent::MCP::utf8dec($value->{"stdout"}) : ($encoding eq "base64" ? &MIME::Base64::encode_base64($value->{"stdout"}, "") : $value->{"stdout"}); 1 } }; return $req->error($@) unless $ok; push @result, [$range, $body]; $remaining -= length $value->{"stdout"}; if ($value->{"truncated"} or $remaining <= 0 and @range) { $truncated = 1; @range = (); } ; &$next(); } ); } ; &$next(); } ) 125 0 125
2644  
2645 125 my $file_write = q{#perl
2646 my ($path, $offset, $data) = @ARGV;
2647  
2648 use Fcntl qw(O_WRONLY O_CREAT);
2649 sysopen my $fh, $path, O_WRONLY | O_CREAT, 0666 or return 0, "open: $!";
2650  
2651 binmode $fh;
2652 defined sysseek $fh, $offset, 0 or return 0, "seek: $!";
2653 my $n = syswrite $fh, $data;
2654 defined $n or return 0, "write: $!";
2655  
2656 (1, "$n")
2657 };
2658  
2659 $perl && mcp_tool file_write =>
2660 "Write up to 1 MiB Base64-decoded bytes at offset; no truncation. Returns {bytes: INTEGER} or {error: STRING} on filesystem failure.",
2661 {
2662 type => "object",
2663 properties => {
2664 path => {
2665 type => "string",
2666 },
2667 offset => {
2668 type => "integer",
2669 minimum => 0,
2670 default => 0,
2671 },
2672 data => {
2673 type => "string",
2674 },
2675 workdir => $workdir_schema,
2676 reason => {
2677 type => "string",
2678 description => "Why access needed.",
2679 },
2680 },
2681 required => ["path", "data"],
2682 additionalProperties => JSON::XS::false,
2683 },
2684 184 ▶ sub {
Subroutine __ANON__: called CC=5 SCAR=17.7
2685 184 my ($req, $args) = @_;
2686  
2687 184 my ($workdir, $identity) = fs_workdir $args->{workdir};
2688 184 ▶ my $offset = $args->{offset} // 0;
Condition50%1/2
$args->{"offset"} // 0
l!l
0184
MC/DC0%0/1
$args->{"offset"} // 0
$args->{"offset"}
Truth table50%1/2
A
A= $args->{"offset"}
Aresult
11
00
2689 184 my $data = MIME::Base64::decode_base64 $args->{data};
2690 MIME::Base64::encode_base64 ($data, "") eq $args->{data}
2691 184 ▶ or die "invalid base64 data\n";
Branch: 1 branch
BranchTrueFalseTotal
&MIME::Base64::encode_base64($data, "") eq $args->{"data"} or die "invalid base64 data\n" 184 0 184
2692 184 ▶ length $data <= 1048576
Branch: 1 branch
BranchTrueFalseTotal
length $data <= 1048576 or die "write data exceeds 1 MiB\n" 184 0 184
2693 or die "write data exceeds 1 MiB\n";
2694 184 my $path = fs_path $workdir, $args->{path};
2695  
2696 my $granted = fs_require_paths ($req, $workdir, $identity, [$path], "write",
2697 184 ▶ $args->{reason} // "write $path");
Condition50%1/2
$args->{"reason"} // "write $path"
l!l
0184
MC/DC0%0/1
$args->{"reason"} // "write $path"
$args->{"reason"}
Truth table50%1/2
A
A= $args->{"reason"}
Aresult
11
00
2698  
2699 58 AE::log debug => join " ", "fs file-write", $path, $offset, length ($data);
2700  
2701 perl_eval $req, $workdir, $granted, $file_write,
2702 54 ▶ [AnyEvent::MCP::utf8enc $path, $offset, $data], 30, sub {
Subroutine __ANON__: called CC=6 SCAR=21.6
2703 54 my ($success, $result) = @_;
2704  
2705 54 ▶ return $req->error ($result)
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 54 54
2706 unless $success;
2707  
2708 54 ▶ @$result == 2
Branch: 1 branch
BranchTrueFalseTotal
@$result == 2 or return $req->error("invalid file-write response\n") 54 0 54
2709 or return $req->error ("invalid file-write response\n");
2710 54 my ($ok, $value) = @$result;
2711 54 ▶ if ($ok eq "1") {
Branch: 2 branches
BranchTrueFalseTotal
if ($ok eq '1') { } 54 0 54
elsif ($ok eq '0') { } 0 0 0
2712 54 ▶ $value =~ /\A[0-9]+\z/
Branch: 1 branch
BranchTrueFalseTotal
$value =~ /\A[0-9]+\z/u or return $req->error("invalid file-write byte count\n") 54 0 54
2713 or return $req->error ("invalid file-write byte count\n");
2714 54 $req->reply (fs_result {
2715 bytes => 0 + $value,
2716 });
2717 } elsif ($ok eq "0") {
2718 0 $req->reply (fs_result {
2719 error => AnyEvent::MCP::utf8dec $value,
2720 });
2721 } else {
2722 0 $req->error ("invalid file-write status\n");
2723 }
2724 58 };
2725 }
2726 125 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$perl and mcp_tool("file_write", "Write up to 1 MiB Base64-decoded bytes at offset; no truncation. Returns {bytes: INTEGER} or {error: STRING} on filesystem failure.", {"type", "object", "properties", {"path", {"type", "string"}, "offset", {"type", "integer", "minimum", 0, "default", 0}, "data", {"type", "string"}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "required", ["path", "data"], "additionalProperties", &JSON::XS::false()}, sub { my($req, $args) = @_; my($workdir, $identity) = fs_workdir($args->{"workdir"}); my $offset = $args->{"offset"} // 0; my $data = &MIME::Base64::decode_base64($args->{"data"}); &MIME::Base64::encode_base64($data, "") eq $args->{"data"} or die "invalid base64 data\n"; length $data <= 1048576 or die "write data exceeds 1 MiB\n"; my $path = fs_path($workdir, $args->{"path"}); my $granted = fs_require_paths($req, $workdir, $identity, [$path], "write", $args->{"reason"} // "write $path"); &AE::log("debug", join(" ", "fs file-write", $path, $offset, length $data)); perl_eval($req, $workdir, $granted, $file_write, [&AnyEvent::MCP::utf8enc($path), $offset, $data], 30, sub { my($success, $result) = @_; return $req->error($result) unless $success; @$result == 2 or return $req->error("invalid file-write response\n"); my($ok, $value) = @$result; if ($ok eq 1) { $value =~ /\A[0-9]+\z/u or return $req->error("invalid file-write byte count\n"); $req->reply(fs_result({"bytes", 0 + $value})); } elsif ($ok eq 0) { $req->reply(fs_result({"error", &AnyEvent::MCP::utf8dec($value)})); } else { $req->error("invalid file-write status\n"); } ; } ); } ) 125 0 125
2727  
2728 125 my $path_op = q{#perl
2729 while (@ARGV) {
2730 my $op = shift;
2731  
2732 if ($op eq "unlink") {
2733 my $path = shift;
2734  
2735 unlink $path
2736 or die "unlink $path: $!\n";
2737 } elsif ($op eq "rmdir") {
2738 my $path = shift;
2739  
2740 rmdir $path
2741 or die "rmdir $path: $!\n";
2742 } elsif ($op eq "mkdir") {
2743 my ($path, $mode) = splice @ARGV, 0, 2;
2744 $mode = oct $mode;
2745 mkdir $path, $mode
2746 or die "mkdir $path: $!\n";
2747 chmod $mode, $path
2748 or die "chmod $path: $!\n";
2749 } elsif ($op eq "mkpath") {
2750 my ($path, $mode) = splice @ARGV, 0, 2;
2751 $mode = oct $mode;
2752 my $prefix = "";
2753  
2754 for (split m{/}, $path) {
2755 next unless length;
2756 $prefix .= "/$_";
2757 next if -d $prefix;
2758 mkdir $prefix, $mode
2759 or die "mkdir $prefix: $!\n";
2760 chmod $mode, $prefix
2761 or die "chmod $prefix: $!\n";
2762 }
2763 } elsif ($op eq "symlink") {
2764 my ($target, $path) = splice @ARGV, 0, 2;
2765 symlink $target, $path
2766 or die "symlink $path: $!\n";
2767 } elsif ($op eq "truncate") {
2768 my ($path, $size) = splice @ARGV, 0, 2;
2769 truncate $path, $size
2770 or die "truncate $path: $!\n";
2771 } elsif ($op eq "chmod") {
2772 my ($path, $mode) = splice @ARGV, 0, 2;
2773 $mode = oct $mode;
2774 chmod $mode, $path
2775 or die "chmod $path: $!\n";
2776 } elsif ($op eq "rename") {
2777 my ($path, $to) = splice @ARGV, 0, 2;
2778 rename $path, $to
2779 or die "rename $path -> $to: $!\n";
2780 } else {
2781 die "invalid path operation '$op'\n";
2782 }
2783 }
2784  
2785 1
2786 };
2787  
2788 $perl && mcp_tool path_op =>
2789 "Mutate paths in fixed order: unlink, rmdir, mkpath, mkdir, symlink, truncate, chmod, rename. "
2790 . "Stop at first failure; earlier changes remain (no rollback). "
2791 . "mkpath creates missing components in worker; symlink target is link text, not sandbox authority.",
2792 {
2793 type => "object",
2794 properties => {
2795 path => {
2796 type => "string",
2797 },
2798 unlink => {
2799 type => "boolean",
2800 },
2801 rmdir => {
2802 type => "boolean",
2803 },
2804 mkdir => {
2805 description => "Create directory with final mode (ignores umask).",
2806 anyOf => [
2807 { type => "string", pattern => q{^[0-7]+$} },
2808 { type => "integer", minimum => 0 },
2809 ],
2810 },
2811 mkpath => {
2812 description => "Create missing directories with final mode (ignores umask).",
2813 anyOf => [
2814 { type => "string", pattern => q{^[0-7]+$} },
2815 { type => "integer", minimum => 0 },
2816 ],
2817 },
2818 symlink => {
2819 type => "string",
2820 minLength => 1,
2821 description => "Create symlink; value is link target.",
2822 },
2823 truncate => {
2824 type => "integer",
2825 minimum => 0,
2826 },
2827 chmod => {
2828 anyOf => [
2829 { type => "string", pattern => q{^[0-7]+$} },
2830 { type => "integer", minimum => 0 },
2831 ],
2832 },
2833 rename => {
2834 type => "string",
2835 minLength => 1,
2836 description => "Rename destination.",
2837 },
2838 workdir => $workdir_schema,
2839 reason => {
2840 type => "string",
2841 description => "Why access needed.",
2842 },
2843 },
2844 required => ["path"],
2845 additionalProperties => JSON::XS::false,
2846 },
2847 679 ▶ sub {
Subroutine __ANON__: called CC=22 SCAR=31.6
2848 679 my ($req, $args) = @_;
2849  
2850 ($args->{unlink} or $args->{rmdir}
2851 679 ▶ or grep { exists $args->{$_} } qw(mkdir mkpath symlink truncate chmod rename))
Branch: 1 branch
BranchTrueFalseTotal
$args->{"unlink"} or $args->{"rmdir"} or grep {exists $args->{$_};} "mkdir", "mkpath", "symlink", "truncate", "chmod", "rename" or die "no path operation requested\n" 679 0 679
Condition66%4/6
$args->{"unlink"} or $args->{"rmdir"} or grep {exists $args->{$_};} "mkdir", "mkpath", "symlink", "truncate", "chmod", "rename"
l!l&&r!l&&!r
1185610
$args->{"unlink"} or $args->{"rmdir"}
l!l&&r!l&&!r
1180561
MC/DC0%0/3
$args->{"unlink"} or $args->{"rmdir"} or grep {exists $args->{$_};} "mkdir", "mkpath", "symlink", "truncate", "chmod", "rename"
$args->{"unlink"} $args->{"rmdir"} grep {exists $args->{$_};} "mkdir", "mkpath", "symlink", "truncate", "chmod", "rename"
Truth table50%2/4
A or B or C
A= $args->{"unlink"}B= $args->{"rmdir"}C= grep {exists $args->{$_};} "mkdir", "mkpath", "symlink", "truncate", "chmod", "rename"
ABCresult
1XX1
01X1
0011
0000
2852 or die "no path operation requested\n";
2853  
2854 679 my ($workdir, $identity) = fs_workdir $args->{workdir};
2855 679 my $path = fs_path $workdir, $args->{path};
2856 my $rename = exists $args->{rename}
2857 ? fs_path $workdir, $args->{rename}
2858 679 ▶ : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $args->{'rename'} ? : 241 438 679
2859 die "mkpath requires a path in the selected workdir\n"
2860 679 ▶ if exists $args->{mkpath} && !fs_inside ($path, $workdir);
Branch: 1 branch
BranchTrueFalseTotal
if exists $args->{"mkpath"} and not fs_inside($path, $workdir) 0 679 679
Condition66%2/3
exists $args->{"mkpath"} and not fs_inside($path, $workdir)
!ll&&!rl&&r
3593200
MC/DC0%0/2
exists $args->{"mkpath"} and not fs_inside($path, $workdir)
exists $args->{"mkpath"} not fs_inside($path, $workdir)
Truth table66%2/3
A and not(B)
A= exists $args->{"mkpath"}B= not fs_inside($path, $workdir)
ABresult
0X0
100
111
2861  
2862 679 my $json = JSON::XS->new;
2863 my @log = map {
2864 679 ($_ eq "unlink" or $_ eq "rmdir")
2865 ? ($args->{$_} ? $_ : ())
2866 : (exists $args->{$_}
2867 5432 ▶ ? "$_: " . $json->encode ($_ eq "rename" ? $rename : $args->{$_}) : ())
Branch: 4 branches
BranchTrueFalseTotal
$_ eq 'unlink' || $_ eq 'rmdir' ? : 1358 4074 5432
$args->{$_} ? : 118 1240 1358
exists $args->{$_} ? : 641 3433 4074
$_ eq 'rename' ? : 241 400 641
Condition100%3/3
$_ eq "unlink" or $_ eq "rmdir"
l!l&&r!l&&!r
6796794074
MC/DC100%2/2
$_ eq "unlink" or $_ eq "rmdir"
$_ eq "unlink" $_ eq "rmdir"
Truth table100%3/3
A or B
A= $_ eq "unlink"B= $_ eq "rmdir"
ABresult
1X1
011
000
2868 } qw(unlink rmdir mkpath mkdir symlink truncate chmod rename);
2869 my $reason = join "\n",
2870 679 ▶ (defined $args->{reason} ? $args->{reason} : ()),
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{'reason'} ? : 80 599 679
2871 "Path: " . $json->encode ($path), "Operations (in order):", map " $_", @log;
2872  
2873 679 ▶ my $granted = fs_require_paths $req, $workdir, $identity,
Branch: 1 branch
BranchTrueFalseTotal
defined $rename ? : 241 438 679
2874 [$path, (defined $rename ? $rename : ())], "write", $reason;
2875  
2876 284 AE::log debug => join " ", "fs path-op", $path, @log;
2877  
2878 284 my @operation;
2879 284 my $raw_path = AnyEvent::MCP::utf8enc $path;
2880  
2881 push @operation, unlink => $raw_path
2882 284 ▶ if $args->{unlink};
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"unlink"} 40 244 284
2883 push @operation, rmdir => $raw_path
2884 284 ▶ if $args->{rmdir};
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"rmdir"} 0 284 284
2885 push @operation, mkpath => $raw_path, $args->{mkpath}
2886 284 ▶ if exists $args->{mkpath};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args->{"mkpath"} 160 124 284
2887 push @operation, mkdir => $raw_path, $args->{mkdir}
2888 284 ▶ if exists $args->{mkdir};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args->{"mkdir"} 0 284 284
2889 push @operation, symlink => (AnyEvent::MCP::utf8enc $args->{symlink}), $raw_path
2890 284 ▶ if exists $args->{symlink};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args->{"symlink"} 0 284 284
2891 push @operation, truncate => $raw_path, $args->{truncate}
2892 284 ▶ if exists $args->{truncate};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args->{"truncate"} 0 284 284
2893 push @operation, chmod => $raw_path, $args->{chmod}
2894 284 ▶ if exists $args->{chmod};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args->{"chmod"} 40 244 284
2895 284 ▶ push @operation, rename => $raw_path, (AnyEvent::MCP::utf8enc $rename)
Branch: 1 branch
BranchTrueFalseTotal
if defined $rename 84 200 284
2896 if defined $rename;
2897  
2898 perl_eval $req, $workdir, $granted, $path_op,
2899 281 ▶ \@operation, 30, sub {
Subroutine __ANON__: called CC=4 SCAR=14.6
2900 281 my ($success, $result) = @_;
2901  
2902 281 ▶ return $req->error ($result)
Branch: 1 branch
BranchTrueFalseTotal
unless $success 80 201 281
2903 unless $success;
2904  
2905 201 ▶ @$result == 1 and $result->[0] eq "1"
Branch: 1 branch
BranchTrueFalseTotal
@$result == 1 and $result->[0] eq 1 or return $req->error("invalid path-op response\n") 201 0 201
Condition33%1/3
@$result == 1 and $result->[0] eq 1
!ll&&!rl&&r
00201
MC/DC0%0/2
@$result == 1 and $result->[0] eq 1
@$result == 1 $result->[0] eq 1
Truth table33%1/3
A and B
A= @$result == 1B= $result->[0] eq 1
ABresult
0X0
100
111
2906 or return $req->error ("invalid path-op response\n");
2907 201 $req->reply (fs_text_result "ok\n");
2908 284 };
2909 }
2910 125 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$perl and mcp_tool("path_op", "Mutate paths in fixed order: unlink, rmdir, mkpath, mkdir, symlink, truncate, chmod, rename. Stop at first failure; earlier changes remain (no rollback). mkpath creates missing components in worker; symlink target is link text, not sandbox authority.", {"type", "object", "properties", {"path", {"type", "string"}, "unlink", {"type", "boolean"}, "rmdir", {"type", "boolean"}, "mkdir", {"description", "Create directory with final mode (ignores umask).", "anyOf", [{"type", "string", "pattern", "^[0-7]+\$"}, {"type", "integer", "minimum", 0}]}, "mkpath", {"description", "Create missing directories with final mode (ignores umask).", "anyOf", [{"type", "string", "pattern", "^[0-7]+\$"}, {"type", "integer", "minimum", 0}]}, "symlink", {"type", "string", "minLength", 1, "description", "Create symlink; value is link target."}, "truncate", {"type", "integer", "minimum", 0}, "chmod", {"anyOf", [{"type", "string", "pattern", "^[0-7]+\$"}, {"type", "integer", "minimum", 0}]}, "rename", {"type", "string", "minLength", 1, "description", "Rename destination."}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "required", ["path"], "additionalProperties", &JSON::XS::false()}, sub { my($req, $args) = @_; $args->{"unlink"} or $args->{"rmdir"} or grep {exists $args->{$_};} "mkdir", "mkpath", "symlink", "truncate", "chmod", "rename" or die "no path operation requested\n"; my($workdir, $identity) = fs_workdir($args->{"workdir"}); my $path = fs_path($workdir, $args->{"path"}); my $rename = exists $args->{"rename"} ? fs_path($workdir, $args->{"rename"}) : undef; die "mkpath requires a path in the selected workdir\n" if exists $args->{"mkpath"} and not fs_inside($path, $workdir); my $json = "JSON::XS"->new; my(@log) = map({$_ eq "unlink" || $_ eq "rmdir" ? $args->{$_} ? $_ : () : (exists $args->{$_} ? "${_}: " . $json->encode($_ eq "rename" ? $rename : $args->{$_}) : ());} "unlink", "rmdir", "mkpath", "mkdir", "symlink", "truncate", "chmod", "rename"); my $reason = join("\n", defined $args->{"reason"} ? $args->{"reason"} : (), 'Path: ' . $json->encode($path), "Operations (in order):", map((" $_"), @log)); my $granted = fs_require_paths($req, $workdir, $identity, [$path, defined $rename ? $rename : ()], "write", $reason); &AE::log("debug", join(" ", "fs path-op", $path, @log)); my @operation; my $raw_path = &AnyEvent::MCP::utf8enc($path); push @operation, "unlink", $raw_path if $args->{"unlink"}; push @operation, "rmdir", $raw_path if $args->{"rmdir"}; push @operation, "mkpath", $raw_path, $args->{"mkpath"} if exists $args->{"mkpath"}; push @operation, "mkdir", $raw_path, $args->{"mkdir"} if exists $args->{"mkdir"}; push @operation, "symlink", &AnyEvent::MCP::utf8enc($args->{"symlink"}), $raw_path if exists $args->{"symlink"}; push @operation, "truncate", $raw_path, $args->{"truncate"} if exists $args->{"truncate"}; push @operation, "chmod", $raw_path, $args->{"chmod"} if exists $args->{"chmod"}; push @operation, "rename", $raw_path, &AnyEvent::MCP::utf8enc($rename) if defined $rename; perl_eval($req, $workdir, $granted, $path_op, \@operation, 30, sub { my($success, $result) = @_; return $req->error($result) unless $success; @$result == 1 and $result->[0] eq 1 or return $req->error("invalid path-op response\n"); $req->reply(fs_text_result("ok\n")); } ); } ) 125 0 125
2911  
2912 125 my $file_patch = q{#perl
2913 use Fcntl qw(O_RDWR O_CREAT O_EXCL);
2914 use Errno qw(EEXIST ENAMETOOLONG);
2915  
2916 my ($patch, $path, $diff, @max_offset) = @ARGV;
2917  
2918 my $create_tempfile = sub {
2919 my ($name) = @_;
2920 utf8::decode $name
2921 or return undef, "invalid UTF-8 tempfile name";
2922  
2923 my $slash = rindex $name, "/";
2924 my $dir = $slash < 0 ? "" : substr $name, 0, $slash + 1;
2925 my $file = substr $name, $slash + 1;
2926  
2927 for (;;) {
2928 my $pathname = "$dir$file";
2929 utf8::encode $pathname;
2930  
2931 if (sysopen my $fh, $pathname, O_RDWR | O_CREAT | O_EXCL, 0600) {
2932 binmode $fh;
2933 return $fh, $pathname
2934 }
2935  
2936 if ($! == EEXIST) {
2937 $file .= "~";
2938 } elsif ($! == ENAMETOOLONG) {
2939 substr $file, (length $file) * .75, 2, "~";
2940 } else {
2941 return undef, "open tempfile: $!"
2942 }
2943 }
2944 };
2945  
2946 # deliberately self-contained: patch validation must not load host modules.
2947 my $check_patch_output = sub {
2948 my ($status, $output, @max_offset) = @_;
2949 my (@hunks, @unparsed);
2950  
2951 for (split /\n/, $output) {
2952 if (/^Hunk #(\d+) (succeeded|FAILED|ignored) at (-?\d+)(?: with fuzz (\d+))?(?: \(offset (-?\d+) lines?\))?\.\z/) {
2953 push @hunks, [0 + $1, $2 eq "succeeded", 0 + $4, 0 + $5];
2954 } elsif (!length
2955 || /^Hmm\.\.\. +Looks like a unified diff to me\.\.\.\z/
2956 || /^The text leading up to this was:\z/
2957 || /^-+\z/ || /^\|/
2958 || /^patching file / || /^checking file /
2959 || /^Using Plan [AB]\.\.\.\z/ || /^done\z/) {
2960 # GNU patch --verbose framing.
2961 } else {
2962 push @unparsed, $_;
2963 }
2964 }
2965  
2966 $status == 0
2967 or die "patch failed (wait status $status):\n$output";
2968 @unparsed == 0
2969 or die "patch: unrecognized output:\n" . (join "\n", @unparsed) . "\n";
2970 @hunks == @max_offset && @hunks
2971 or die "patch: expected " . @max_offset . " hunks, got " . @hunks . "\n";
2972  
2973 for my $i (0 .. $#hunks) {
2974 my ($number, $success, $fuzz, $offset) = @{$hunks[$i]};
2975  
2976 $number == $i + 1
2977 or die "patch: unexpected hunk number $number\n";
2978 $success
2979 or die "patch: hunk $number failed\n";
2980 !$fuzz
2981 or die "patch: hunk $number used fuzz $fuzz\n";
2982 abs ($offset) <= $max_offset[$i]
2983 or die "patch: hunk $number offset $offset exceeds $max_offset[$i]\n";
2984 }
2985 };
2986  
2987 my $run_patch = sub {
2988 my ($newname, $path, $diff) = @_;
2989  
2990 my ($errfh, $errname) = $create_tempfile->("/tmp/mcp-fs~~patch~~");
2991 $errfh
2992 or return undef, $errname;
2993  
2994 local $ENV{LC_ALL} = "C";
2995 open my $write, "|-", "sh", "-c",
2996 q{exec "$4" --unified --verbose --binary --batch --forward --get=0 --fuzz=0 --reject-file=- --no-backup-if-mismatch -o "$2" "$1" >"$3" 2>&1},
2997 "--", $path, $newname, $errname, $patch
2998 or return undef, "open patch pipe: $!";
2999  
3000 my $write_error;
3001 {
3002 print $write $diff
3003 or $write_error = "write patch: $!";
3004 close $write;
3005 }
3006  
3007 my $status = $?;
3008  
3009 unlink $errname
3010 or return undef, "unlink patch stderr: $!";
3011 defined sysseek $errfh, 0, 0
3012 or return undef, "seek patch stderr: $!";
3013 my $output = do { local $/; <$errfh> };
3014 $output = "" unless defined $output;
3015 $output =~ s/\s+\z//;
3016  
3017 return undef, $write_error
3018 if $write_error and !$status;
3019  
3020 $status, $output
3021 };
3022  
3023 my $replace_file = sub {
3024 my ($path, $before, $newfh, $newname) = @_;
3025  
3026 chown $before->[4], $before->[5], $newfh;
3027 chmod $before->[2], $newfh;
3028  
3029 my @after = lstat $path;
3030 @after
3031 or return undef, "lstat: $!";
3032 (join "\0", @$before[0, 1, 2, 3, 4, 5, 7, 9, 10])
3033 eq (join "\0", @after[0, 1, 2, 3, 4, 5, 7, 9, 10])
3034 or return undef, "file changed while applying patch";
3035 my @new = stat $newfh;
3036 $after[3] == 1
3037 or return undef, "refusing to replace multiply-linked file";
3038 (join "\0", @after[2, 4, 5]) eq (join "\0", @new[2, 4, 5])
3039 or return undef, "cannot preserve file metadata";
3040  
3041 rename $newname, $path
3042 or return undef, "rename: $!";
3043  
3044 $new[7], undef
3045 };
3046  
3047 my @before = lstat $path;
3048 @before
3049 or return 0, "lstat: $!";
3050 -f _
3051 or return 0, "not a regular file";
3052  
3053 my ($newfh, $newname) = $create_tempfile->("$path~~new~~");
3054 $newfh
3055 or return 0, $newname;
3056  
3057 my ($status, $output) = $run_patch->($newname, $path, $diff);
3058 unless (defined $status) {
3059 unlink $newname;
3060 return 0, $output
3061 }
3062  
3063 unless (eval { $check_patch_output->($status, $output, @max_offset); 1 }) {
3064 my $error = $@;
3065 unlink $newname;
3066 return 0, $error
3067 }
3068  
3069 my ($bytes, $error) = $replace_file->($path, \@before, $newfh, $newname);
3070 unlink $newname unless defined $bytes;
3071 defined $bytes
3072 ? (1, "$bytes")
3073 : (0, $error)
3074 };
3075  
3076 $perl && $patch && mcp_tool file_patch =>
3077 "Patch one regular file via unified diff. Recompute hunk counts; no fuzz. "
3078 . "Whole-hunk relocation bounded per hunk by distinct old-side lines. "
3079 . "Pure insertion only at file start; elsewhere include old-side context. "
3080 . "diff: Unicode text (encoded UTF-8) "
3081 . "or Base64 raw bytes; autodetect by @ hunk markers ("
3082 . "Base64 cannot contain @).",
3083 {
3084 type => "object",
3085 properties => {
3086 path => { type => "string" },
3087 diff => { type => "string", minLength => 1 },
3088 workdir => $workdir_schema,
3089 reason => {
3090 type => "string",
3091 description => "Why access needed.",
3092 },
3093 },
3094 required => ["path", "diff"],
3095 additionalProperties => JSON::XS::false,
3096 },
3097 0 ▶ sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
3098 0 my ($req, $args) = @_;
3099  
3100 0 my ($workdir, $identity) = fs_workdir $args->{workdir};
3101 0 my $path = fs_path $workdir, $args->{path};
3102 0 my $diff = $args->{diff};
3103 0 my $detail = $diff;
3104  
3105 0 ▶ if ((index $diff, "@") >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($diff, '@') != -1) { } 0 0 0
3106 0 $diff = AnyEvent::MCP::utf8enc $diff;
3107 } else {
3108 0 my $bytes = MIME::Base64::decode_base64 $diff;
3109 0 ▶ MIME::Base64::encode_base64 ($bytes, "") eq $diff
Branch: 1 branch
BranchTrueFalseTotal
&MIME::Base64::encode_base64($bytes, "") eq $diff or die "invalid base64 diff\n" 0 0 0
3110 or die "invalid base64 diff\n";
3111 0 $diff = $bytes;
3112 0 $detail = eval { AnyEvent::MCP::utf8dec $bytes };
3113  
3114 0 ▶ unless (defined $detail) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $detail) 0 0 0
3115 0 $detail = $bytes;
3116 0 $detail =~ s/([^\x09\x0a\x20-\x5b\x5d-\x7e])/sprintf "\\x{%02X}", ord $1/ge;
3117 0 $detail = "Raw patch: " . length ($bytes) . " bytes (escaped byte view)\n\n" . $detail;
3118 }
3119 }
3120  
3121 0 my $max_offset;
3122 0 ($diff, $max_offset) = AnyEvent::MCP::normalize_udiff $diff;
3123 0 ▶ length $diff <= 4<<20
Branch: 1 branch
BranchTrueFalseTotal
length $diff <= 4194304 or die "patch exceeds 4 MiB\n" 0 0 0
3124 or die "patch exceeds 4 MiB\n";
3125  
3126 my $granted = fs_require_paths ($req, $workdir, $identity, [$path], "write",
3127 0 ▶ $args->{reason} // "patch $path", { "View patch" => "File: $path\n\n$detail" });
Condition0%0/2
$args->{"reason"} // "patch $path"
l!l
00
MC/DC0%0/1
$args->{"reason"} // "patch $path"
$args->{"reason"}
Truth table0%0/2
A
A= $args->{"reason"}
Aresult
11
00
3128  
3129 0 AE::log debug => join " ", "fs file-patch", $path, scalar (@$max_offset), "hunks", length ($diff), "bytes";
3130  
3131 perl_eval $req, $workdir, $granted, $file_patch,
3132 0 ▶ [$patch, AnyEvent::MCP::utf8enc $path, $diff, @$max_offset], 30, sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
3133 0 my ($success, $result) = @_;
3134  
3135 0 ▶ return $req->error ($result)
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 0 0
3136 unless $success;
3137  
3138 0 ▶ @$result == 2
Branch: 1 branch
BranchTrueFalseTotal
@$result == 2 or return $req->error("invalid file-patch response\n") 0 0 0
3139 or return $req->error ("invalid file-patch response\n");
3140 0 my ($ok, $value) = @$result;
3141  
3142 0 ▶ if ($ok eq "1") {
Branch: 2 branches
BranchTrueFalseTotal
if ($ok eq '1') { } 0 0 0
elsif ($ok eq '0') { } 0 0 0
3143 0 ▶ $value =~ /\A[0-9]+\z/
Branch: 1 branch
BranchTrueFalseTotal
$value =~ /\A[0-9]+\z/u or return $req->error("invalid file-patch byte count\n") 0 0 0
3144 or return $req->error ("invalid file-patch byte count\n");
3145 0 $req->reply (fs_result {
3146 bytes => 0 + $value,
3147 });
3148 } elsif ($ok eq "0") {
3149 0 $req->reply (fs_result {
3150 error => AnyEvent::MCP::utf8dec $value,
3151 });
3152 } else {
3153 0 $req->error ("invalid file-patch status\n");
3154 }
3155 0 };
3156 }
3157 125 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$perl and $patch and mcp_tool("file_patch", "Patch one regular file via unified diff. Recompute hunk counts; no fuzz. Whole-hunk relocation bounded per hunk by distinct old-side lines. Pure insertion only at file start; elsewhere include old-side context. diff: Unicode text (encoded UTF-8) or Base64 raw bytes; autodetect by \@ hunk markers (Base64 cannot contain \@).", {"type", "object", "properties", {"path", {"type", "string"}, "diff", {"type", "string", "minLength", 1}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "required", ["path", "diff"], "additionalProperties", &JSON::XS::false()}, sub { my($req, $args) = @_; my($workdir, $identity) = fs_workdir($args->{"workdir"}); my $path = fs_path($workdir, $args->{"path"}); my $diff = $args->{"diff"}; my $detail = $diff; if (index($diff, "\@") != -1) { $diff = &AnyEvent::MCP::utf8enc($diff); } else { my $bytes = &MIME::Base64::decode_base64($diff); &MIME::Base64::encode_base64($bytes, "") eq $diff or die "invalid base64 diff\n"; $diff = $bytes; $detail = eval { do { &AnyEvent::MCP::utf8dec($bytes) } }; unless (defined $detail) { $detail = $bytes; $detail =~ s/([^\x09\x0a\x20-\x5b\x5d-\x7e])/sprintf "\\x{%02X}", ord $1;/egu; $detail = 'Raw patch: ' . length($bytes) . " bytes (escaped byte view)\n\n" . $detail; } ; } ; my $max_offset; ($diff, $max_offset) = AnyEvent::MCP::normalize_udiff($diff); length $diff <= 4194304 or die "patch exceeds 4 MiB\n"; my $granted = fs_require_paths($req, $workdir, $identity, [$path], "write", $args->{"reason"} // "patch $path", {"View patch", "File: $path\n\n$detail"}); &AE::log("debug", join(" ", "fs file-patch", $path, scalar @$max_offset, "hunks", length $diff, "bytes")); perl_eval($req, $workdir, $granted, $file_patch, [$patch, &AnyEvent::MCP::utf8enc($path), $diff, @$max_offset], 30, sub { my($success, $result) = @_; return $req->error($result) unless $success; @$result == 2 or return $req->error("invalid file-patch response\n"); my($ok, $value) = @$result; if ($ok eq 1) { $value =~ /\A[0-9]+\z/u or return $req->error("invalid file-patch byte count\n"); $req->reply(fs_result({"bytes", 0 + $value})); } elsif ($ok eq 0) { $req->reply(fs_result({"error", &AnyEvent::MCP::utf8dec($value)})); } else { $req->error("invalid file-patch status\n"); } ; } ); } ) 0 125 125
Condition33%1/3
$perl and $patch
!ll&&!rl&&r
01250
MC/DC0%0/2
$perl and $patch
$perl $patch
Truth table33%1/3
A and B
A= $perlB= $patch
ABresult
0X0
100
111
3158  
3159 $find && $grep && mcp_tool grep =>
3160 "Search regular files up to 1 MiB recursively; skip symlinks and .git. "
3161 . "Literal match default; mode=pcre uses GNU grep -P. "
3162 . "Stop at limit; report truncation and timeout separately.",
3163 {
3164 type => "object",
3165 properties => {
3166 path => {
3167 type => "string",
3168 description => "Search root; omitted/empty = .",
3169 },
3170 pattern => {
3171 type => "string",
3172 minLength => 1,
3173 },
3174 mode => {
3175 type => "string",
3176 enum => ["fixed", "pcre"],
3177 default => "fixed",
3178 },
3179 limit => {
3180 type => "integer",
3181 minimum => 1,
3182 maximum => 1000,
3183 default => 200,
3184 description => "Max matching lines.",
3185 },
3186 workdir => $workdir_schema,
3187 reason => {
3188 type => "string",
3189 description => "Why access needed.",
3190 },
3191 },
3192 required => ["pattern"],
3193 additionalProperties => JSON::XS::false,
3194 },
3195 7 ▶ sub {
Subroutine __ANON__: called CC=9 SCAR=24.8
3196 7 my ($req, $args) = @_;
3197  
3198 7 my ($workdir, $identity) = fs_workdir $args->{workdir};
3199 7 ▶ my $path = fs_path $workdir, length $args->{path} ? $args->{path} : ".";
Branch: 1 branch
BranchTrueFalseTotal
length $args->{'path'} ? : 7 0 7
3200 7 ▶ my $mode = $args->{mode} // "fixed";
Condition50%1/2
$args->{"mode"} // "fixed"
l!l
07
MC/DC0%0/1
$args->{"mode"} // "fixed"
$args->{"mode"}
Truth table50%1/2
A
A= $args->{"mode"}
Aresult
11
00
3201 7 ▶ $mode eq "fixed" or $mode eq "pcre"
Branch: 1 branch
BranchTrueFalseTotal
$mode eq "fixed" or $mode eq "pcre" or die "invalid grep mode\n" 7 0 7
Condition33%1/3
$mode eq "fixed" or $mode eq "pcre"
l!l&&r!l&&!r
700
MC/DC0%0/2
$mode eq "fixed" or $mode eq "pcre"
$mode eq "fixed" $mode eq "pcre"
Truth table33%1/3
A or B
A= $mode eq "fixed"B= $mode eq "pcre"
ABresult
1X1
011
000
3202 or die "invalid grep mode\n";
3203 7 ▶ my $limit = $args->{limit} // 200;
Condition50%1/2
$args->{"limit"} // 200
l!l
07
MC/DC0%0/1
$args->{"limit"} // 200
$args->{"limit"}
Truth table50%1/2
A
A= $args->{"limit"}
Aresult
11
00
3204 7 ▶ $limit <= 1000
Branch: 1 branch
BranchTrueFalseTotal
$limit <= 1000 or die "invalid limit\n" 7 0 7
3205 or die "invalid limit\n";
3206 my $granted = fs_require_paths ($req, $workdir, $identity, [$path], "read",
3207 7 ▶ $args->{reason} // "grep $path");
Condition50%1/2
$args->{"reason"} // "grep $path"
l!l
07
MC/DC0%0/1
$args->{"reason"} // "grep $path"
$args->{"reason"}
Truth table50%1/2
A
A= $args->{"reason"}
Aresult
11
00
3208  
3209 7 AE::log debug => join " ", "fs grep", $path, $mode, (substr $args->{pattern}, 0, 40);
3210  
3211 7 my $find_path = AnyEvent::MCP::utf8enc $path;
3212 7 my $pattern = AnyEvent::MCP::utf8enc $args->{pattern};
3213 7 ▶ my @command = (
Branch: 1 branch
BranchTrueFalseTotal
$mode eq 'pcre' ? : 0 7 7
3214 (fs_sandbox $workdir, $granted),
3215 $find, $find_path,
3216 "-name", ".git", "-prune", "-o",
3217 "-type", "f",
3218 "-size", "-1048577c",
3219 "-exec",
3220 # GNU find treats any nonzero -exec ... + batch as failure.
3221 # grep uses 1 for no matches, which is a successful empty search;
3222 # preserve all other errors (including find traversal failures).
3223 "/bin/sh", "-c", q{"$@" || [ "$?" -eq 1 ]}, "sh",
3224 $grep, ($mode eq "pcre" ? "-P" : "-F"),
3225 "-I", "-H", "-n", "--color=never", "-e", $pattern,
3226 "{}", "+",
3227 );
3228  
3229 6 ▶ fs_run $req, \@command, "", 30, 1024 * 1024, $limit, sub {
Subroutine __ANON__: called CC=7 SCAR=22.5
3230 6 my ($success, $result) = @_;
3231  
3232 6 ▶ return $req->error ($result)
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 6 6
3233 unless $success;
3234  
3235 6 my $response;
3236 6 my $ok = eval {
3237 6 my $stdout = AnyEvent::MCP::utf8dec $result->{stdout};
3238 6 my $stderr = AnyEvent::MCP::utf8dec $result->{stderr};
3239  
3240 6 ▶ if (($result->{exit} or $result->{signal})
Branch: 1 branch
BranchTrueFalseTotal
if ($result->{"exit"} || $result->{"signal"} and not $result->{"truncated"} and not $result->{"timed_out"}) 0 6 6
Condition33%3/9
$result->{"exit"} || $result->{"signal"} and not $result->{"truncated"} and not $result->{"timed_out"}
!ll&&!rl&&r
600
$result->{"exit"} || $result->{"signal"} and not $result->{"truncated"}
!ll&&!rl&&r
600
$result->{"exit"} or $result->{"signal"}
l!l&&r!l&&!r
006
MC/DC0%0/4
$result->{"exit"} || $result->{"signal"} and not $result->{"truncated"} and not $result->{"timed_out"}
$result->{"exit"} $result->{"signal"} not $result->{"truncated"} not $result->{"timed_out"}
Truth table14%1/7
A or B and not(C) and not(D)
A= $result->{"exit"}B= $result->{"signal"}C= not $result->{"truncated"}D= not $result->{"timed_out"}
ABCDresult
00XX0
1X0X0
010X0
1X100
01100
1X111
01111
3241 and !$result->{truncated} and !$result->{timed_out}) {
3242 0 die "grep failed (exit $result->{exit}, signal $result->{signal}): $stderr\n";
3243 }
3244  
3245 $response = {
3246 stdout => $stdout,
3247 stderr => $stderr,
3248 timed_out => $result->{timed_out},
3249 truncated => $result->{truncated},
3250 6 };
3251 6 1
3252 };
3253 6 ▶ return $req->error ($@)
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 6 6
3254 unless $ok;
3255  
3256 6 $req->reply (fs_result $response);
3257 7 };
3258 }
3259 125 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$find and $grep and mcp_tool("grep", "Search regular files up to 1 MiB recursively; skip symlinks and .git. Literal match default; mode=pcre uses GNU grep -P. Stop at limit; report truncation and timeout separately.", {"type", "object", "properties", {"path", {"type", "string", "description", "Search root; omitted/empty = ."}, "pattern", {"type", "string", "minLength", 1}, "mode", {"type", "string", "enum", ["fixed", "pcre"], "default", "fixed"}, "limit", {"type", "integer", "minimum", 1, "maximum", 1000, "default", 200, "description", "Max matching lines."}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "required", ["pattern"], "additionalProperties", &JSON::XS::false()}, sub { my($req, $args) = @_; my($workdir, $identity) = fs_workdir($args->{"workdir"}); my $path = fs_path($workdir, length $args->{"path"} ? $args->{"path"} : "."); my $mode = $args->{"mode"} // "fixed"; $mode eq "fixed" or $mode eq "pcre" or die "invalid grep mode\n"; my $limit = $args->{"limit"} // 200; $limit <= 1000 or die "invalid limit\n"; my $granted = fs_require_paths($req, $workdir, $identity, [$path], "read", $args->{"reason"} // "grep $path"); &AE::log("debug", join(" ", "fs grep", $path, $mode, substr($args->{"pattern"}, 0, 40))); my $find_path = &AnyEvent::MCP::utf8enc($path); my $pattern = &AnyEvent::MCP::utf8enc($args->{"pattern"}); my(@command) = (fs_sandbox($workdir, $granted), $find, $find_path, "-name", ".git", "-prune", "-o", "-type", "f", "-size", "-1048577c", "-exec", "/bin/sh", "-c", "\"\$\@\" || [ \"\$?\" -eq 1 ]", "sh", $grep, $mode eq "pcre" ? "-P" : "-F", "-I", "-H", "-n", "--color=never", "-e", $pattern, "{}", "+"); fs_run($req, \@command, "", 30, 1048576, $limit, sub { my($success, $result) = @_; return $req->error($result) unless $success; my $response; my $ok = eval { do { my $stdout = &AnyEvent::MCP::utf8dec($result->{"stdout"}); my $stderr = &AnyEvent::MCP::utf8dec($result->{"stderr"}); if ($result->{"exit"} || $result->{"signal"} and not $result->{"truncated"} and not $result->{"timed_out"}) { die qq[grep failed (exit $result->{"exit"}, signal $result->{"signal"}): $stderr\n]; } ; $response = {"stdout", $stdout, "stderr", $stderr, "timed_out", $result->{"timed_out"}, "truncated", $result->{"truncated"}}; 1 } }; return $req->error($@) unless $ok; $req->reply(fs_result($response)); } ); } ) 125 0 125
Condition33%1/3
$find and $grep
!ll&&!rl&&r
00125
MC/DC0%0/2
$find and $grep
$find $grep
Truth table33%1/3
A and B
A= $findB= $grep
ABresult
0X0
100
111
3260  
3261 125 my $stat = q{#perl
3262 map {
3263 my @s = lstat $_;
3264  
3265 pack "(w/a*)*", (@s
3266 ? (1, (-l _ ? "link" : -d _ ? "directory" : -f _ ? "file" : "other"), @s)
3267 : (0, "lstat: $!"))
3268 } @ARGV
3269 };
3270  
3271 $perl && mcp_tool stat =>
3272 "lstat up to 100 paths; no symlink following.",
3273 {
3274 type => "object",
3275 properties => {
3276 paths => {
3277 type => "array",
3278 items => {
3279 type => "string",
3280 },
3281 minItems => 1,
3282 maxItems => 100,
3283 },
3284 workdir => $workdir_schema,
3285 reason => {
3286 type => "string",
3287 description => "Why access needed.",
3288 },
3289 },
3290 required => ["paths"],
3291 additionalProperties => JSON::XS::false,
3292 },
3293 92 ▶ sub {
Subroutine __ANON__: called CC=6 SCAR=18.6
3294 92 my ($req, $args) = @_;
3295  
3296 92 my ($workdir, $identity) = fs_workdir $args->{workdir};
3297 92 ▶ ARRAY:: eq ref $args->{paths} and @{$args->{paths}} and @{$args->{paths}} <= 100
Branch: 1 branch
BranchTrueFalseTotal
"ARRAY" eq ref $args->{"paths"} and @{$args->{"paths"};} and @{$args->{"paths"};} <= 100 or die "stat needs 1..100 paths\n" 92 0 92
Condition33%2/6
"ARRAY" eq ref $args->{"paths"} and @{$args->{"paths"};} and @{$args->{"paths"};} <= 100
!ll&&!rl&&r
0092
"ARRAY" eq ref $args->{"paths"} and @{$args->{"paths"};}
!ll&&!rl&&r
0092
MC/DC0%0/3
"ARRAY" eq ref $args->{"paths"} and @{$args->{"paths"};} and @{$args->{"paths"};} <= 100
"ARRAY" eq ref $args->{"paths"} @{$args->{"paths"};} @{$args->{"paths"};} <= 100
Truth table25%1/4
A and B and C
A= "ARRAY" eq ref $args->{"paths"}B= @{$args->{"paths"};}C= @{$args->{"paths"};} <= 100
ABCresult
0XX0
10X0
1100
1111
3298 or die "stat needs 1..100 paths\n";
3299 92 my @paths = map { fs_path $workdir, $_ } @{$args->{paths}};
3300 die "stat paths must be inside the selected workdir\n"
3301 92 ▶ if grep { !fs_inside ($_, $workdir) } @paths;
Branch: 1 branch
BranchTrueFalseTotal
if grep {not fs_inside($_, $workdir);} @paths 2 90 92
3302  
3303 90 my $granted = fs_require_paths $req, $workdir, $identity, \@paths, "read", $args->{reason};
3304  
3305 50 my @log = @paths;
3306 50 ▶ splice @log, 3, @log - 3, "..." if @log > 3;
Branch: 1 branch
BranchTrueFalseTotal
if @log > 3 0 50 50
3307 50 AE::log debug => join " ", "fs stat", @log;
3308  
3309 90 perl_eval $req, $workdir, $granted, $stat, [map { AnyEvent::MCP::utf8enc $_ } @paths],
3310 48 ▶ 30, sub {
Subroutine __ANON__: called CC=5 SCAR=16.7
3311 48 my ($success, $result) = @_;
3312  
3313 48 ▶ return $req->error ($result)
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 48 48
3314 unless $success;
3315  
3316 48 ▶ @$result == @paths
Branch: 1 branch
BranchTrueFalseTotal
@$result == @paths or return $req->error("invalid stat response\n") 48 0 48
3317 or return $req->error ("invalid stat response\n");
3318  
3319 48 my @result;
3320 48 for my $i (0 .. $#paths) {
3321 87 my ($ok, @s) = unpack "(w/a*)*", $result->[$i];
3322  
3323 87 ▶ if ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ok) { } 87 0 87
3324 87 my $type = shift @s;
3325 87 push @result, +{
3326 path => $paths[$i],
3327 type => $type,
3328 size => 0 + $s[7],
3329 mode => (sprintf "%04o", $s[2] & 07777),
3330 uid => 0 + $s[4],
3331 gid => 0 + $s[5],
3332 mtime => 0 + $s[9],
3333 };
3334 } else {
3335 0 push @result, +{
3336 path => $paths[$i],
3337 error => AnyEvent::MCP::utf8dec $s[0],
3338 };
3339 }
3340 }
3341  
3342 48 $req->reply (fs_result { result => \@result });
3343 50 };
3344 }
3345 125 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$perl and mcp_tool("stat", "lstat up to 100 paths; no symlink following.", {"type", "object", "properties", {"paths", {"type", "array", "items", {"type", "string"}, "minItems", 1, "maxItems", 100}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "required", ["paths"], "additionalProperties", &JSON::XS::false()}, sub { my($req, $args) = @_; my($workdir, $identity) = fs_workdir($args->{"workdir"}); "ARRAY" eq ref $args->{"paths"} and @{$args->{"paths"};} and @{$args->{"paths"};} <= 100 or die "stat needs 1..100 paths\n"; my(@paths) = map({fs_path($workdir, $_);} @{$$args{"paths"};}); die "stat paths must be inside the selected workdir\n" if grep {not fs_inside($_, $workdir);} @paths; my $granted = fs_require_paths($req, $workdir, $identity, \@paths, "read", $args->{"reason"}); my(@log) = @paths; splice @log, 3, @log - 3, "..." if @log > 3; &AE::log("debug", join(" ", "fs stat", @log)); perl_eval($req, $workdir, $granted, $stat, [map({&AnyEvent::MCP::utf8enc($_);} @paths)], 30, sub { my($success, $result) = @_; return $req->error($result) unless $success; @$result == @paths or return $req->error("invalid stat response\n"); my @result; foreach my $i (0 .. $#paths) { my($ok, @s) = unpack("(w/a*)*", $result->[$i]); if ($ok) { my $type = shift @s; push @result, {"path", $paths[$i], "type", $type, "size", 0 + $s[7], "mode", sprintf("%04o", $s[2] & 4095), "uid", 0 + $s[4], "gid", 0 + $s[5], "mtime", 0 + $s[9]}; } else { push @result, {"path", $paths[$i], "error", &AnyEvent::MCP::utf8dec($s[0])}; } ; } ; $req->reply(fs_result({"result", \@result})); } ); } ) 125 0 125
3346  
3347 mcp_tool exec =>
3348 "Run argv " . ($bwrap ? "in bubblewrap. " : "UNSANDBOXED with full host-user privileges. ")
3349 . ($bwrap ? "Private /tmp by default (gone after exec); use for temp files/IPC. shared-tmp exposes HOST /tmp (sockets/services). Request ONLY for HOST /tmp, NOT ordinary temp/IPC. " : "")
3350 . "stdin_encoding: utf-8 (default), latin1 or base64; max 4 MiB decoded. "
3351 . "stdout/stderr UTF-8, captured to 1 MiB each; max_lines/max_bytes bound response. Optional grep: PCRE stdout filter after capture; stderr unfiltered. Reports capture truncation. "
3352 . "Explicit sandbox_grants replace default workdir-read. Exit/signal/timeout are normal results, not tool errors. No command-prefix safety classification. Timeout >300 s requires "
3353 . "long-running grant; max six hours.",
3354 {
3355 type => "object",
3356 properties => {
3357 %output_schema,
3358 workdir => $workdir_schema,
3359 argv => {
3360 type => "array",
3361 items => { type => "string" },
3362 minItems => 1,
3363 },
3364 sandbox_grants => {
3365 type => "array",
3366 description => "Providing sandbox_grants (even []) replaces this default entirely; otherwise workdir-read under bubblewrap. Without bubblewrap: full host authority. host-proc unavailable under bubblewrap.",
3367 items => {
3368 type => "string",
3369 enum => [sort keys %sandbox_grant],
3370 },
3371 },
3372 reason => {
3373 type => "string",
3374 description => "Why command needs authority.",
3375 },
3376 stdin => { type => "string" },
3377 stdin_encoding => {
3378 type => "string",
3379 default => "utf-8",
3380 enum => [qw(utf-8 latin1 base64)],
3381 description => "stdin bytes: UTF-8 (default), Latin-1 code points U+0000..U+00FF, or canonical Base64; max 4 MiB decoded.",
3382 },
3383 timeout => {
3384 type => "integer",
3385 minimum => 1,
3386 maximum => 21600,
3387 default => 30,
3388 description => "Timeout seconds; >300 also requires long-running grant.",
3389 },
3390 },
3391 required => [qw(argv reason)],
3392 additionalProperties => JSON::XS::false,
3393 },
3394 659 ▶ sub {
Subroutine __ANON__: called CC=32 SCAR=35.2
3395 659 my ($req, $args) = @_;
3396  
3397 659 my $output = fs_output_options $args;
3398  
3399 623 ▶ ARRAY:: eq ref $args->{argv} and @{$args->{argv}}
Branch: 1 branch
BranchTrueFalseTotal
"ARRAY" eq ref $args->{"argv"} and @{$args->{"argv"};} or die "exec needs argv strings without NUL\n" 623 0 623
Condition33%1/3
"ARRAY" eq ref $args->{"argv"} and @{$args->{"argv"};}
!ll&&!rl&&r
00623
MC/DC0%0/2
"ARRAY" eq ref $args->{"argv"} and @{$args->{"argv"};}
"ARRAY" eq ref $args->{"argv"} @{$args->{"argv"};}
Truth table33%1/3
A and B
A= "ARRAY" eq ref $args->{"argv"}B= @{$args->{"argv"};}
ABresult
0X0
100
111
3400 or die "exec needs argv strings without NUL\n";
3401 623 for my $arg (@{$args->{argv}}) {
3402 1862 ▶ defined $arg and !ref $arg and $arg !~ /\0/
Branch: 1 branch
BranchTrueFalseTotal
defined $arg and not ref $arg and not $arg =~ /\0/u or die "exec needs argv strings without NUL\n" 1862 0 1862
Condition33%2/6
defined $arg and not ref $arg and not $arg =~ /\0/u
!ll&&!rl&&r
001862
defined $arg and not ref $arg
!ll&&!rl&&r
001862
MC/DC0%0/3
defined $arg and not ref $arg and not $arg =~ /\0/u
defined $arg not ref $arg not $arg =~ /\0/u
Truth table25%1/4
A and not(B) and not(C)
A= defined $argB= not ref $argC= not $arg =~ /\0/u
ABCresult
0XX0
10X0
1100
1111
3403 or die "exec needs argv strings without NUL\n";
3404 }
3405 623 ▶ length $args->{argv}[0] or die "exec needs an executable\n";
Branch: 1 branch
BranchTrueFalseTotal
length $args->{"argv"}[0] or die "exec needs an executable\n" 623 0 623
3406  
3407 623 my ($workdir, $identity) = fs_workdir $args->{workdir};
3408 623 ▶ my $timeout = $args->{timeout} // 30;
Condition100%2/2
$args->{"timeout"} // 30
l!l
27596
MC/DC100%1/1
$args->{"timeout"} // 30
$args->{"timeout"}
Truth table100%2/2
A
A= $args->{"timeout"}
Aresult
11
00
3409 623 ▶ $timeout >= 1 && $timeout <= 21600 && $timeout == int $timeout
Branch: 1 branch
BranchTrueFalseTotal
$timeout >= 1 and $timeout <= 21600 and $timeout == int $timeout or die "invalid timeout\n" 621 2 623
Condition66%4/6
$timeout >= 1 and $timeout <= 21600 and $timeout == int $timeout
!ll&&!rl&&r
20621
$timeout >= 1 and $timeout <= 21600
!ll&&!rl&&r
02621
MC/DC33%1/3
$timeout >= 1 and $timeout <= 21600 and $timeout == int $timeout
$timeout >= 1 $timeout <= 21600 $timeout == int $timeout
Truth table50%2/4
A and B and C
A= $timeout >= 1B= $timeout <= 21600C= $timeout == int $timeout
ABCresult
0XX0
10X0
1100
1111
3410 or die "invalid timeout\n";
3411  
3412 621 ▶ my $sandbox_grants = [exists $args->{sandbox_grants} ? @{$args->{sandbox_grants}} : @exec_default_sandbox_grants];
Branch: 1 branch
BranchTrueFalseTotal
exists $args->{'sandbox_grants'} ? : 69 552 621
3413 621 ▶ push @$sandbox_grants, "long-running" if $timeout > 300;
Branch: 1 branch
BranchTrueFalseTotal
if $timeout > 300 17 604 621
3414 621 $sandbox_grants = [fs_effective_grants @$sandbox_grants];
3415 621 my $requested = $permissions->closure ($sandbox_grants);
3416 die "host-proc sandbox authority is unresolved and unavailable in v1\n"
3417 621 ▶ if $bwrap && $requested->{"host-proc"};
Branch: 1 branch
BranchTrueFalseTotal
if $bwrap and $requested->{"host-proc"} 0 621 621
Condition66%2/3
$bwrap and $requested->{"host-proc"}
!ll&&!rl&&r
76140
MC/DC0%0/2
$bwrap and $requested->{"host-proc"}
$bwrap $requested->{"host-proc"}
Truth table66%2/3
A and B
A= $bwrapB= $requested->{"host-proc"}
ABresult
0X0
100
111
3418  
3419 621 ▶ my $stdin_text = $args->{stdin} // "";
Condition100%2/2
$args->{"stdin"} // ""
l!l
221400
MC/DC100%1/1
$args->{"stdin"} // ""
$args->{"stdin"}
Truth table100%2/2
A
A= $args->{"stdin"}
Aresult
11
00
3420 621 ▶ my $stdin_encoding = $args->{stdin_encoding} // "utf-8";
Condition100%2/2
$args->{"stdin_encoding"} // "utf-8"
l!l
132489
MC/DC100%1/1
$args->{"stdin_encoding"} // "utf-8"
$args->{"stdin_encoding"}
Truth table100%2/2
A
A= $args->{"stdin_encoding"}
Aresult
11
00
3421 621 ▶ $stdin_encoding =~ /\A(?:utf-8|latin1|base64)\z/
Branch: 1 branch
BranchTrueFalseTotal
$stdin_encoding =~ /\A(?:utf-8|latin1|base64)\z/u or die "invalid stdin_encoding\n" 611 10 621
3422 or die "invalid stdin_encoding\n";
3423 611 my $input;
3424 611 ▶ if ($stdin_encoding eq "utf-8") {
Branch: 2 branches
BranchTrueFalseTotal
if ($stdin_encoding eq 'utf-8') { } 489 122 611
elsif ($stdin_encoding eq 'latin1') { } 34 88 122
3425 489 $input = AnyEvent::MCP::utf8enc $stdin_text;
3426 } elsif ($stdin_encoding eq "latin1") {
3427 34 ▶ $stdin_text !~ /[^\x00-\xff]/
Branch: 1 branch
BranchTrueFalseTotal
$stdin_text =~ /[^\x00-\xff]/u and die "latin1 stdin contains code points above U+00FF\n" 10 24 34
3428 or die "latin1 stdin contains code points above U+00FF\n";
3429 24 $input = pack "C*", unpack "U*", $stdin_text;
3430 } else {
3431 88 $input = MIME::Base64::decode_base64 $stdin_text;
3432 88 ▶ MIME::Base64::encode_base64 ($input, "") eq $stdin_text
Branch: 1 branch
BranchTrueFalseTotal
&MIME::Base64::encode_base64($input, "") eq $stdin_text or die "invalid base64 stdin\n" 68 20 88
3433 or die "invalid base64 stdin\n";
3434 }
3435 581 ▶ length $input <= 4 * 1024 * 1024 or die "stdin exceeds 4 MiB\n";
Branch: 1 branch
BranchTrueFalseTotal
length $input <= 4194304 or die "stdin exceeds 4 MiB\n" 573 8 581
3436 573 my $stdin_detail = $stdin_text;
3437 573 ▶ if (length $input && $stdin_encoding ne "utf-8") {
Branch: 1 branch
BranchTrueFalseTotal
if (length $input and $stdin_encoding ne "utf-8") 84 489 573
Condition100%3/3
length $input and $stdin_encoding ne "utf-8"
!ll&&!rl&&r
4008984
MC/DC100%2/2
length $input and $stdin_encoding ne "utf-8"
length $input $stdin_encoding ne "utf-8"
Truth table100%3/3
A and B
A= length $inputB= $stdin_encoding ne "utf-8"
ABresult
0X0
100
111
3438 84 my $preview = substr $input, 0, 4096;
3439 84 $preview =~ s/([^\x20-\x5b\x5d-\x7e])/sprintf "\\x{%02X}", ord $1/ge;
3440 84 $stdin_detail = "$stdin_encoding stdin: " . length ($input) . " bytes (escaped preview)\n\n" . $preview;
3441 84 ▶ $stdin_detail .= "\n... (preview limited to 4096 bytes)"
Branch: 1 branch
BranchTrueFalseTotal
if length $input > 4096 38 46 84
3442 if length $input > 4096;
3443 }
3444  
3445 573 my $coder = JSON::XS->new->canonical;
3446 573 my $subject = $coder->encode ($args->{argv});
3447 573 my $executable = $coder->encode ($args->{argv}[0]);
3448 my $granted = fs_require_permission ($req, $identity, {
3449 tool => "exec",
3450 action => "exec",
3451 dimensions => fs_permission_dimensions (fs_grant_workdir ($identity, $sandbox_grants),
3452 $subject, [
3453 { label => "exact executable and argv", match => $subject },
3454 { label => "this executable, arbitrary argv",
3455 match => "^\\[\Q$executable\E(?:,.*)?\\]\\z" },
3456 { label => "any command", match => "^" },
3457 ]),
3458 reason => $args->{reason},
3459 573 ▶ sandbox_grants => $sandbox_grants,
Branch: 1 branch
BranchTrueFalseTotal
length $input ? : 173 400 573
3460 (length $input ? (details => { "View stdin" => $stdin_detail }) : ()),
3461 });
3462  
3463 300 ▶ $timeout <= 300 || $permissions->closure ($granted)->{"long-running"}
Branch: 1 branch
BranchTrueFalseTotal
$timeout <= 300 or $permissions->closure($granted)->{"long-running"} or die "permission reduced below long-running for exec\n" 298 2 300
Condition100%3/3
$timeout <= 300 or $permissions->closure($granted)->{"long-running"}
l!l&&r!l&&!r
29352
MC/DC100%2/2
$timeout <= 300 or $permissions->closure($granted)->{"long-running"}
$timeout <= 300 $permissions->closure($granted)->{"long-running"}
Truth table100%3/3
A or B
A= $timeout <= 300B= $permissions->closure($granted)->{"long-running"}
ABresult
1X1
011
000
3464 or die "permission reduced below long-running for exec\n";
3465  
3466 298 ▶ AE::log debug => "fs exec "
Branch: 2 branches
BranchTrueFalseTotal
length $subject > 200 ? : 7 291 298
length $input ? : 89 209 298
3467 . (substr $subject, 0, 200)
3468 . (length $subject > 200 ? "..." : "")
3469 . (length $input ? " stdin=" . length ($input) : "");
3470  
3471 298 fs_command $req, $workdir, $granted, $args->{argv}, $input, $timeout, $output;
3472 }
3473 125 ▶;
Branch: 2 branches
BranchTrueFalseTotal
$bwrap ? : 119 6 125
$bwrap ? : 119 6 125
3474  
3475 # fixed operations accept filenames, never caller-supplied VCS options or shell code.
3476 125 for my $operation (qw(diff status log)) {
3477 mcp_tool "vcs-$operation" =>
3478 "Run $operation via Git, SVN, CVS or Mercurial in workdir. "
3479 . "Explicit backend; cwd within workdir (default .). "
3480 . "files relative to cwd; must stay in workdir; never options. "
3481 . "Dedicated permission plus workdir-read; CVS and SVN log also need ssh-agent/network. "
3482 . "Returns exit/signal, bounded stdout/stderr, truncation flags. "
3483 . "grep filters stdout via PCRE after 1 MiB capture; max_lines/max_bytes bound output. "
3484 . "Trusts VCS client/config; sandbox enforces approved filesystem/network grants.",
3485 {
3486 type => "object",
3487 properties => {
3488 workdir => $workdir_schema,
3489 cwd => { type => "string", default => ".",
3490 description => "cwd relative to workdir; empty = .; must stay inside. Mount boundary unchanged." },
3491 backend => { type => "string", enum => [qw(git svn cvs hg)] },
3492 files => { type => "array", items => { type => "string" }, default => [] },
3493 %output_schema,
3494 },
3495 required => ["backend"],
3496 additionalProperties => JSON::XS::false,
3497 },
3498 1182 ▶ sub {
Subroutine __ANON__: called CC=25 SCAR=32.4
3499 1182 my ($req, $args) = @_;
3500  
3501 1182 my $backend = $args->{backend};
3502 1182 ▶ defined $backend && !ref $backend && $backend =~ /\A(?:git|svn|cvs|hg)\z/
Branch: 1 branch
BranchTrueFalseTotal
defined $backend and not ref $backend and $backend =~ /\A(?:git|svn|cvs|hg)\z/u or die "backend must be git, svn, cvs or hg\n" 1182 0 1182
Condition33%2/6
defined $backend and not ref $backend and $backend =~ /\A(?:git|svn|cvs|hg)\z/u
!ll&&!rl&&r
001182
defined $backend and not ref $backend
!ll&&!rl&&r
001182
MC/DC0%0/3
defined $backend and not ref $backend and $backend =~ /\A(?:git|svn|cvs|hg)\z/u
defined $backend not ref $backend $backend =~ /\A(?:git|svn|cvs|hg)\z/u
Truth table25%1/4
A and not(B) and C
A= defined $backendB= not ref $backendC= $backend =~ /\A(?:git|svn|cvs|hg)\z/u
ABCresult
0XX0
10X0
1100
1111
3503 or die "backend must be git, svn, cvs or hg\n";
3504 1182 ▶ my $program = $vcs_program{$backend}
Branch: 1 branch
BranchTrueFalseTotal
my $program = $vcs_program{$backend} or die "$backend executable is unavailable\n" 1182 0 1182
3505 or die "$backend executable is unavailable\n";
3506 1182 my $output = fs_output_options $args;
3507 1182 my ($workdir, $identity) = fs_workdir $args->{workdir};
3508 1182 ▶ my $cwd = fs_path $workdir, length $args->{cwd} ? $args->{cwd} : ".";
Branch: 1 branch
BranchTrueFalseTotal
length $args->{'cwd'} ? : 307 875 1182
3509 1182 ▶ fs_inside $cwd, $workdir or die "VCS cwd must stay within the selected workdir\n";
Branch: 1 branch
BranchTrueFalseTotal
fs_inside($cwd, $workdir) or die "VCS cwd must stay within the selected workdir\n" 1163 19 1182
3510 1163 ▶ my $files = $args->{files} // [];
Condition100%2/2
$args->{"files"} // []
l!l
703460
MC/DC100%1/1
$args->{"files"} // []
$args->{"files"}
Truth table100%2/2
A
A= $args->{"files"}
Aresult
11
00
3511 1163 ▶ ref $files eq "ARRAY" or die "files must be an array of filenames\n";
Branch: 1 branch
BranchTrueFalseTotal
ref $files eq "ARRAY" or die "files must be an array of filenames\n" 1163 0 1163
3512 1163 my @files;
3513 1163 my @paths = ($cwd);
3514 1163 for my $file (@$files) {
3515 703 my $path = fs_path $cwd, $file;
3516 684 ▶ fs_inside $path, $workdir or die "VCS files must stay within the selected workdir\n";
Branch: 1 branch
BranchTrueFalseTotal
fs_inside($path, $workdir) or die "VCS files must stay within the selected workdir\n" 668 16 684
3517 668 push @paths, $path;
3518 668 my $relative = File::Spec::Unix->abs2rel ($path, $cwd);
3519 668 push @files, "./$relative";
3520 }
3521  
3522 1128 ▶ my @argv = $backend eq "git"
Branch: 8 branches
BranchTrueFalseTotal
$backend eq 'git' ? : 410 718 1128
$operation eq 'diff' ? : 120 290 410
$operation eq 'status' ? : 222 68 290
$backend eq 'svn' ? : 270 448 718
$operation eq 'diff' ? : 112 158 270
$backend eq 'cvs' ? : 250 198 448
$operation eq 'diff' ? : 104 146 250
$operation eq 'log' ? : 56 90 146
3523 ? ($program, "--no-pager", "--no-optional-locks", "--literal-pathspecs", "-c", "core.fsmonitor=false",
3524 $operation, ($operation eq "diff" ? qw(--no-ext-diff --no-textconv --no-color --ignore-submodules)
3525 : $operation eq "status" ? qw(--short --untracked-files=normal --ignore-submodules)
3526 : qw(--no-decorate)),
3527 "--", @files)
3528 : $backend eq "svn"
3529 ? ($program, "--non-interactive", "--no-auth-cache", $operation,
3530 ($operation eq "diff" ? ("--internal-diff") : ()), "--", map "$_\@", @files)
3531 : $backend eq "cvs"
3532 ? ($program, "-f", $operation,
3533 ($operation eq "diff" ? ("-u") : $operation eq "log" ? ("-N") : ()),
3534 "--", @files)
3535 : ($program, "--noninteractive", "--config", "ui.paginate=never", $operation, "--", @files);
3536  
3537 1128 ▶ my @need = fs_effective_grants ("workdir-read",
Branch: 1 branch
BranchTrueFalseTotal
$backend eq 'cvs' || $backend eq 'svn' && $operation eq 'log' ? : 344 784 1128
Condition100%6/6
$backend eq "cvs" or $backend eq "svn" and $operation eq "log"
l!l&&r!l&&!r
25094784
$backend eq "svn" and $operation eq "log"
!ll&&!rl&&r
60817694
MC/DC100%3/3
$backend eq "cvs" or $backend eq "svn" and $operation eq "log"
$backend eq "cvs" $backend eq "svn" $operation eq "log"
Truth table100%4/4
A or B and C
A= $backend eq "cvs"B= $backend eq "svn"C= $operation eq "log"
ABCresult
1XX1
0111
00X0
0100
3538 ($backend eq "cvs" || $backend eq "svn" && $operation eq "log" ? ("ssh-agent") : ()));
3539 my $granted = fs_require_permission ($req, $identity, {
3540 1128 ▶ tool => $req->{tool}, action => "vcs-$operation",
Branch: 1 branch
BranchTrueFalseTotal
@files ? : 668 460 1128
3541 dimensions => fs_permission_dimensions (fs_grant_workdir ($identity, \@need),
3542 $backend, [
3543 { label => "$backend working copies", match => $backend },
3544 { label => "all supported VCS clients", match => "^" },
3545 ]),
3546 sandbox_grants => \@need, paths => \@paths,
3547 reason => "$backend $operation in $cwd (workdir $identity)"
3548 . (@files ? ": " . join (", ", @files) : " (entire working copy)"),
3549 });
3550 564 my $have = $permissions->closure ($granted);
3551 564 ▶ $have->{$_} or die "permission reduced below $_ for $req->{tool}\n" for @need;
Branch: 1 branch
BranchTrueFalseTotal
$have->{$_} or die qq[permission reduced below $_ for $req->{"tool"}\n] 704 32 736
3552  
3553 532 AE::log debug => join " ", "fs vcs-$operation", $backend, $cwd, @files;
3554  
3555 532 fs_command $req, $workdir, $granted, \@argv, "", 30, $output, $cwd;
3556 375 };
3557 }
3558  
3559 mcp_config
3560 name => $name,
3561 idle_exit => 300,
3562 server_name => "mcp-fs",
3563 server_version => 0,
3564 permissions => $permissions,
3565 347 ▶ on_error => sub { AE::log info => "mcp-tool $_[1]{tool}: $_[2]" },
Subroutine __ANON__: called CC=1 SCAR=0.0
3566 130 ▶ on_start => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
3567 130 ▶ print STDERR "Permission rules: $permissions->{file}\n"
Branch: 1 branch
BranchTrueFalseTotal
if $_[0]->isa("AnyEvent::MCP::Server::HTTP") 1 129 130
3568 if $_[0]->isa ("AnyEvent::MCP::Server::HTTP");
3569 },
3570 125 short_instructions => "Filesystem access: read/edit files, run sandboxed commands, inspect VCS in configured workdirs. Discover tools when working with files.",
3571 instructions =>
3572 "Start with workdirs: IDs/paths, mounts, sandbox_grants. "
3573 . "Select persistent integer ID (listing key, not array position) or configured/resolved path. "
3574 . "Inactive mappings expire after seven days; IDs may be reused; stale paths fail. "
3575 . "Paths relative to selected workdir. "
3576 . "workdir-read/write grant only selected workdir; all-workdirs-read/write grant every workdir. "
3577 . "all-workdirs-read + workdir-write: read all, write selected only. "
3578 . "Absolute paths in other workdirs need all-workdirs grants; other absolute paths need home/world grants or shared-tmp for host tmp. "
3579 . "Multi-path stat stays in selected workdir; rename across paths needs combined grants and may fail EXDEV at mount boundary. "
3580 . "Symlinks resolve inside granted mounts; overlapping workdir access unspecified. "
3581 . "Trusted mounts add baseline authority; world-read keeps writable exceptions, world-write ignores them. "
3582 . "exec requires useful reason and explicit sandbox_grants when needed. "
3583 . "Prefer vcs-diff/vcs-status/vcs-log for working copies: explicit backend, fixed argv, automatic grants. "
3584 . "exec/VCS: grep filters stdout via PCRE after capture; max_lines/max_bytes bound output; stderr unfiltered. "
3585 . "capture_truncated means possible unseen matches.\n";
3586  
3587 125 mcp_start %$server_options, (stdio => $stdio);
3588  
« lib/AnyEvent/MCP/IMAP/OAuth2.pm ↑ Summary blib/lib/AnyEvent/MCP/Server/HTTP.pm »