bin/mcp-fs

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