lib/Test/Permissions.pm

filter: Statementstmt 99.8% 532 / 533 Branchbran 100% 198 / 198 Conditioncond 90.9% 50 / 55 MC/DCmcdc 84.3% 27 / 32 Subroutinesub 100% 92 / 92 Podpod 100% 16 / 16 totaltotal 98.8% 915 / 926 CC 124 SCAR 17.6
CC
124
Cov
99%
_probe
15.0
_normalise_args
14.0
_check_args
12.0
CRAP 5.8
↑ Summary
1 package Test::Permissions;
2  
3 17 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 17 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 17 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 # Nothing is imported: every external function is called by its full name,
8 # so the only subroutines in this package are its own.
9 17 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 17 ▶use Cwd ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 17 ▶use Errno ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 17 ▶use File::Path ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 17 ▶use File::Spec ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 17 ▶use File::Temp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 17 ▶use Params::Get ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 17 ▶use Params::Validate::Strict ();
Subroutine BEGIN: called CC=1 SCAR=0.0
17 17 ▶use Readonly ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 17 ▶use Return::Set ();
Subroutine BEGIN: called CC=1 SCAR=0.0
19 17 ▶use overload ();
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 # Exporter is inherited rather than imported, for the same reason.
22 17 require Exporter;
23 17 our @ISA = ('Exporter'); ## no critic (ClassHierarchies::ProhibitExplicitISA)
24  
25 =head1 NAME
26  
27 Test::Permissions - Find out whether chmod can really take access away, so tests know when to skip
28  
29 =head1 VERSION
30  
31 0.001.3
32  
33 =cut
34  
35 17 our $VERSION = '0.001.3';
36  
37 # One tag per family of functions. A new family gets its own tag and
38 # prefix, and is added to :all.
39 17 our @EXPORT_OK = qw(
40 can_revoke_read can_revoke_write can_revoke_create can_revoke_search
41 can_revoke_exec can_revoke_delete can_revoke_sticky
42 can_revoke why_not skip_unless_can_revoke
43 acl_denies with_revoked permissions_report
44 clear_cache set_cache_scope set_messages
45 );
46 17 our %EXPORT_TAGS = (
47 all => [ @EXPORT_OK ],
48 revoke => [ qw(
49 can_revoke_read can_revoke_write can_revoke_create can_revoke_search
50 can_revoke_exec can_revoke_delete can_revoke_sticky
51 can_revoke why_not skip_unless_can_revoke
52 ) ],
53 acl => [ qw(acl_denies) ],
54 guard => [ qw(with_revoked) ],
55 report => [ qw(permissions_report) ],
56 );
57  
58 # -----------------------------------------------------------------------
59 # Constants
60 # -----------------------------------------------------------------------
61  
62 # Modes given to the scratch objects. Every object gets an explicit mode
63 # after it is created, so the result never depends on the caller's umask.
64 17 Readonly::Scalar my $MODE_NONE => 0;
65 17 Readonly::Scalar my $MODE_FILE_RW => oct '0600';
66 17 Readonly::Scalar my $MODE_FILE_RO => oct '0400';
67 17 Readonly::Scalar my $MODE_FILE_RWX => oct '0700';
68 17 Readonly::Scalar my $MODE_DIR_RWX => oct '0700';
69 17 Readonly::Scalar my $MODE_DIR_RX => oct '0500';
70 17 Readonly::Scalar my $MODE_DIR_ALL => oct '0777';
71 17 Readonly::Scalar my $MODE_DIR_STICKY => oct '01777';
72  
73 # The permission bits of st_mode, and the owner's share of them. The
74 # probe runs as the owner of its scratch objects, so only the owner bits
75 # decide whether access is allowed. Comparing just those bits also copes
76 # with Windows, where perl reports a read-only file as 0444: chmod 0 there
77 # still gives owner bits 0400 (caught), and chmod 0400 gives owner bits
78 # 0400 (correct). The sticky probe compares every bit, because the bit it
79 # is about is not an owner bit.
80 17 Readonly::Scalar my $MODE_BITS => oct '07777';
81 17 Readonly::Scalar my $OWNER_BITS => oct '0700';
82 17 Readonly::Scalar my $ANY_EXEC => oct '0111';
83  
84 # Where the owner, group and other permission bits start in st_mode, and
85 # the bit for each access within them.
86 17 Readonly::Scalar my $OWNER_SHIFT => 6;
87 17 Readonly::Scalar my $GROUP_SHIFT => 3;
88 17 Readonly::Scalar my $OTHER_SHIFT => 0;
89 17 Readonly::Hash my %ACCESS_BIT => (read => 4, write => 2, exec => 1);
90  
91 # Indexes into the list returned by stat.
92 17 Readonly::Scalar my $STAT_DEV => 0;
93 17 Readonly::Scalar my $STAT_MODE => 2;
94 17 Readonly::Scalar my $STAT_UID => 4;
95 17 Readonly::Scalar my $STAT_GID => 5;
96  
97 # The superuser.
98 17 Readonly::Scalar my $ROOT_UID => 0;
99  
100 # The two users the sticky probe acts as: the owner of the file, and
101 # another user who tries to delete it. They need not exist in the
102 # password file; 65534 is "nobody" on most systems.
103 17 Readonly::Scalar my $STICKY_OWNER_UID => 65_534;
104 17 Readonly::Scalar my $STICKY_OTHER_UID => 65_533;
105  
106 # Names inside the probe directory P.
107 17 Readonly::Scalar my $PROBE_TEMPLATE => 'test-permissions-XXXXXXXX';
108 17 Readonly::Scalar my $PROBE_FILE => 'f';
109 17 Readonly::Scalar my $PROBE_SUBDIR => 'd';
110 17 Readonly::Scalar my $PROBE_NEW => 'new';
111 17 Readonly::Scalar my $PROBE_CONTENT => 'x'; # the one byte of a read probe
112 17 Readonly::Scalar my $PROBE_SCRIPT => "#!/bin/sh\nexit 0\n";
113  
114 # open() modes used by the probes.
115 17 Readonly::Scalar my $OPEN_READ => '<';
116 17 Readonly::Scalar my $OPEN_APPEND => '>>';
117 17 Readonly::Scalar my $OPEN_TRUNCATE => '>';
118  
119 # The errnos that mean "permission denied". Any other failure of the
120 # attempt says nothing about permissions.
121 17 Readonly::Hash my %DENIED_ERRNO => map { $_ => 1 } (Errno::EACCES(), Errno::EPERM());
122  
123 # The errno reported when the exec probe's script runs but does not exit 0.
124 17 Readonly::Scalar my $ERRNO_BAD_EXIT => Errno::ENOEXEC();
125  
126 # Environment variables removed while the exec probe runs its script:
127 # taint mode refuses to run anything while they are set, and they could
128 # change what /bin/sh does.
129 17 Readonly::Array my @UNSAFE_ENV => qw(PATH IFS CDPATH ENV BASH_ENV);
130  
131 # Separates the parts of a cache key; cannot appear in a path.
132 17 Readonly::Scalar my $KEY_SEP => "\0";
133  
134 # Control characters and Unicode bidirectional controls ("Trojan Source",
135 # CVE-2021-42574). They are escaped in every path and error text placed
136 # in a message, so a hostile directory name cannot send escape sequences
137 # to the terminal or make a message display differently from its content.
138 17 Readonly::Scalar my $UNSAFE_CHARS_RE =>
139 qr/[\x00-\x1F\x7F-\x9F\x{061C}\x{200E}\x{200F}\x{202A}-\x{202E}\x{2066}-\x{2069}]/;
140  
141 # Characters that are unsafe in a byte string that is not valid UTF-8
142 # (C0 and C1 controls in Latin-1).
143 17 Readonly::Scalar my $UNSAFE_BYTES_RE => qr/[\x00-\x1F\x7F-\x9F]/;
144  
145 # Matches any string, capturing all of it: used to untaint a path that has
146 # already been checked (see _untaint).
147 17 Readonly::Scalar my $ANYTHING_RE => qr/\A(.*)\z/s;
148  
149 # How each kind of access is probed. Every kind follows the same steps
150 # (see _probe); this table holds what differs:
151 # precondition - optional; returns false if the probe cannot run here
152 # (reason_needs_root)
153 # setup - creates the scratch objects in P with explicit modes and
154 # returns { target => path to chmod, object => path to use,
155 # as => uid to act as (optional) }
156 # op - the operation; returns (ok, errno) and never throws
157 # tidy - optional; undoes a successful baseline so the attempt
158 # starts from the same state (runs under autodie)
159 # permissive - the mode of the target while the operation is allowed
160 # restricted - the mode that should forbid it
161 # bits - optional; which mode bits the check after chmod
162 # compares (default: the owner bits)
163 # The ops call the seams by name, so that tests can mock them.
164 Readonly::Hash my %PROBE => (
165 read => {
166 143 ▶ setup => sub { _setup_file($_[0], $PROBE_CONTENT, $MODE_FILE_RW) },
Subroutine __ANON__: called CC=1 SCAR=0.0
167 247 ▶ op => sub { _try_open($_[0]{object}, $OPEN_READ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
168 permissive => $MODE_FILE_RW,
169 restricted => $MODE_NONE,
170 },
171 write => {
172 93 ▶ setup => sub { _setup_file($_[0], $PROBE_CONTENT, $MODE_FILE_RW) },
Subroutine __ANON__: called CC=1 SCAR=0.0
173 150 ▶ op => sub { _try_open($_[0]{object}, $OPEN_APPEND) },
Subroutine __ANON__: called CC=1 SCAR=0.0
174 permissive => $MODE_FILE_RW,
175 restricted => $MODE_FILE_RO,
176 },
177 create => {
178 88 ▶ setup => sub { _setup_subdir($_[0], 0) },
Subroutine __ANON__: called CC=1 SCAR=0.0
179 140 ▶ op => sub { _try_open($_[0]{object}, $OPEN_TRUNCATE) },
Subroutine __ANON__: called CC=1 SCAR=0.0
180 65 ▶ tidy => sub { unlink $_[0]{object} },
Subroutine __ANON__: called CC=1 SCAR=0.0
181 permissive => $MODE_DIR_RWX,
182 restricted => $MODE_DIR_RX,
183 },
184 search => {
185 88 ▶ setup => sub { _setup_subdir($_[0], 1) },
Subroutine __ANON__: called CC=1 SCAR=0.0
186 142 ▶ op => sub { _try_stat($_[0]{object}) },
Subroutine __ANON__: called CC=1 SCAR=0.0
187 permissive => $MODE_DIR_RWX,
188 restricted => $MODE_NONE,
189 },
190 exec => {
191 82 ▶ setup => sub { _setup_file($_[0], $PROBE_SCRIPT, $MODE_FILE_RWX) },
Subroutine __ANON__: called CC=1 SCAR=0.0
192 132 ▶ op => sub { _try_exec($_[0]{object}) },
Subroutine __ANON__: called CC=1 SCAR=0.0
193 permissive => $MODE_FILE_RWX,
194 restricted => $MODE_FILE_RW,
195 },
196 delete => {
197 82 ▶ setup => sub { _setup_subdir($_[0], 1) },
Subroutine __ANON__: called CC=1 SCAR=0.0
198 132 ▶ op => sub { _try_unlink($_[0]{object}) },
Subroutine __ANON__: called CC=1 SCAR=0.0
199 60 ▶ tidy => sub { _make_file($_[0]{object}, q{}); _set_mode($_[0]{object}, $MODE_FILE_RW) },
Subroutine __ANON__: called CC=1 SCAR=0.0
200 permissive => $MODE_DIR_RWX,
201 restricted => $MODE_DIR_RX,
202 },
203 sticky => {
204 31 ▶ precondition => sub { _can_switch_uid() },
Subroutine __ANON__: called CC=1 SCAR=0.0
205 8 ▶ setup => sub { _setup_sticky($_[0]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
206 12 ▶ op => sub { _try_unlink($_[0]{object}, $_[0]{as}) },
Subroutine __ANON__: called CC=1 SCAR=0.0
207 7 ▶ tidy => sub { _make_file($_[0]{object}, q{}); _give_away($_[0]{object}, $STICKY_OWNER_UID) },
Subroutine __ANON__: called CC=1 SCAR=0.0
208 17 permissive => $MODE_DIR_ALL,
209 restricted => $MODE_DIR_STICKY,
210 bits => $MODE_BITS,
211 },
212 );
213  
214 # The kinds, in the order they are listed in messages and reports.
215 17 Readonly::Array my @KINDS => qw(read write create search exec delete sticky);
216  
217 # The kinds acl_denies() and with_revoked() accept. with_revoked() leaves
218 # out sticky: setting the sticky bit does not take the owner's access away.
219 17 Readonly::Array my @ACL_KINDS => qw(read write exec);
220 17 Readonly::Array my @GUARD_KINDS => qw(read write create search exec delete);
221  
222 # The kinds whose restricted mode applies to a file; the others apply to a
223 # directory.
224 17 Readonly::Hash my %FILE_KIND => map { $_ => 1 } qw(read write exec);
225  
226 # How answers are shared between directories (set_cache_scope).
227 17 Readonly::Array my @CACHE_SCOPES => qw(directory device);
228 17 Readonly::Scalar my $DEFAULT_SCOPE => 'directory';
229  
230 # Input schemas (Params::Validate::Strict), as documented in the POD.
231 # 'position' gives the order of positional arguments.
232 17 Readonly::Hash my %INPUT_SCHEMA => (
233 dir => {
234 dir => { type => 'string', optional => 1, min => 1, position => 0 },
235 },
236 kind_dir => {
237 kind => { type => 'string', memberof => [ @KINDS ], position => 0 },
238 dir => { type => 'string', optional => 1, min => 1, position => 1 },
239 },
240 kind_count_dir => {
241 kind => { type => 'string', memberof => [ @KINDS ], position => 0 },
242 count => { type => 'integer', min => 1, position => 1 },
243 dir => { type => 'string', optional => 1, min => 1, position => 2 },
244 },
245 acl => {
246 kind => { type => 'string', memberof => [ @ACL_KINDS ], position => 0 },
247 path => { type => 'string', min => 1, position => 1 },
248 },
249 guard => {
250 kind => { type => 'string', memberof => [ @GUARD_KINDS ], position => 0 },
251 path => { type => 'string', min => 1, position => 1 },
252 code => { type => 'coderef', position => 2 },
253 },
254 scope => {
255 scope => { type => 'string', memberof => [ @CACHE_SCOPES ], position => 0 },
256 },
257 );
258  
259 # Output schemas (Return::Set).
260 17 Readonly::Hash my %OUTPUT_SCHEMA => (
261 answer => { type => 'boolean' },
262 reason => { type => 'string', optional => 1 },
263 report => { type => 'string', min => 1 },
264 void => { type => 'void' },
265 );
266  
267 # Every user-facing text, as sprintf formats. set_messages() overrides
268 # them by key; see MESSAGES in the POD.
269 17 Readonly::Hash my %MESSAGES => (
270 error_unknown_kind => q{Unknown access kind '%s'; expected one of: %s},
271 error_not_a_directory => q{'%s' is not a directory},
272 error_not_a_file => q{'%s' is a directory; %s access is revoked on a file},
273 error_no_such_path => q{'%s' does not exist},
274 error_unknown_message => q{Unknown message key '%s'},
275 error_too_many_arguments => q{Too many arguments: expected at most %d, got %d},
276 error_chmod_failed => q{Could not chmod '%s' to %04o: %s},
277 error_restore_failed => q{Could not restore mode %04o on '%s': %s},
278 reason_not_enforced => q{chmod cannot revoke %s access in '%s' (running as root, or the filesystem ignores permissions)},
279 reason_chmod_ignored => q{chmod did not set mode %04o in '%s' (got %04o)},
280 reason_baseline_failed => q{%s access fails in '%s' even when it is allowed: %s},
281 reason_other_error => q{%s access in '%s' failed for a reason other than permissions: %s},
282 reason_setup_failed => q{Could not set up the %s probe in '%s': %s},
283 reason_cleanup_failed => q{%s; also could not clean up '%s': %s},
284 reason_probe_succeeded => q{chmod revoked %s access in '%s'},
285 reason_needs_root => q{The %s probe in '%s' must act as two users, which needs root (not Windows)},
286 report_header => q{Test::Permissions %s in '%s' (effective uid %s):},
287 report_yes => q{ %s: yes},
288 report_no => q{ %s: no - %s},
289 );
290  
291 # -----------------------------------------------------------------------
292 # Package state
293 # -----------------------------------------------------------------------
294  
295 # Answers already found:
296 # "kind\0euid\0egids\0scope key" => [ answer, reason ].
297 17 my %cache;
298  
299 # How answers are shared between directories: 'directory' or 'device'.
300 17 my $cache_scope = $DEFAULT_SCOPE;
301  
302 # Message texts set by set_messages(), by key.
303 17 my %message_override;
304  
305 =head1 SYNOPSIS
306  
307 use Test::Most;
308 use File::Temp qw(tempdir);
309 use Test::Permissions qw(:revoke :guard :report);
310  
311 my $dir = tempdir(CLEANUP => 1); # where the fixtures live
312 diag(permissions_report($dir)); # once, for CPAN Testers reports
313  
314 SKIP: {
315 skip why_not('read', $dir), 1 unless can_revoke_read($dir);
316  
317 with_revoked(read => "$dir/fixture", sub {
318 ok(!open(my $fh, '<', "$dir/fixture"), 'unreadable file is refused');
319 }); # the mode is restored, even if the block dies
320 }
321  
322 SKIP: {
323 skip_unless_can_revoke('search', 1, $dir);
324 ...
325 }
326  
327 done_testing();
328  
329 =head1 DESCRIPTION
330  
331 Test suites often need to know whether C<chmod> really takes access away,
332 so they can skip tests that rely on an unreadable file or an unsearchable
333 directory. The usual guess, C<skip ... if $E<gt> == 0>, is wrong on:
334  
335 =over 4
336  
337 =item * Windows, where C<chmod> only sets the read-only attribute;
338  
339 =item * C<fakeroot>, and containers where a non-root user holds
340 C<CAP_DAC_OVERRIDE>;
341  
342 =item * filesystems that ignore mode bits (FAT, some SMB/NFS/FUSE mounts,
343 Cygwin C<noacl> mounts);
344  
345 =item * root in a user namespace, where root may I<not> be able to bypass
346 modes;
347  
348 =item * root on an NFS export with C<root_squash>, where root is treated
349 as "nobody".
350  
351 =back
352  
353 Test::Permissions does not guess. It tries the operation on a scratch
354 file in the directory you care about, and reports what actually happened.
355 Results are cached per process.
356  
357 Seven kinds of access can be probed:
358  
359 Kind Question Restricted mode
360 read can a file be made unreadable? file 0
361 write can a file be made unwritable? file 0400
362 create can a directory be made to refuse new files? directory 0500
363 search can a directory be made unsearchable (stat of a directory 0
364 file inside it fails)?
365 exec can a script be made unrunnable? file 0600
366 delete can a directory be made to keep its files? directory 0500
367 sticky does the sticky bit stop one user deleting directory 01777
368 another user's file?
369  
370 What to expect (your tests must not rely on these; that is the point):
371  
372 Environment read write create search exec delete sticky
373 Linux/BSD/macOS, normal user 1 1 1 1 1 1 0 (a)
374 Unix root, or CAP_DAC_OVERRIDE 0 0 0 0 1(b) 0 1
375 fakeroot 0 0 0 0 1(b) 0 0
376 Windows (NTFS) 0 1 0 (c) 0 0 0 (c) 0
377 FAT or a mount that ignores modes 0 0 0 0 0 0 0
378 a noexec mount . . . . 0 . .
379  
380 (a) the sticky probe must act as two users, so it needs root
381 (b) even root cannot run a file that has no execute bit at all
382 (c) Windows ignores the read-only attribute on directories
383  
384 =head2 Which directory to probe
385  
386 The answer depends on the filesystem, so pass the directory your fixtures
387 live in (usually your own C<tempdir>). If you pass nothing, the probe
388 runs in C<< File::Spec->tmpdir >>, which may be on a different filesystem
389 from your fixtures (a C<tmpfs>, for example) and give a different answer.
390  
391 =head2 How a probe works
392  
393 Each probe creates a fresh directory C<P> inside the target directory and
394 then:
395  
396 =over 4
397  
398 =item 1. B<Setup>: creates the scratch objects with explicit modes, so the
399 answer does not depend on your C<umask>.
400  
401 =item 2. B<Baseline>: does the operation while it is allowed. If that
402 fails, the filesystem cannot tell us anything, and the answer is 0.
403  
404 =item 3. B<Restrict>: C<chmod>s to the restricted mode and checks, with
405 C<stat>, that the owner's permission bits (for C<sticky>: all the mode
406 bits) really changed. If not (this is what happens on Windows), the
407 answer is 0.
408  
409 =item 4. B<Attempt>: does the operation again. It must fail with
410 C<EACCES> or C<EPERM> for the answer to be 1.
411  
412 =item 5. B<Restore and clean up>: always, even if an earlier step failed.
413 Nothing is left in the target directory.
414  
415 =back
416  
417 A probe never dies and never warns: anything that goes wrong becomes an
418 answer of 0, and L</why_not(kind, dir)> tells you why. Only mistakes in
419 the call itself (an unknown kind, a directory that does not exist) croak.
420  
421 =head2 Paths with non-ASCII characters
422  
423 Directory and file names are used exactly as perl's own file functions
424 use them: as byte strings. On Unix, pass the same (usually UTF-8
425 encoded) bytes you would pass to C<open>. On Windows, perl's file
426 functions use the ANSI code page, so a name with characters outside it
427 cannot be found, and the call croaks with C<error_not_a_directory> or
428 C<error_no_such_path>. Names in messages are shown as they are, except
429 that control and bidirectional-override characters are escaped.
430  
431 =head2 Taint mode
432  
433 The functions work under C<perl -T>. The directory you pass is checked
434 with C<-d>, and its canonical path is then untainted, because the probe
435 only creates its own scratch directory inside it. C<with_revoked>
436 likewise untaints the path you give it, because changing its mode is what
437 you asked for. The C<exec> probe runs its script with C<PATH>, C<IFS>,
438 C<CDPATH>, C<ENV> and C<BASH_ENV> removed from the environment.
439  
440 =head1 SUBROUTINES/METHODS
441  
442 Nothing is exported by default. Import what you need by name, or use a
443 tag:
444  
445 :revoke can_revoke_* , can_revoke, why_not, skip_unless_can_revoke
446 :acl acl_denies
447 :guard with_revoked
448 :report permissions_report
449 :all all of these, plus clear_cache, set_cache_scope, set_messages
450  
451 Every function that takes C<dir> accepts it in any of these forms:
452  
453 f() # dir is File::Spec->tmpdir
454 f($dir)
455 f(dir => $dir)
456 f({ dir => $dir })
457  
458 An object that stringifies (such as a L<Path::Tiny> object) is accepted
459 wherever a directory or path name is.
460  
461 =head2 can_revoke_read(dir)
462  
463 =head3 PURPOSE
464  
465 Find out whether a file with mode 0 refuses C<< open '<' >>: that is,
466 whether C<chmod> can make a file unreadable in C<dir>. The same as
467 C<can_revoke('read', $dir)>.
468  
469 =head3 ARGUMENTS
470  
471 =over 4
472  
473 =item * C<dir> - optional. The directory to probe in. It must exist
474 and be a directory. Default: C<< File::Spec->tmpdir >>.
475  
476 =back
477  
478 =head3 RETURNS
479  
480 1 if C<chmod> can take that access away in C<dir>, otherwise 0. Never
481 undef.
482  
483 =head3 SIDE EFFECTS
484  
485 =over 4
486  
487 =item * The first call for a kind and directory creates and removes a
488 probe directory inside C<dir>. Later calls use the cache and do not touch
489 the filesystem.
490  
491 =item * Never dies or warns because of what it finds; see
492 L</FAILURE POLICY>.
493  
494 =item * Does not change the caller's C<$@>, C<$!> or C<umask>.
495  
496 =back
497  
498 =head3 USAGE EXAMPLE
499  
500 SKIP: {
501 skip 'chmod cannot make a file unreadable here', 1
502 unless Test::Permissions::can_revoke_read($dir);
503 ...
504 }
505  
506 =head3 API SPECIFICATION
507  
508 =head4 Input
509  
510 {
511 dir => {
512 type => 'string',
513 optional => 1,
514 min => 1,
515 position => 0,
516 },
517 }
518  
519 =head4 Output
520  
521 { type => 'boolean' }
522  
523 =head3 MESSAGES
524  
525 Errors (the call dies):
526  
527 '$dir' is not a directory (error_not_a_directory)
528 dir does not exist, or is not a directory.
529 What to do: pass the directory your fixtures live in.
530  
531 Too many arguments: expected at most 1, got N (error_too_many_arguments)
532 More than one positional argument was given.
533 What to do: pass only the directory.
534  
535 (an error from Params::Validate::Strict or Params::Get)
536 dir is not a string (for example an array reference), is empty,
537 or the named form has an unknown key.
538  
539 The reason for a 0 answer is available from L</why_not(kind, dir)>, which
540 lists every C<reason_*> message.
541  
542 =cut
543  
544 1071 ▶sub can_revoke_read { return _revoke_wrapper('read', \@_) }
Subroutine can_revoke_read: called CC=1 SCAR=0.0
Pod documented
545  
546 =head2 can_revoke_write(dir)
547  
548 =head3 PURPOSE
549  
550 Find out whether a file with mode 0400 refuses C<<< open '>>' >>>: that
551 is, whether C<chmod> can make a file unwritable in C<dir>. The same as
552 C<can_revoke('write', $dir)>.
553  
554 =head3 ARGUMENTS
555  
556 =over 4
557  
558 =item * C<dir> - optional. As for L</can_revoke_read(dir)>.
559  
560 =back
561  
562 =head3 RETURNS
563  
564 1 or 0, never undef.
565  
566 =head3 SIDE EFFECTS
567  
568 As for L</can_revoke_read(dir)>.
569  
570 =head3 USAGE EXAMPLE
571  
572 SKIP: {
573 skip 'chmod cannot make a file read-only here', 1
574 unless Test::Permissions::can_revoke_write($dir);
575 chmod 0400, $file;
576 ok(!open(my $fh, '>>', $file), 'read-only file is refused');
577 chmod 0600, $file;
578 }
579  
580 =head3 API SPECIFICATION
581  
582 =head4 Input
583  
584 {
585 dir => {
586 type => 'string',
587 optional => 1,
588 min => 1,
589 position => 0,
590 },
591 }
592  
593 =head4 Output
594  
595 { type => 'boolean' }
596  
597 =head3 MESSAGES
598  
599 The same as L</can_revoke_read(dir)>.
600  
601 =cut
602  
603 2 ▶sub can_revoke_write { return _revoke_wrapper('write', \@_) }
Subroutine can_revoke_write: called CC=1 SCAR=0.0
Pod documented
604  
605 =head2 can_revoke_create(dir)
606  
607 =head3 PURPOSE
608  
609 Find out whether a directory with mode 0500 refuses C<< open '>' >> of a
610 new file in it: that is, whether C<chmod> can stop files being created
611 in a directory in C<dir>. The same as C<can_revoke('create', $dir)>.
612  
613 Note: in App-makefilepl2cpanfile's private copy of this module, this
614 question was called C<can_revoke_write>. L</can_revoke_write(dir)> now
615 asks about a file's own write bit.
616  
617 On Windows the answer is 0 with C<reason_not_enforced>: Windows ignores
618 the read-only attribute on directories.
619  
620 =head3 ARGUMENTS
621  
622 =over 4
623  
624 =item * C<dir> - optional. As for L</can_revoke_read(dir)>.
625  
626 =back
627  
628 =head3 RETURNS
629  
630 1 or 0, never undef.
631  
632 =head3 SIDE EFFECTS
633  
634 As for L</can_revoke_read(dir)>.
635  
636 =head3 USAGE EXAMPLE
637  
638 SKIP: {
639 skip Test::Permissions::why_not('create', $dir), 1
640 unless Test::Permissions::can_revoke_create($dir);
641 chmod 0500, $outdir;
642 ok(!eval { write_report($outdir) }, 'cannot write the report');
643 chmod 0700, $outdir;
644 }
645  
646 =head3 API SPECIFICATION
647  
648 =head4 Input
649  
650 {
651 dir => {
652 type => 'string',
653 optional => 1,
654 min => 1,
655 position => 0,
656 },
657 }
658  
659 =head4 Output
660  
661 { type => 'boolean' }
662  
663 =head3 MESSAGES
664  
665 The same as L</can_revoke_read(dir)>.
666  
667 =cut
668  
669 2 ▶sub can_revoke_create { return _revoke_wrapper('create', \@_) }
Subroutine can_revoke_create: called CC=1 SCAR=0.0
Pod documented
670  
671 =head2 can_revoke_search(dir)
672  
673 =head3 PURPOSE
674  
675 Find out whether a directory with mode 0 makes C<stat> of a file inside
676 it fail: that is, whether C<chmod> can make a directory in C<dir>
677 unsearchable. The same as C<can_revoke('search', $dir)>.
678  
679 =head3 ARGUMENTS
680  
681 =over 4
682  
683 =item * C<dir> - optional. As for L</can_revoke_read(dir)>.
684  
685 =back
686  
687 =head3 RETURNS
688  
689 1 or 0, never undef.
690  
691 =head3 SIDE EFFECTS
692  
693 As for L</can_revoke_read(dir)>.
694  
695 =head3 USAGE EXAMPLE
696  
697 SKIP: {
698 skip 'chmod cannot hide a directory here', 1
699 unless Test::Permissions::can_revoke_search($dir);
700 chmod 0, $subdir;
701 ok(!-e "$subdir/file", 'file inside is hidden');
702 chmod 0700, $subdir;
703 }
704  
705 =head3 API SPECIFICATION
706  
707 =head4 Input
708  
709 {
710 dir => {
711 type => 'string',
712 optional => 1,
713 min => 1,
714 position => 0,
715 },
716 }
717  
718 =head4 Output
719  
720 { type => 'boolean' }
721  
722 =head3 MESSAGES
723  
724 The same as L</can_revoke_read(dir)>.
725  
726 =cut
727  
728 3 ▶sub can_revoke_search { return _revoke_wrapper('search', \@_) }
Subroutine can_revoke_search: called CC=1 SCAR=0.0
Pod documented
729  
730 =head2 can_revoke_exec(dir)
731  
732 =head3 PURPOSE
733  
734 Find out whether a script with mode 0600 refuses to run: that is, whether
735 C<chmod> can take away the execute bit in C<dir>. The probe runs a
736 two-line C</bin/sh> script with C<system>, so it needs C</bin/sh>, and a
737 filesystem not mounted C<noexec>. The same as C<can_revoke('exec', $dir)>.
738  
739 Unlike the other kinds, the answer is usually 1 even for root: root can
740 run a file only if at least one of its execute bits is set.
741  
742 =head3 ARGUMENTS
743  
744 =over 4
745  
746 =item * C<dir> - optional. As for L</can_revoke_read(dir)>.
747  
748 =back
749  
750 =head3 RETURNS
751  
752 1 or 0, never undef.
753  
754 =head3 SIDE EFFECTS
755  
756 As for L</can_revoke_read(dir)>; also starts two short-lived processes.
757  
758 =head3 USAGE EXAMPLE
759  
760 SKIP: {
761 skip Test::Permissions::why_not('exec', $dir), 1
762 unless Test::Permissions::can_revoke_exec($dir);
763 chmod 0600, $hook;
764 ok(!run_hook($hook), 'a hook without the execute bit is not run');
765 }
766  
767 =head3 API SPECIFICATION
768  
769 =head4 Input
770  
771 {
772 dir => {
773 type => 'string',
774 optional => 1,
775 min => 1,
776 position => 0,
777 },
778 }
779  
780 =head4 Output
781  
782 { type => 'boolean' }
783  
784 =head3 MESSAGES
785  
786 The same as L</can_revoke_read(dir)>. On a C<noexec> mount, or without
787 C</bin/sh>, the reason is C<reason_baseline_failed>.
788  
789 =cut
790  
791 1 ▶sub can_revoke_exec { return _revoke_wrapper('exec', \@_) }
Subroutine can_revoke_exec: called CC=1 SCAR=0.0
Pod documented
792  
793 =head2 can_revoke_delete(dir)
794  
795 =head3 PURPOSE
796  
797 Find out whether a directory with mode 0500 refuses C<unlink> of a file
798 in it: that is, whether C<chmod> can stop files being deleted from a
799 directory in C<dir>. The same as C<can_revoke('delete', $dir)>.
800  
801 =head3 ARGUMENTS
802  
803 =over 4
804  
805 =item * C<dir> - optional. As for L</can_revoke_read(dir)>.
806  
807 =back
808  
809 =head3 RETURNS
810  
811 1 or 0, never undef.
812  
813 =head3 SIDE EFFECTS
814  
815 As for L</can_revoke_read(dir)>.
816  
817 =head3 USAGE EXAMPLE
818  
819 SKIP: {
820 skip Test::Permissions::why_not('delete', $dir), 1
821 unless Test::Permissions::can_revoke_delete($dir);
822 chmod 0500, $spool;
823 ok(!eval { purge($spool) }, 'purge reports the failure');
824 chmod 0700, $spool;
825 }
826  
827 =head3 API SPECIFICATION
828  
829 =head4 Input
830  
831 {
832 dir => {
833 type => 'string',
834 optional => 1,
835 min => 1,
836 position => 0,
837 },
838 }
839  
840 =head4 Output
841  
842 { type => 'boolean' }
843  
844 =head3 MESSAGES
845  
846 The same as L</can_revoke_read(dir)>.
847  
848 =cut
849  
850 1 ▶sub can_revoke_delete { return _revoke_wrapper('delete', \@_) }
Subroutine can_revoke_delete: called CC=1 SCAR=0.0
Pod documented
851  
852 =head2 can_revoke_sticky(dir)
853  
854 =head3 PURPOSE
855  
856 Find out whether the sticky bit works in C<dir>: in a directory with mode
857 01777, can one user be stopped from deleting another user's file? The
858 same as C<can_revoke('sticky', $dir)>.
859  
860 This needs two users, so the probe only runs as root (real and effective
861 uid 0), and not on Windows. It gives its file to uid 65534 and tries to
862 delete it as uid 65533, by setting C<< $> >> for the moment of the
863 C<unlink>. Anywhere else the answer is 0 with C<reason_needs_root>.
864  
865 =head3 ARGUMENTS
866  
867 =over 4
868  
869 =item * C<dir> - optional. As for L</can_revoke_read(dir)>.
870  
871 =back
872  
873 =head3 RETURNS
874  
875 1 or 0, never undef.
876  
877 =head3 SIDE EFFECTS
878  
879 As for L</can_revoke_read(dir)>. While it runs, the process briefly
880 changes its effective uid and its working directory; both are restored
881 before it returns.
882  
883 =head3 USAGE EXAMPLE
884  
885 SKIP: {
886 skip Test::Permissions::why_not('sticky', $dir), 1
887 unless Test::Permissions::can_revoke_sticky($dir);
888 ...
889 }
890  
891 =head3 API SPECIFICATION
892  
893 =head4 Input
894  
895 {
896 dir => {
897 type => 'string',
898 optional => 1,
899 min => 1,
900 position => 0,
901 },
902 }
903  
904 =head4 Output
905  
906 { type => 'boolean' }
907  
908 =head3 MESSAGES
909  
910 The same as L</can_revoke_read(dir)>. When not running as root, the
911 reason is C<reason_needs_root>.
912  
913 =cut
914  
915 4 ▶sub can_revoke_sticky { return _revoke_wrapper('sticky', \@_) }
Subroutine can_revoke_sticky: called CC=1 SCAR=0.0
Pod documented
916  
917 # _revoke_wrapper
918 #
919 # Purpose: The shared body of the can_revoke_<kind> functions.
920 # Entry: $kind - a kind from @KINDS; $args - arrayref of the caller's @_.
921 # Exit: 1 or 0. Croaks (from the caller's line) on bad arguments.
922 1084 ▶sub _revoke_wrapper {
Subroutine _revoke_wrapper: called CC=2 SCAR=6.9
923 1084 my ($kind, $args) = @_;
924  
925 1084 my ($params, $error) = _check_args('dir', $args);
926 1084 ▶ Carp::croak($error) if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 25 1059 1084
927  
928 1059 return _set_return(_answer($kind, $params->{dir})->[0], 'answer');
929 }
930  
931 =head2 can_revoke(kind, dir)
932  
933 =head3 PURPOSE
934  
935 The general form of the C<can_revoke_*> functions: answer the question
936 for the kind of access named by C<kind>.
937  
938 =head3 ARGUMENTS
939  
940 =over 4
941  
942 =item * C<kind> - required. One of C<read>, C<write>, C<create>,
943 C<search>, C<exec>, C<delete> or C<sticky>.
944  
945 =item * C<dir> - optional. As for L</can_revoke_read(dir)>.
946  
947 =back
948  
949 Positional (C<can_revoke('read', $dir)>), named
950 (C<< can_revoke(kind => 'read', dir => $dir) >>) and hash reference
951 (C<< can_revoke({ kind => 'read' }) >>) forms are all accepted.
952  
953 =head3 RETURNS
954  
955 1 or 0, never undef.
956  
957 =head3 SIDE EFFECTS
958  
959 As for L</can_revoke_read(dir)>.
960  
961 =head3 USAGE EXAMPLE
962  
963 for my $kind (qw(read search)) {
964 SKIP: {
965 skip "cannot revoke $kind access", 1
966 unless Test::Permissions::can_revoke($kind, $dir);
967 ...
968 }
969 }
970  
971 =head3 API SPECIFICATION
972  
973 =head4 Input
974  
975 {
976 kind => {
977 type => 'string',
978 memberof => [ 'read', 'write', 'create', 'search', 'exec', 'delete', 'sticky' ],
979 position => 0,
980 },
981 dir => {
982 type => 'string',
983 optional => 1,
984 min => 1,
985 position => 1,
986 },
987 }
988  
989 =head4 Output
990  
991 { type => 'boolean' }
992  
993 =head3 MESSAGES
994  
995 Errors (the call dies):
996  
997 Unknown access kind '$kind'; expected one of: read, write, create,
998 search, exec, delete, sticky (error_unknown_kind)
999 What to do: use one of the listed kinds.
1000  
1001 '$dir' is not a directory (error_not_a_directory)
1002 What to do: pass an existing directory.
1003  
1004 Too many arguments: expected at most 2, got N (error_too_many_arguments)
1005  
1006 (an error from Params::Validate::Strict or Params::Get)
1007 kind is missing or not a string, dir is not a string or is empty,
1008 or the named form has an unknown key.
1009  
1010 =cut
1011  
1012 823 ▶sub can_revoke {
Subroutine can_revoke: called CC=2 SCAR=6.9
Pod documented
1013 823 my ($params, $error) = _check_args('kind_dir', \@_);
1014 823 ▶ Carp::croak($error) if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 38 785 823
1015  
1016 785 return _set_return(_answer($params->{kind}, $params->{dir})->[0], 'answer');
1017 }
1018  
1019 =head2 why_not(kind, dir)
1020  
1021 =head3 PURPOSE
1022  
1023 Say why the answer for C<kind> in C<dir> is 0, in words suitable for a
1024 skip message.
1025  
1026 =head3 ARGUMENTS
1027  
1028 The same as L</can_revoke(kind, dir)>.
1029  
1030 =head3 RETURNS
1031  
1032 undef when the answer is 1. Otherwise a non-empty string: one of the
1033 C<reason_*> messages below.
1034  
1035 =head3 SIDE EFFECTS
1036  
1037 Runs the probe if it has not run yet for this kind and directory, exactly
1038 as L</can_revoke(kind, dir)> would, and caches the result.
1039  
1040 =head3 USAGE EXAMPLE
1041  
1042 SKIP: {
1043 my $why = Test::Permissions::why_not('search', $dir);
1044 skip $why, 2 if defined $why;
1045 ...
1046 }
1047  
1048 =head3 API SPECIFICATION
1049  
1050 =head4 Input
1051  
1052 {
1053 kind => {
1054 type => 'string',
1055 memberof => [ 'read', 'write', 'create', 'search', 'exec', 'delete', 'sticky' ],
1056 position => 0,
1057 },
1058 dir => {
1059 type => 'string',
1060 optional => 1,
1061 min => 1,
1062 position => 1,
1063 },
1064 }
1065  
1066 =head4 Output
1067  
1068 { type => 'string', optional => 1 }
1069  
1070 =head3 MESSAGES
1071  
1072 Errors: the same as L</can_revoke(kind, dir)>.
1073  
1074 Reasons (returned, never thrown or warned). C<$dir> is the canonical
1075 path of the directory; C<$error> is the system's error text, in the
1076 current locale (so a reason may mix these English texts, or your own from
1077 L</set_messages(%overrides)>, with another language).
1078  
1079 chmod cannot revoke $kind access in '$dir' (running as root, or the
1080 filesystem ignores permissions) (reason_not_enforced)
1081 The operation still worked after chmod. You are root, hold
1082 CAP_DAC_OVERRIDE, run under fakeroot, or the filesystem ignores
1083 modes. On Windows, create and delete give this reason because
1084 Windows ignores the read-only attribute on directories.
1085 What to do: nothing; skip the test. To run it, run the suite as
1086 an ordinary user on a filesystem that honours modes.
1087  
1088 chmod did not set mode $wanted in '$dir' (got $got)
1089 (reason_chmod_ignored)
1090 chmod "worked" but the permission bits did not change. This is
1091 Windows, or a FAT or noacl mount.
1092 What to do: nothing; skip the test.
1093  
1094 $kind access fails in '$dir' even when it is allowed: $error
1095 (reason_baseline_failed)
1096 The operation failed before any permission was removed, so the
1097 probe learnt nothing. The filesystem may be read-only or broken;
1098 for exec, it may be mounted noexec, or /bin/sh may be missing.
1099 What to do: check the directory and the filesystem.
1100  
1101 $kind access in '$dir' failed for a reason other than permissions: $error
1102 (reason_other_error)
1103 After chmod the operation failed, but not with EACCES or EPERM
1104 (for example ENOSPC).
1105 What to do: check the error; the directory may be full or odd.
1106  
1107 Could not set up the $kind probe in '$dir': $error
1108 (reason_setup_failed)
1109 The probe could not create its scratch files, usually because you
1110 cannot write to dir.
1111 What to do: pass a directory you can write to.
1112  
1113 The sticky probe in '$dir' must act as two users, which needs root
1114 (not Windows) (reason_needs_root)
1115 Only the sticky probe gives this reason.
1116 What to do: nothing; run the suite as root to probe it.
1117  
1118 $reason; also could not clean up '$probe_dir': $error
1119 (reason_cleanup_failed)
1120 Restoring the modes or removing the probe directory failed, so
1121 the answer is 0 whatever the probe found. $reason is one of the
1122 reasons above, or, if the probe itself succeeded, the text of
1123 reason_probe_succeeded:
1124  
1125 chmod revoked $kind access in '$dir' (reason_probe_succeeded)
1126 Only ever seen as the first part of reason_cleanup_failed.
1127 What to do: remove $probe_dir by hand; it is also removed when
1128 the process exits.
1129  
1130 Paths and error texts in reasons have control characters and Unicode
1131 direction-override characters replaced by C<\x{..}> escapes.
1132  
1133 =cut
1134  
1135 630 ▶sub why_not {
Subroutine why_not: called CC=3 SCAR=11.0
Pod documented
1136 630 my ($params, $error) = _check_args('kind_dir', \@_);
1137 630 ▶ Carp::croak($error) if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 1 629 630
1138  
1139 629 my $entry = _answer($params->{kind}, $params->{dir});
1140 629 ▶ return _set_return($entry->[0] ? undef : $entry->[1], 'reason');
Branch: 1 branch
BranchTrueFalseTotal
$entry->[0] ? : 58 571 629
1141 }
1142  
1143 =head2 skip_unless_can_revoke(kind, count, dir)
1144  
1145 =head3 PURPOSE
1146  
1147 Skip the rest of the enclosing C<SKIP:> block, with the reason from
1148 L</why_not(kind, dir)>, when C<chmod> cannot revoke C<kind> access.
1149  
1150 =head3 ARGUMENTS
1151  
1152 =over 4
1153  
1154 =item * C<kind> - required. As for L</can_revoke(kind, dir)>.
1155  
1156 =item * C<count> - required. The number of tests in the block, as for
1157 C<Test::More::skip>. A whole number, 1 or more.
1158  
1159 =item * C<dir> - optional. As for L</can_revoke_read(dir)>.
1160  
1161 =back
1162  
1163 =head3 RETURNS
1164  
1165 Nothing, when the answer is 1. When the answer is 0 it does not return:
1166 it records C<count> skipped tests and leaves the enclosing C<SKIP:> block,
1167 exactly as a direct C<skip> call would.
1168  
1169 =head3 SIDE EFFECTS
1170  
1171 =over 4
1172  
1173 =item * Runs the probe, as L</can_revoke(kind, dir)> does.
1174  
1175 =item * When the answer is 0, records C<count> skipped tests. With
1176 L<Test::More> (or anything else that loads L<Test::Builder>) it calls
1177 C<Test::More::skip>. In a L<Test2::V0> suite, which does not load
1178 Test::Builder, it records the skips through L<Test2::API> instead.
1179  
1180 =item * Must be called inside a C<SKIP:> block, like C<Test::More::skip>.
1181 Outside one, perl dies with C<Label not found for "last SKIP">.
1182  
1183 =back
1184  
1185 =head3 USAGE EXAMPLE
1186  
1187 SKIP: {
1188 Test::Permissions::skip_unless_can_revoke('search', 2, $dir);
1189 chmod 0, $subdir;
1190 ok(!-e "$subdir/file", 'file hidden');
1191 ok(!opendir(my $dh, $subdir), 'directory unreadable');
1192 chmod 0700, $subdir;
1193 }
1194  
1195 =head3 API SPECIFICATION
1196  
1197 =head4 Input
1198  
1199 {
1200 kind => {
1201 type => 'string',
1202 memberof => [ 'read', 'write', 'create', 'search', 'exec', 'delete', 'sticky' ],
1203 position => 0,
1204 },
1205 count => {
1206 type => 'integer',
1207 min => 1,
1208 position => 1,
1209 },
1210 dir => {
1211 type => 'string',
1212 optional => 1,
1213 min => 1,
1214 position => 2,
1215 },
1216 }
1217  
1218 =head4 Output
1219  
1220 { type => 'void' }
1221  
1222 Returns nothing (an empty list) when the answer is 1.
1223  
1224 =head3 MESSAGES
1225  
1226 Errors: the same as L</can_revoke(kind, dir)>, plus an error from
1227 Params::Validate::Strict when C<count> is missing, not a whole number, or
1228 less than 1.
1229  
1230 The skip message is one of the reasons listed under
1231 L</why_not(kind, dir)>.
1232  
1233 =cut
1234  
1235 44 ▶sub skip_unless_can_revoke {
Subroutine skip_unless_can_revoke: called CC=6 SCAR=17.9
Pod documented
1236 44 my ($params, $error) = _check_args('kind_count_dir', \@_);
1237 44 ▶ Carp::croak($error) if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 14 30 44
1238  
1239 30 my $entry = _answer($params->{kind}, $params->{dir});
1240 30 ▶ if($entry->[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($entry->[0]) 21 9 30
1241 21 _set_return(undef, 'void');
1242 21 return;
1243 }
1244  
1245 # A Test2::V0 suite has Test2::API but not Test::Builder; loading
1246 # Test::More there would work, but is not what the suite asked for.
1247 9 ▶ if($INC{'Test2/API.pm'} && !$INC{'Test/Builder.pm'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($INC{"Test2/API.pm"} and not $INC{"Test/Builder.pm"}) 2 7 9
Condition66%2/3
$INC{"Test2/API.pm"} and not $INC{"Test/Builder.pm"}
!ll&&!rl&&r
072
MC/DC50%1/2
$INC{"Test2/API.pm"} and not $INC{"Test/Builder.pm"}
$INC{"Test2/API.pm"} not $INC{"Test/Builder.pm"}
Truth table66%2/3
A and not(B)
A= $INC{"Test2/API.pm"}B= not $INC{"Test/Builder.pm"}
ABresult
0X0
100
111
1248 2 my $context = Test2::API::context();
1249 2 $context->skip(q{}, $entry->[1]) for 1 .. $params->{count};
1250 2 $context->release();
1251 17 ▶ no warnings 'exiting'; ## no critic (TestingAndDebugging::ProhibitNoWarnings)
Subroutine BEGIN: called CC=1 SCAR=0.0
1252 2 last SKIP; ## no critic (ControlStructures::ProhibitLastInSubroutine)
1253 }
1254  
1255 # Loaded here, not at compile time, so that code which never skips does
1256 # not load Test::Builder. skip() leaves the SKIP block with 'last SKIP',
1257 # which unwinds through this sub.
1258 7 require Test::More;
1259 7 Test::More::skip($entry->[1], $params->{count});
1260 0 return; # not reached inside a SKIP block
1261 }
1262  
1263 =head2 acl_denies(kind, path)
1264  
1265 =head3 PURPOSE
1266  
1267 Find out whether something other than the mode bits - usually an access
1268 control list - denies you C<kind> access to an existing C<path>, even
1269 though its mode bits allow it. Use it to skip or explain a test that
1270 fails because of a fixture's ACL, not its mode.
1271  
1272 It compares what the mode bits say (for your effective uid and groups)
1273 with what the system says, using C<access(2)> (perl's C<-r>, C<-w> and
1274 C<-x> under C<use filetest 'access'>), which takes ACLs into account. It
1275 does not open, change or run C<path>.
1276  
1277 =head3 ARGUMENTS
1278  
1279 =over 4
1280  
1281 =item * C<kind> - required. C<read>, C<write> or C<exec> (for a
1282 directory, C<exec> means search).
1283  
1284 =item * C<path> - required. An existing file or directory.
1285  
1286 =back
1287  
1288 =head3 RETURNS
1289  
1290 1 if the mode bits allow the access but the system denies it, otherwise 0
1291 (including when the mode bits themselves deny it).
1292  
1293 =head3 SIDE EFFECTS
1294  
1295 None. It is not cached: each call looks at C<path> again.
1296  
1297 Besides ACLs, a read-only mount, an immutable flag or a mandatory access
1298 control policy (SELinux, AppArmor) can also make it return 1. On Windows,
1299 perl's file tests do not consult ACLs, so it returns 0.
1300  
1301 =head3 USAGE EXAMPLE
1302  
1303 SKIP: {
1304 skip "an ACL denies reading $fixture", 1
1305 if Test::Permissions::acl_denies(read => $fixture);
1306 ok(load($fixture), 'fixture loads');
1307 }
1308  
1309 =head3 API SPECIFICATION
1310  
1311 =head4 Input
1312  
1313 {
1314 kind => {
1315 type => 'string',
1316 memberof => [ 'read', 'write', 'exec' ],
1317 position => 0,
1318 },
1319 path => {
1320 type => 'string',
1321 min => 1,
1322 position => 1,
1323 },
1324 }
1325  
1326 =head4 Output
1327  
1328 { type => 'boolean' }
1329  
1330 =head3 MESSAGES
1331  
1332 Errors (the call dies):
1333  
1334 Unknown access kind '$kind'; expected one of: read, write, exec
1335 (error_unknown_kind)
1336  
1337 '$path' does not exist (error_no_such_path)
1338 What to do: pass an existing file or directory.
1339  
1340 Too many arguments: expected at most 2, got N (error_too_many_arguments)
1341  
1342 (an error from Params::Validate::Strict or Params::Get)
1343  
1344 =cut
1345  
1346 31 ▶sub acl_denies {
Subroutine acl_denies: called CC=4 SCAR=13.9
Pod documented
1347 31 my ($params, $error) = _check_args('acl', \@_);
1348 31 ▶ Carp::croak($error) if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 12 19 31
1349  
1350 19 local $!;
1351 19 my @stat = stat $params->{path};
1352 19 my $allowed = _mode_allows($params->{kind}, \@stat, -d _);
1353 19 ▶ my $denied = $allowed && !_access($params->{kind}, $params->{path}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$allowed && !_access($params->{'kind'}, $params->{'path'}) ? : 3 16 19
Condition100%3/3
$allowed and not _access($params->{"kind"}, $params->{"path"})
!ll&&!rl&&r
6103
MC/DC100%2/2
$allowed and not _access($params->{"kind"}, $params->{"path"})
$allowed not _access($params->{"kind"}, $params->{"path"})
Truth table100%3/3
A and not(B)
A= $allowedB= not _access($params->{"kind"}, $params->{"path"})
ABresult
0X0
100
111
1354 19 return _set_return($denied, 'answer');
1355 }
1356  
1357 =head2 with_revoked(kind, path, code)
1358  
1359 =head3 PURPOSE
1360  
1361 Take C<kind> access away from C<path>, run C<code>, and put the mode back
1362 - always, even if C<code> dies. It uses the same restricted modes as the
1363 probes, so a test written as
1364  
1365 SKIP: {
1366 skip_unless_can_revoke('read', 1, $dir);
1367 with_revoked(read => $file, sub { ok(!load($file), 'refused') });
1368 }
1369  
1370 cannot leave an unreadable file behind for the next test, or for
1371 C<File::Temp>'s cleanup.
1372  
1373 =head3 ARGUMENTS
1374  
1375 =over 4
1376  
1377 =item * C<kind> - required. C<read> (mode 0), C<write> (0400) or
1378 C<exec> (0600), which apply to a file; or C<create> (0500), C<search>
1379 (0) or C<delete> (0500), which apply to a directory.
1380  
1381 =item * C<path> - required. An existing file (for read, write, exec) or
1382 directory (for create, search, delete).
1383  
1384 =item * C<code> - required. A code reference, called with no arguments.
1385  
1386 =back
1387  
1388 =head3 RETURNS
1389  
1390 Whatever C<code> returns, in the same (list, scalar or void) context. If
1391 C<code> dies, the mode is restored and the exception is passed on
1392 unchanged.
1393  
1394 =head3 SIDE EFFECTS
1395  
1396 =over 4
1397  
1398 =item * Changes the mode of C<path> while C<code> runs, then restores the
1399 mode it had before.
1400  
1401 =item * Does not check that C<chmod> really takes the access away: use
1402 L</can_revoke(kind, dir)> (or C<skip_unless_can_revoke>) first.
1403  
1404 =item * Under taint mode, C<path> is untainted; see L</Taint mode>.
1405  
1406 =back
1407  
1408 =head3 USAGE EXAMPLE
1409  
1410 my $content = Test::Permissions::with_revoked(search => $dir, sub {
1411 return eval { read_config("$dir/app.conf") };
1412 });
1413 ok(!defined $content, 'config in an unsearchable directory is not read');
1414  
1415 =head3 API SPECIFICATION
1416  
1417 =head4 Input
1418  
1419 {
1420 kind => {
1421 type => 'string',
1422 memberof => [ 'read', 'write', 'create', 'search', 'exec', 'delete' ],
1423 position => 0,
1424 },
1425 path => {
1426 type => 'string',
1427 min => 1,
1428 position => 1,
1429 },
1430 code => {
1431 type => 'coderef',
1432 position => 2,
1433 },
1434 }
1435  
1436 =head4 Output
1437  
1438 Whatever C<code> returns; it is not checked.
1439  
1440 =head3 MESSAGES
1441  
1442 Errors (the call dies):
1443  
1444 Unknown access kind '$kind'; expected one of: read, write, create,
1445 search, exec, delete (error_unknown_kind)
1446 sticky is not accepted: it does not take the owner's access away.
1447  
1448 '$path' does not exist (error_no_such_path)
1449  
1450 '$path' is not a directory (error_not_a_directory)
1451 create, search and delete apply to a directory.
1452  
1453 '$path' is a directory; $kind access is revoked on a file
1454 (error_not_a_file)
1455 read, write and exec apply to a file.
1456  
1457 Could not chmod '$path' to $mode: $error (error_chmod_failed)
1458 code was not run.
1459 What to do: check that you own path.
1460  
1461 Could not restore mode $mode on '$path': $error
1462 (error_restore_failed)
1463 code ran (and any exception it threw is lost), but the old mode
1464 could not be put back.
1465 What to do: fix the mode by hand.
1466  
1467 (an error from Params::Validate::Strict or Params::Get)
1468 For example, code is not a code reference.
1469  
1470 (anything code dies with, unchanged)
1471  
1472 =cut
1473  
1474 47 ▶sub with_revoked {
Subroutine with_revoked: called CC=11 SCAR=24.0
Pod documented
1475 47 my ($params, $error) = _check_args('guard', \@_);
1476 47 ▶ Carp::croak($error) if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 9 38 47
1477  
1478 38 my ($kind, $code) = @{$params}{qw(kind code)};
1479 38 my $path = _untaint($params->{path});
1480 38 my $shown = _printable($path);
1481  
1482 38 ▶ if($FILE_KIND{$kind}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($FILE_KIND{$kind}) { } 28 10 38
1483 28 ▶ Carp::croak(_msg('error_not_a_file', $shown, $kind)) if -d $path;
Branch: 1 branch
BranchTrueFalseTotal
if -d $path 6 22 28
1484 } else {
1485 10 ▶ Carp::croak(_msg('error_not_a_directory', $shown)) unless -d $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $path 5 5 10
1486 }
1487  
1488 27 my ($old_mode, $restricted) = (_mode_of($path), $PROBE{$kind}{restricted});
1489 27 $error = _chmod_error($path, $restricted);
1490 27 ▶ Carp::croak(_msg('error_chmod_failed', $shown, $restricted, $error)) if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 3 24 27
1491  
1492 # Run the code in the caller's context. $@ is localised only around
1493 # the eval, so that the exception can be rethrown outside it (on
1494 # perl < 5.14 a die inside a 'local $@' scope loses the exception).
1495 24 my $want = wantarray;
1496 24 my (@result, $ok, $exception);
1497 {
1498 24 local $@;
1499 24 $ok = eval {
1500 24 ▶ if($want) {
Branch: 2 branches
BranchTrueFalseTotal
if ($want) { } 2 22 24
elsif (defined $want) { } 2 20 22
1501 2 @result = $code->();
1502 } elsif(defined $want) {
1503 2 $result[0] = $code->();
1504 } else {
1505 20 $code->();
1506 }
1507 21 1;
1508 };
1509 24 $exception = $@;
1510 }
1511  
1512 24 $error = _chmod_error($path, $old_mode);
1513 24 ▶ Carp::croak(_msg('error_restore_failed', $old_mode, $shown, $error)) if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 3 21 24
1514  
1515 # Pass the code's exception on unchanged (objects included); croak
1516 # would add a location to it.
1517 21 ▶ die $exception unless $ok; ## no critic (ErrorHandling::RequireCarping)
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 2 19 21
1518  
1519 19 ▶ return $want ? @result : $result[0];
Branch: 1 branch
BranchTrueFalseTotal
$want ? : 2 17 19
1520 }
1521  
1522 =head2 permissions_report(dir)
1523  
1524 =head3 PURPOSE
1525  
1526 Describe, in a few lines, what C<chmod> can revoke in C<dir>: every kind,
1527 with the reason for each 0. Print it once with C<diag> (or C<note>) so
1528 that a CPAN Testers report shows the environment the tests ran in.
1529  
1530 =head3 ARGUMENTS
1531  
1532 =over 4
1533  
1534 =item * C<dir> - optional. As for L</can_revoke_read(dir)>.
1535  
1536 =back
1537  
1538 =head3 RETURNS
1539  
1540 A string of lines, ending without a newline:
1541  
1542 Test::Permissions 0.001.0 in '/tmp/abc' (effective uid 1000):
1543 read: yes
1544 ...
1545 sticky: no - The sticky probe in '/tmp/abc' must act as two users, ...
1546  
1547 =head3 SIDE EFFECTS
1548  
1549 Probes every kind that is not already cached for C<dir>, as
1550 L</can_revoke(kind, dir)> would.
1551  
1552 =head3 USAGE EXAMPLE
1553  
1554 diag(Test::Permissions::permissions_report($dir));
1555  
1556 =head3 API SPECIFICATION
1557  
1558 =head4 Input
1559  
1560 {
1561 dir => {
1562 type => 'string',
1563 optional => 1,
1564 min => 1,
1565 position => 0,
1566 },
1567 }
1568  
1569 =head4 Output
1570  
1571 { type => 'string', min => 1 }
1572  
1573 =head3 MESSAGES
1574  
1575 Errors: the same as L</can_revoke_read(dir)>.
1576  
1577 The lines come from the messages C<report_header> (arguments: version,
1578 directory, effective uid), C<report_yes> (kind) and C<report_no> (kind,
1579 reason), which L</set_messages(%overrides)> can translate.
1580  
1581 =cut
1582  
1583 8 ▶sub permissions_report {
Subroutine permissions_report: called CC=4 SCAR=13.9
Pod documented
1584 8 my ($params, $error) = _check_args('dir', \@_);
1585 8 ▶ Carp::croak($error) if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 1 7 8
1586  
1587 7 my $dir = $params->{dir};
1588 7 my @lines = _msg('report_header', $VERSION, _printable(_canonical($dir)), $>);
1589 7 for my $kind (@KINDS) {
1590 49 my $entry = _answer($kind, $dir);
1591 49 ▶ push @lines, $entry->[0] ? _msg('report_yes', $kind) : _msg('report_no', $kind, $entry->[1]);
Branch: 1 branch
BranchTrueFalseTotal
$entry->[0] ? : 33 16 49
1592 }
1593 7 return _set_return(join("\n", @lines), 'report');
1594 }
1595  
1596 =head2 clear_cache()
1597  
1598 =head3 PURPOSE
1599  
1600 Forget every answer, so the next call probes again. This is mainly for
1601 the module's own tests, and for a directory whose permissions or mount
1602 have changed since it was probed.
1603  
1604 =head3 ARGUMENTS
1605  
1606 None.
1607  
1608 =head3 RETURNS
1609  
1610 Nothing.
1611  
1612 =head3 SIDE EFFECTS
1613  
1614 Empties the cache.
1615  
1616 =head3 USAGE EXAMPLE
1617  
1618 Test::Permissions::clear_cache();
1619  
1620 =head3 API SPECIFICATION
1621  
1622 =head4 Input
1623  
1624 {}
1625  
1626 =head4 Output
1627  
1628 { type => 'void' }
1629  
1630 =head3 MESSAGES
1631  
1632 None.
1633  
1634 =cut
1635  
1636 724 ▶sub clear_cache {
Subroutine clear_cache: called CC=1 SCAR=0.0
Pod documented
1637 724 %cache = ();
1638 724 _set_return(undef, 'void');
1639 724 return;
1640 }
1641  
1642 =head2 set_cache_scope(scope)
1643  
1644 =head3 PURPOSE
1645  
1646 Choose how answers are shared between directories.
1647  
1648 =over 4
1649  
1650 =item * C<directory> (the default) - each directory is probed on its own.
1651 This is always right, because ACLs, bind mounts and mount options can
1652 differ between directories on one device.
1653  
1654 =item * C<device> - directories on the same device (the same C<st_dev>)
1655 share answers. A suite that makes a new C<tempdir> for every test can
1656 use this to probe once instead of once per directory, when it knows its
1657 directories are alike. The reason text names the first directory probed
1658 on the device.
1659  
1660 =back
1661  
1662 =head3 ARGUMENTS
1663  
1664 =over 4
1665  
1666 =item * C<scope> - required. C<directory> or C<device>.
1667  
1668 =back
1669  
1670 =head3 RETURNS
1671  
1672 Nothing.
1673  
1674 =head3 SIDE EFFECTS
1675  
1676 Applies to later calls. Answers already cached under the other scope
1677 stay in the cache but are not used.
1678  
1679 =head3 USAGE EXAMPLE
1680  
1681 Test::Permissions::set_cache_scope('device');
1682  
1683 =head3 API SPECIFICATION
1684  
1685 =head4 Input
1686  
1687 {
1688 scope => {
1689 type => 'string',
1690 memberof => [ 'directory', 'device' ],
1691 position => 0,
1692 },
1693 }
1694  
1695 =head4 Output
1696  
1697 { type => 'void' }
1698  
1699 =head3 MESSAGES
1700  
1701 Errors (the call dies): an error from Params::Validate::Strict when scope
1702 is missing or not one of the two names.
1703  
1704 =cut
1705  
1706 17 ▶sub set_cache_scope {
Subroutine set_cache_scope: called CC=2 SCAR=6.9
Pod documented
1707 17 my ($params, $error) = _check_args('scope', \@_);
1708 17 ▶ Carp::croak($error) if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 6 11 17
1709  
1710 11 $cache_scope = $params->{scope};
1711 11 _set_return(undef, 'void');
1712 11 return;
1713 }
1714  
1715 =head2 set_messages(%overrides)
1716  
1717 =head3 PURPOSE
1718  
1719 Replace message texts by key, for example to translate them.
1720  
1721 =head3 ARGUMENTS
1722  
1723 Pairs of message key and text, as a list or a hash reference. The keys
1724 are those listed under MESSAGES for each function (C<error_*>, C<reason_*>
1725 and C<report_*>). Each text is a C<sprintf> format taking the same
1726 arguments, in the same order, as the default text.
1727  
1728 =head3 RETURNS
1729  
1730 Nothing.
1731  
1732 =head3 SIDE EFFECTS
1733  
1734 =over 4
1735  
1736 =item * Changes the texts for the rest of the process.
1737  
1738 =item * Reasons are worded when a probe runs, so answers already in the
1739 cache keep their old wording until L</clear_cache()>.
1740  
1741 =item * All pairs are checked before any is applied: if one is invalid,
1742 nothing changes.
1743  
1744 =item * A text with more or fewer C<%s> than the default does not warn:
1745 missing arguments are empty and extra ones are ignored.
1746  
1747 =back
1748  
1749 =head3 USAGE EXAMPLE
1750  
1751 Test::Permissions::set_messages(
1752 reason_not_enforced => q{chmod ne peut pas retirer l'acces %s dans '%s'},
1753 );
1754  
1755 =head3 API SPECIFICATION
1756  
1757 =head4 Input
1758  
1759 {
1760 error_unknown_kind => { type => 'string', min => 1, optional => 1 },
1761 error_not_a_directory => { type => 'string', min => 1, optional => 1 },
1762 error_not_a_file => { type => 'string', min => 1, optional => 1 },
1763 error_no_such_path => { type => 'string', min => 1, optional => 1 },
1764 error_unknown_message => { type => 'string', min => 1, optional => 1 },
1765 error_too_many_arguments => { type => 'string', min => 1, optional => 1 },
1766 error_chmod_failed => { type => 'string', min => 1, optional => 1 },
1767 error_restore_failed => { type => 'string', min => 1, optional => 1 },
1768 reason_not_enforced => { type => 'string', min => 1, optional => 1 },
1769 reason_chmod_ignored => { type => 'string', min => 1, optional => 1 },
1770 reason_baseline_failed => { type => 'string', min => 1, optional => 1 },
1771 reason_other_error => { type => 'string', min => 1, optional => 1 },
1772 reason_setup_failed => { type => 'string', min => 1, optional => 1 },
1773 reason_cleanup_failed => { type => 'string', min => 1, optional => 1 },
1774 reason_probe_succeeded => { type => 'string', min => 1, optional => 1 },
1775 reason_needs_root => { type => 'string', min => 1, optional => 1 },
1776 report_header => { type => 'string', min => 1, optional => 1 },
1777 report_yes => { type => 'string', min => 1, optional => 1 },
1778 report_no => { type => 'string', min => 1, optional => 1 },
1779 }
1780  
1781 =head4 Output
1782  
1783 { type => 'void' }
1784  
1785 =head3 MESSAGES
1786  
1787 Errors (the call dies, and no text is changed):
1788  
1789 Unknown message key '$key' (error_unknown_message)
1790 What to do: use a key listed under MESSAGES.
1791  
1792 (an error from Params::Validate::Strict or Params::Get)
1793 A text is empty or not a string, or the arguments are not pairs.
1794  
1795 =cut
1796  
1797 52 ▶sub set_messages {
Subroutine set_messages: called CC=2 SCAR=6.9
Pod documented
1798 52 my ($texts, $error) = _check_messages(\@_);
1799 52 ▶ Carp::croak($error) if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 19 33 52
1800  
1801 33 @message_override{keys %{$texts}} = values %{$texts};
1802 33 _set_return(undef, 'void');
1803 33 return;
1804 }
1805  
1806 # -----------------------------------------------------------------------
1807 # Argument handling
1808 # -----------------------------------------------------------------------
1809  
1810 # _check_args
1811 #
1812 # Purpose: Turn a public function's @_ into a validated hashref.
1813 # Errors are returned rather than thrown, so the caller can
1814 # croak outside the local($@, $!) scope here (on perl < 5.14 a
1815 # die inside a 'local $@' scope loses the message).
1816 # Entry: $schema_name - a key of %INPUT_SCHEMA; $args - arrayref of @_.
1817 # Exit: ($params, undef) on success, with dir set (default tmpdir);
1818 # (undef, $message) on a caller error.
1819 2691 ▶sub _check_args {
Subroutine _check_args: called CC=12 SCAR=24.8
1820 2691 my ($schema_name, $args) = @_;
1821 2691 local ($@, $!);
1822  
1823 2691 my $schema = $INPUT_SCHEMA{$schema_name};
1824 2691 my @names = sort { $schema->{$a}{position} <=> $schema->{$b}{position} } keys %{$schema};
1825  
1826 2691 my $params;
1827 2691 my $ok = eval {
1828 2691 $params = _normalise_args(\@names, $args);
1829 2690 1;
1830 };
1831 2691 ▶ return (undef, _exception_text($@)) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 1 2690 2691
1832 2690 ▶ return (undef, $params) if !ref $params; # an error message
Branch: 1 branch
BranchTrueFalseTotal
unless ref $params 7 2683 2690
1833  
1834 # Our own message for an unknown kind, before the generic validator.
1835 2683 my $kind = $params->{kind};
1836 2683 ▶ if(defined $kind && !ref $kind) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $kind and not ref $kind) 1569 1114 2683
Condition100%3/3
defined $kind and not ref $kind
!ll&&!rl&&r
111221569
MC/DC100%2/2
defined $kind and not ref $kind
defined $kind not ref $kind
Truth table100%3/3
A and not(B)
A= defined $kindB= not ref $kind
ABresult
0X0
100
111
1837 1569 my @allowed = @{ $schema->{kind}{memberof} };
1838 1569 ▶ if(!grep { $_ eq $kind } @allowed) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$_ eq $kind;} @allowed) 36 1533 1569
1839 36 return (undef, _msg('error_unknown_kind', _printable($kind), join(', ', @allowed)));
1840 }
1841 }
1842  
1843 # The documented schemas carry 'position'; the validator's positional
1844 # mode mis-reports missing arguments, so validate the hash form.
1845 2647 my %hash_schema = map { $_ => _hash_rule($schema->{$_}) } @names;
1846 2647 $ok = eval {
1847 2647 $params = Params::Validate::Strict::validate_strict(schema => \%hash_schema, input => $params);
1848 2602 1;
1849 };
1850 2647 ▶ return (undef, _exception_text($@)) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 45 2602 2647
1851  
1852 2602 ▶ if(exists $schema->{dir}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $schema->{"dir"}) 2528 74 2602
1853 2528 ▶ $params->{dir} = File::Spec->tmpdir() unless defined $params->{dir};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $params->{"dir"} 12 2516 2528
1854 return (undef, _msg('error_not_a_directory', _printable($params->{dir})))
1855 2528 ▶ unless -d $params->{dir};
Branch: 1 branch
BranchTrueFalseTotal
unless -d $params->{"dir"} 15 2513 2528
1856 }
1857 2587 ▶ if(exists $schema->{path}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $schema->{"path"}) 63 2524 2587
1858 return (undef, _msg('error_no_such_path', _printable($params->{path})))
1859 63 ▶ unless -e $params->{path};
Branch: 1 branch
BranchTrueFalseTotal
unless -e $params->{"path"} 5 58 63
1860 }
1861 2582 return ($params, undef);
1862 }
1863  
1864 # _hash_rule
1865 #
1866 # Purpose: A plain (not Readonly) copy of one schema rule, without
1867 # 'position', for validating the hash form of the arguments.
1868 # Entry: $rule - a hashref from %INPUT_SCHEMA.
1869 # Exit: A new hashref.
1870 4277 ▶sub _hash_rule {
Subroutine _hash_rule: called CC=2 SCAR=6.9
1871 4277 my $rule = $_[0];
1872 4277 my %copy = %{$rule};
1873 4277 delete $copy{position};
1874 4277 ▶ $copy{memberof} = [ @{ $copy{memberof} } ] if $copy{memberof};
Branch: 1 branch
BranchTrueFalseTotal
if $copy{"memberof"} 1557 2720 4277
1875 4277 return \%copy;
1876 }
1877  
1878 # _normalise_args
1879 #
1880 # Purpose: Accept every calling form: f(), f(@positional),
1881 # f(name => value, ...), f({ name => value }).
1882 # Params::Get's positional mode does not recognise named pairs,
1883 # so the named form is detected here: an even number of
1884 # arguments, the first of which is an argument name. (No valid
1885 # positional call looks like that: a kind is never 'kind', 'count'
1886 # or 'dir', and a lone directory is a single argument.) Unknown
1887 # names in the rest are then reported by the validator.
1888 # Entry: $names - argument names in positional order; $args - arrayref.
1889 # Exit: A new hashref (the caller's hash is never modified), with
1890 # undefined values removed and stringifiable objects turned into
1891 # strings; or a plain string, the error message for too many
1892 # positional arguments. Params::Get may croak on malformed
1893 # input.
1894 2700 ▶sub _normalise_args {
Subroutine _normalise_args: called CC=14 SCAR=26.4
1895 2700 my ($names, $args) = @_;
1896  
1897 2700 my %known = map { $_ => 1 } @{$names};
1898 2700 my $params;
1899 2700 ▶ if(@{$args} == 1 && ref $args->[0] eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (@{$args;} == 1 and ref $args->[0] eq 'HASH') { } 13 2687 2700
elsif (@{$args;} >= 2 and @{$args;} % 2 == 0 and defined $args->[0] and not ref $args->[0] and $known{$args->[0]}) { } 9 2678 2687
Condition100%3/3
@{$args;} == 1 and ref $args->[0] eq "HASH"
!ll&&!rl&&r
1583110413
MC/DC100%2/2
@{$args;} == 1 and ref $args->[0] eq "HASH"
@{$args;} == 1 ref $args->[0] eq "HASH"
Truth table100%3/3
A and B
A= @{$args;} == 1B= ref $args->[0] eq "HASH"
ABresult
0X0
100
111
1900 13 $params = { %{ Params::Get::get_params(undef, $args->[0]) } };
1901 2687 ▶ } elsif(@{$args} >= 2 && @{$args} % 2 == 0 && defined $args->[0] && !ref $args->[0] && $known{$args->[0]}) {
Condition100%12/12
@{$args;} >= 2 and @{$args;} % 2 == 0 and defined $args->[0] and not ref $args->[0] and $known{$args->[0]}
!ll&&!rl&&r
120514739
@{$args;} >= 2 and @{$args;} % 2 == 0 and defined $args->[0] and not ref $args->[0]
!ll&&!rl&&r
120231482
@{$args;} >= 2 and @{$args;} % 2 == 0 and defined $args->[0]
!ll&&!rl&&r
120021485
@{$args;} >= 2 and @{$args;} % 2 == 0
!ll&&!rl&&r
1111891487
MC/DC100%5/5
@{$args;} >= 2 and @{$args;} % 2 == 0 and defined $args->[0] and not ref $args->[0] and $known{$args->[0]}
@{$args;} >= 2 @{$args;} % 2 == 0 defined $args->[0] not ref $args->[0] $known{$args->[0]}
Truth table100%6/6
A and B and C and not(D) and E
A= @{$args;} >= 2B= @{$args;} % 2 == 0C= defined $args->[0]D= not ref $args->[0]E= $known{$args->[0]}
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
1902 9 $params = { %{ Params::Get::get_params(undef, @{$args}) } };
1903 } else {
1904 8 return _msg('error_too_many_arguments', scalar @{$names}, scalar @{$args})
1905 2678 ▶ if @{$args} > @{$names};
Branch: 1 branch
BranchTrueFalseTotal
if @{$args;} > @{$names;} 8 2670 2678
1906 2670 ▶ $params = @{$args} ? { %{ Params::Get::get_params([ @{$names} ], @{$args}) } } : {};
Branch: 1 branch
BranchTrueFalseTotal
@{$args;} ? : 2663 7 2670
1907 }
1908  
1909 2691 for my $name (keys %{$params}) {
1910 4355 my $value = $params->{$name};
1911 4355 ▶ if(!defined $value) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $value) { } 29 4326 4355
elsif (ref $value and overload::Method($value, '""')) { } 2 8597 8599
1912 29 delete $params->{$name};
1913 ▶ } elsif(ref $value && overload::Method($value, q{""})) {
Condition100%3/3
ref $value and overload::Method($value, "\"\"")
!ll&&!rl&&r
4273512
MC/DC100%2/2
ref $value and overload::Method($value, "\"\"")
ref $value overload::Method($value, "\"\"")
Truth table100%3/3
A and B
A= ref $valueB= overload::Method($value, "\"\"")
ABresult
0X0
100
111
1914 2 $params->{$name} = "$value";
1915 }
1916 }
1917 2691 return $params;
1918 }
1919  
1920 # _check_messages
1921 #
1922 # Purpose: Validate set_messages() arguments, all before any is applied.
1923 # Entry: $args - arrayref of @_.
1924 # Exit: ($hashref, undef) or (undef, $message).
1925 55 ▶sub _check_messages {
Subroutine _check_messages: called CC=6 SCAR=17.9
1926 55 my $args = $_[0];
1927 55 local ($@, $!);
1928  
1929 55 ▶ return ({}, undef) unless @{$args};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$args;} 4 51 55
1930  
1931 51 my $texts;
1932 51 my $ok = eval {
1933 51 $texts = { %{ Params::Get::get_params(undef, @{$args}) } };
1934 49 1;
1935 };
1936 51 ▶ return (undef, _exception_text($@)) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 2 49 51
1937  
1938 49 for my $key (sort keys %{$texts}) {
1939 49 ▶ return (undef, _msg('error_unknown_message', _printable($key))) unless exists $MESSAGES{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $MESSAGES{$key} 11 38 49
1940 }
1941  
1942 # Every key given is required, so an undef text is refused too.
1943 38 my %schema = map { $_ => { type => 'string', min => 1 } } keys %{$texts};
1944 38 $ok = eval {
1945 38 Params::Validate::Strict::validate_strict(schema => \%schema, input => $texts);
1946 31 1;
1947 };
1948 38 ▶ return (undef, _exception_text($@)) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 7 31 38
1949 31 return ($texts, undef);
1950 }
1951  
1952 # _set_return
1953 #
1954 # Purpose: Return a value checked against an output schema (Return::Set),
1955 # without letting Return::Set's eval change the caller's $@.
1956 # Entry: $value; $schema_name - a key of %OUTPUT_SCHEMA.
1957 # Exit: $value.
1958 3291 ▶sub _set_return {
Subroutine _set_return: called CC=1 SCAR=0.0
1959 3291 my ($value, $schema_name) = @_;
1960 3291 local ($@, $!);
1961 3291 return Return::Set::set_return($value, { %{ $OUTPUT_SCHEMA{$schema_name} } });
1962 }
1963  
1964 # -----------------------------------------------------------------------
1965 # Messages
1966 # -----------------------------------------------------------------------
1967  
1968 # _msg
1969 #
1970 # Purpose: Format a user-facing text from the message dictionary.
1971 # Entry: $key - a key of %MESSAGES; @args - sprintf arguments, already
1972 # passed through _printable where they come from outside.
1973 # Exit: The text. Never warns or dies: a translated text with the
1974 # wrong number of arguments must not fail the caller's tests.
1975 # The caller's $@ is restored.
1976 1042 ▶sub _msg {
Subroutine _msg: called CC=3 SCAR=11.0
1977 1042 my ($key, @args) = @_;
1978  
1979 1042 ▶ my $format = defined $message_override{$key} ? $message_override{$key} : $MESSAGES{$key};
Branch: 1 branch
BranchTrueFalseTotal
defined $message_override{$key} ? : 35 1007 1042
1980 1042 local $@;
1981 1042 my $text = eval {
1982 17 ▶ no warnings; ## no critic (TestingAndDebugging::ProhibitNoWarnings)
Subroutine BEGIN: called CC=1 SCAR=0.0
1983 1042 sprintf $format, @args;
1984 };
1985 1042 ▶ return defined $text ? $text : join ': ', $key, @args;
Branch: 1 branch
BranchTrueFalseTotal
defined $text ? : 1041 1 1042
1986 }
1987  
1988 # _printable
1989 #
1990 # Purpose: Make a path or error text safe to put in a message. Control
1991 # characters and bidirectional-override characters become \x{..}
1992 # escapes; everything else is kept.
1993 # A byte string that is valid UTF-8 (the usual form of a
1994 # non-ASCII path on Unix) is checked as characters and returned
1995 # as bytes again, so its letters are not escaped; other byte
1996 # strings are checked for C0 and C1 controls.
1997 # Entry: $_[0] - any value (stringified; undef is '').
1998 # Exit: The escaped string.
1999 1807 ▶sub _printable {
Subroutine _printable: called CC=4 SCAR=13.9
2000 1807 ▶ my $text = defined $_[0] ? "$_[0]" : q{};
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 1806 1 1807
2001 1807 ▶ my $escape = sub { sprintf '\\x{%X}', ord $_[0] };
Subroutine __ANON__: called CC=1 SCAR=0.0
2002  
2003 1807 ▶ if(!utf8::is_utf8($text)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (utf8::is_utf8($text)) 1804 3 1807
2004 1804 my $chars = $text;
2005 1804 ▶ if(utf8::decode($chars)) {
Branch: 1 branch
BranchTrueFalseTotal
if (utf8::decode($chars)) 1801 3 1804
2006 1801 $chars =~ s/($UNSAFE_CHARS_RE)/$escape->($1)/ge;
2007 1801 utf8::encode($chars);
2008 1801 return $chars;
2009 }
2010 3 $text =~ s/($UNSAFE_BYTES_RE)/$escape->($1)/ge;
2011 3 return $text;
2012 }
2013 3 $text =~ s/($UNSAFE_CHARS_RE)/$escape->($1)/ge;
2014 3 return $text;
2015 }
2016  
2017 # _exception_text
2018 #
2019 # Purpose: Turn an exception (a string, or an autodie::exception object)
2020 # into one printable line.
2021 # Entry: $_[0] - the exception.
2022 # Exit: The text, without trailing newlines or a trailing
2023 # "at FILE line N.", via _printable.
2024 386 ▶sub _exception_text {
Subroutine _exception_text: called CC=4 SCAR=13.9
2025 386 ▶ my $text = defined $_[0] ? "$_[0]" : q{};
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 385 1 386
2026 386 ▶ $text = substr($text, 0, -1) while length $text && substr($text, -1) eq "\n";
Branch: 1 branch
BranchTrueFalseTotal
length $text and substr($text, -1) eq "\n" and do { $text = substr($text, 0, -1) } 375 386 761
Condition100%3/3
length $text and substr($text, -1) eq "\n"
!ll&&!rl&&r
2384375
MC/DC100%2/2
length $text and substr($text, -1) eq "\n"
length $text substr($text, -1) eq "\n"
Truth table100%3/3
A and B
A= length $textB= substr($text, -1) eq "\n"
ABresult
0X0
100
111
2027 # A croak from inside this module (the validator, Params::Get) names a
2028 # line here; croak adds the caller's line instead.
2029 386 $text =~ s/ at \S+ line [0-9]+\.\z//;
2030 386 return _printable($text);
2031 }
2032  
2033 # _errno_text
2034 #
2035 # Purpose: The system's text for an errno, in the current locale.
2036 # Entry: $errno - a number.
2037 # Exit: The printable text.
2038 156 ▶sub _errno_text {
Subroutine _errno_text: called CC=1 SCAR=0.0
2039 156 my ($errno) = @_;
2040 156 local $! = $errno;
2041 156 return _printable("$!");
2042 }
2043  
2044 # _untaint
2045 #
2046 # Purpose: Untaint a path the caller has named and this module has
2047 # checked (-d or -e). The module only ever creates its own
2048 # scratch directory inside such a path, or changes its mode at
2049 # the caller's request, so taint mode's protection is not lost.
2050 # Without this, every probe under perl -T fails its setup
2051 # ("Insecure dependency in mkdir") and answers 0.
2052 # Entry: $path.
2053 # Exit: The same string, untainted.
2054 2612 ▶sub _untaint {
Subroutine _untaint: called CC=1 SCAR=0.0
2055 2612 my ($path) = @_;
2056 2612 my ($clean) = $path =~ $ANYTHING_RE;
2057 2612 return $clean;
2058 }
2059  
2060 # -----------------------------------------------------------------------
2061 # Probing
2062 # -----------------------------------------------------------------------
2063  
2064 # _answer
2065 #
2066 # Purpose: Look up, or probe and cache, the answer for a kind and dir.
2067 # Entry: $kind - a kind from @KINDS; $dir - an existing directory.
2068 # Exit: Arrayref [ answer (1 or 0), reason (undef when 1) ].
2069 # Effects: May create and remove a probe directory in $dir. $@ and $!
2070 # are restored.
2071 2554 ▶sub _answer {
Subroutine _answer: called CC=2 SCAR=6.9
2072 2554 my ($kind, $dir) = @_;
2073 2554 local ($@, $!);
2074  
2075 2554 my $canonical = _canonical($dir);
2076 2554 my $key = _cache_key($kind, $canonical);
2077 2554 ▶ $cache{$key} = [ _probe($kind, $canonical) ] unless $cache{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless $cache{$key} 854 1700 2554
2078 2554 return $cache{$key};
2079 }
2080  
2081 # _cache_key
2082 #
2083 # Purpose: The cache key for a kind and directory. It includes the
2084 # effective uid and groups, because the answer depends on who
2085 # asks: a root suite that drops privileges must not reuse
2086 # root's answers. The directory part depends on the cache scope.
2087 # Entry: $kind; $canonical - canonical directory path.
2088 # Exit: The key.
2089 2561 ▶sub _cache_key {
Subroutine _cache_key: called CC=3 SCAR=11.0
2090 2561 my ($kind, $canonical) = @_;
2091 2561 my $where = "dir:$canonical";
2092 2561 ▶ if($cache_scope eq 'device') {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache_scope eq "device") 8 2553 2561
2093 8 my @stat = stat $canonical;
2094 8 ▶ $where = "dev:$stat[$STAT_DEV]" if @stat;
Branch: 1 branch
BranchTrueFalseTotal
if @stat 6 2 8
2095 }
2096 2561 return join $KEY_SEP, $kind, $>, $), $where;
2097 }
2098  
2099 # _canonical
2100 #
2101 # Purpose: The canonical absolute path of a directory: the cache key, and
2102 # where the probe runs. Not the device number: ACLs and bind
2103 # mounts can differ within one device, and inode numbers are 0
2104 # on Windows. Untainted (see _untaint).
2105 # Entry: $dir - an existing directory.
2106 # Exit: Cwd::abs_path($dir), or the absolute form of $dir if that fails.
2107 # Effects: None; $@ and $! are restored.
2108 2565 ▶sub _canonical {
Subroutine _canonical: called CC=3 SCAR=11.0
2109 2565 my ($dir) = @_;
2110 2565 local ($@, $!);
2111 2565 my $abs = eval { Cwd::abs_path($dir) };
2112 2565 ▶ $abs = File::Spec->rel2abs($dir) unless defined $abs && length $abs;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $abs and length $abs 2 2563 2565
Condition66%2/3
defined $abs and length $abs
!ll&&!rl&&r
202563
MC/DC50%1/2
defined $abs and length $abs
defined $abs length $abs
Truth table66%2/3
A and B
A= defined $absB= length $abs
ABresult
0X0
100
111
2113 2565 return _untaint($abs);
2114 }
2115  
2116 # _probe
2117 #
2118 # Purpose: Find out whether chmod can revoke $kind access in $dir, by
2119 # trying it (see "How a probe works" in the POD).
2120 # Strategy: steps 1-4 run inside one eval, so an exception from
2121 # any of them (autodie during setup, a mocked seam dying) becomes
2122 # reason_setup_failed. Step 5 (restore and clean up) runs after
2123 # the eval, whatever happened, and any failure there overrides
2124 # the answer with 0 and reason_cleanup_failed.
2125 # Entry: $kind - a kind from @KINDS; $dir - canonical directory path.
2126 # Exit: (answer, reason): (1, undef) or (0, text). Never dies or warns.
2127 # Effects: Creates and removes a probe directory in $dir.
2128 878 ▶sub _probe {
Subroutine _probe: called CC=15 SCAR=27.1
2129 878 my ($kind, $dir) = @_;
2130 878 my $probe = $PROBE{$kind};
2131 878 my $shown = _printable($dir);
2132  
2133 878 ▶ if($probe->{precondition} && !$probe->{precondition}->()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($probe->{"precondition"} and not $probe->{"precondition"}->()) 23 855 878
Condition100%3/3
$probe->{"precondition"} and not $probe->{"precondition"}->()
!ll&&!rl&&r
847823
MC/DC100%2/2
$probe->{"precondition"} and not $probe->{"precondition"}->()
$probe->{"precondition"} not $probe->{"precondition"}->()
Truth table100%3/3
A and not(B)
A= $probe->{"precondition"}B= not $probe->{"precondition"}->()
ABresult
0X0
100
111
2134 23 return (0, _msg('reason_needs_root', $kind, $shown));
2135 }
2136  
2137 # Internal exceptions are expected; the caller's die hook (for example
2138 # a stack-trace printer) must not see them.
2139 855 local $SIG{__DIE__};
2140  
2141 855 my ($probe_dir, $paths, $restore_target);
2142 855 my ($answer, $reason) = (0, undef);
2143 855 ▶ my $bits = defined $probe->{bits} ? $probe->{bits} : $OWNER_BITS;
Branch: 1 branch
BranchTrueFalseTotal
defined $probe->{'bits'} ? : 8 847 855
2144  
2145 855 my $ok = eval {
2146 # 1. Setup.
2147 855 $probe_dir = _make_probe_dir($dir);
2148 584 $paths = $probe->{setup}->($probe_dir);
2149  
2150 # 2. Baseline: the operation must work while it is allowed.
2151 582 my ($baseline_ok, $baseline_errno) = $probe->{op}->($paths);
2152 575 ▶ if(!$baseline_ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($baseline_ok) 130 445 575
2153 130 $reason = _msg('reason_baseline_failed', $kind, $shown, _errno_text($baseline_errno));
2154 130 return 1;
2155 }
2156 445 ▶ $probe->{tidy}->($paths) if $probe->{tidy};
Branch: 1 branch
BranchTrueFalseTotal
if $probe->{"tidy"} 132 313 445
2157  
2158 # 3. Restrict, and check that chmod really changed the mode bits.
2159 443 $restore_target = $paths->{target};
2160 443 _set_mode($paths->{target}, $probe->{restricted});
2161 443 my $got = _mode_of($paths->{target});
2162 443 ▶ if(!defined $got) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $got) 3 440 443
2163 3 $reason = _msg('reason_setup_failed', $kind, $shown, _printable("$!"));
2164 3 return 1;
2165 }
2166 440 ▶ if(($got & $bits) != ($probe->{restricted} & $bits)) {
Branch: 1 branch
BranchTrueFalseTotal
if (($got & $bits) != ($probe->{"restricted"} & $bits)) 67 373 440
2167 67 $reason = _msg('reason_chmod_ignored', $probe->{restricted}, $shown, $got & $MODE_BITS);
2168 67 return 1;
2169 }
2170  
2171 # 4. Attempt: only EACCES or EPERM means chmod took access away.
2172 373 my ($attempt_ok, $attempt_errno) = $probe->{op}->($paths);
2173 353 ▶ if($attempt_ok) {
Branch: 2 branches
BranchTrueFalseTotal
if ($attempt_ok) { } 52 301 353
elsif ($DENIED_ERRNO{$attempt_errno}) { } 276 25 301
2174 52 $reason = _msg('reason_not_enforced', $kind, $shown);
2175 } elsif($DENIED_ERRNO{$attempt_errno}) {
2176 276 $answer = 1;
2177 } else {
2178 25 $reason = _msg('reason_other_error', $kind, $shown, _errno_text($attempt_errno));
2179 }
2180 353 1;
2181 };
2182 855 ▶ if(!$ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 302 553 855
2183 302 ($answer, $reason) = (0, _msg('reason_setup_failed', $kind, $shown, _exception_text($@)));
2184 }
2185  
2186 # 5. Restore and clean up, always.
2187 855 my $problem = _cleanup($probe_dir, $restore_target, $probe->{permissive});
2188 855 ▶ if(defined $problem) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $problem) 255 600 855
2189 255 ▶ $reason = _msg('reason_probe_succeeded', $kind, $shown) if $answer;
Branch: 1 branch
BranchTrueFalseTotal
if $answer 20 235 255
2190 255 ▶ ($answer, $reason) = (0, _msg('reason_cleanup_failed', $reason,
Branch: 1 branch
BranchTrueFalseTotal
defined $probe_dir ? : 135 120 255
2191 _printable(defined $probe_dir ? $probe_dir : $dir), $problem));
2192 }
2193  
2194 855 ▶ return ($answer, $answer ? undef : $reason);
Branch: 1 branch
BranchTrueFalseTotal
$answer ? : 256 599 855
2195 }
2196  
2197 # _cleanup
2198 #
2199 # Purpose: Step 5 of a probe: restore the permissive mode, then remove the
2200 # probe directory. Both are attempted even if the first fails.
2201 # Entry: $probe_dir - P, or undef if it was never created;
2202 # $target - the path that was chmod-ed, or undef;
2203 # $mode - the permissive mode to restore.
2204 # Exit: undef on success, or the printable text of what went wrong.
2205 864 ▶sub _cleanup {
Subroutine _cleanup: called CC=10 SCAR=23.0
2206 864 my ($probe_dir, $target, $mode) = @_;
2207  
2208 864 my @problems;
2209 864 ▶ if(defined $target) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $target) 446 418 864
2210 446 my $restored = eval { _set_mode($target, $mode) };
2211 446 ▶ push @problems, _exception_text($@ || "$target: $!") unless $restored;
Branch: 1 branch
BranchTrueFalseTotal
unless $restored 15 431 446
Condition100%2/2
$@ || "${target}: $!"
l!l
87
MC/DC100%1/1
$@ || "${target}: $!"
$@
Truth table100%2/2
A
A= $@
Aresult
11
00
2212 }
2213 864 ▶ if(defined $probe_dir) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $probe_dir) 588 276 864
2214 588 my $errors;
2215 588 my $ok = eval {
2216 588 File::Path::remove_tree($probe_dir, { error => \$errors });
2217 586 1;
2218 };
2219 588 ▶ push @problems, _exception_text($@) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 2 586 588
2220 588 ▶ for my $error (@{ $errors || [] }) {
Condition100%2/2
$errors || []
l!l
5862
MC/DC100%1/1
$errors || []
$errors
Truth table100%2/2
A
A= $errors
Aresult
11
00
2221 3 my ($path, $text) = %{$error};
2222 3 ▶ push @problems, _printable(length $path ? "$path: $text" : $text);
Branch: 1 branch
BranchTrueFalseTotal
length $path ? : 2 1 3
2223 }
2224 }
2225 864 ▶ return @problems ? join('; ', @problems) : undef;
Branch: 1 branch
BranchTrueFalseTotal
@problems ? : 19 845 864
2226 }
2227  
2228 # _chmod_error
2229 #
2230 # Purpose: chmod a path for with_revoked, reporting failure as text.
2231 # Entry: $path; $mode.
2232 # Exit: undef on success, else the printable error text.
2233 53 ▶sub _chmod_error {
Subroutine _chmod_error: called CC=3 SCAR=11.0
2234 53 my ($path, $mode) = @_;
2235 53 local ($@, $!);
2236 53 my $ok = eval { _set_mode($path, $mode) };
2237 53 ▶ return $ok ? undef : _exception_text($@ || "$!");
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 46 7 53
Condition66%2/3
$@ || "$!"
l!l&&r!l&&!r
601
MC/DC50%1/2
$@ || "$!"
$@ "$!"
Truth table66%2/3
A || B
A= $@B= "$!"
ABresult
1X1
011
000
2238 }
2239  
2240 # _setup_file
2241 #
2242 # Purpose: Setup for the read, write and exec kinds: file P/f with the
2243 # given content and mode.
2244 # Entry: $probe_dir - P; $content; $mode.
2245 # Exit: { target => P/f, object => P/f }. Throws (autodie) on failure.
2246 320 ▶sub _setup_file {
Subroutine _setup_file: called CC=1 SCAR=0.0
2247 320 my ($probe_dir, $content, $mode) = @_;
2248 320 my $file = File::Spec->catfile($probe_dir, $PROBE_FILE);
2249 320 _make_file($file, $content);
2250 320 _set_mode($file, $mode);
2251 320 return { target => $file, object => $file };
2252 }
2253  
2254 # _setup_subdir
2255 #
2256 # Purpose: Setup for the create, search and delete kinds: directory P/d,
2257 # mode 0700, optionally holding file P/d/f (mode 0600).
2258 # Entry: $probe_dir - P; $with_file - true to create P/d/f.
2259 # Exit: { target => P/d, object => P/d/f or P/d/new }. Throws on
2260 # failure.
2261 261 ▶sub _setup_subdir {
Subroutine _setup_subdir: called CC=2 SCAR=6.9
2262 261 my ($probe_dir, $with_file) = @_;
2263 261 my $subdir = File::Spec->catdir($probe_dir, $PROBE_SUBDIR);
2264 261 mkdir $subdir;
2265 261 _set_mode($subdir, $MODE_DIR_RWX);
2266 261 ▶ if($with_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($with_file) 172 89 261
2267 172 my $file = File::Spec->catfile($subdir, $PROBE_FILE);
2268 172 _make_file($file, q{});
2269 172 _set_mode($file, $MODE_FILE_RW);
2270 172 return { target => $subdir, object => $file };
2271 }
2272 89 return { target => $subdir, object => File::Spec->catfile($subdir, $PROBE_NEW) };
2273 }
2274  
2275 # _setup_sticky
2276 #
2277 # Purpose: Setup for the sticky kind: directory P/d, mode 0777, holding
2278 # file P/d/f owned by $STICKY_OWNER_UID. The op deletes it as
2279 # $STICKY_OTHER_UID.
2280 # Entry: $probe_dir - P.
2281 # Exit: { target => P/d, object => P/d/f, as => other uid }. Throws
2282 # on failure.
2283 9 ▶sub _setup_sticky {
Subroutine _setup_sticky: called CC=1 SCAR=0.0
2284 9 my ($probe_dir) = @_;
2285 9 my $subdir = File::Spec->catdir($probe_dir, $PROBE_SUBDIR);
2286 9 mkdir $subdir;
2287 9 _set_mode($subdir, $MODE_DIR_ALL);
2288 9 my $file = File::Spec->catfile($subdir, $PROBE_FILE);
2289 9 _make_file($file, q{});
2290 9 _give_away($file, $STICKY_OWNER_UID);
2291 8 return { target => $subdir, object => $file, as => $STICKY_OTHER_UID };
2292 }
2293  
2294 # _make_file
2295 #
2296 # Purpose: Create a file with exactly the given bytes (binmode: on
2297 # Windows, text mode would turn the script's "\n" into "\r\n").
2298 # Setup step: autodie.
2299 # Entry: $path; $content.
2300 # Exit: Nothing useful. Throws on failure (close reports write errors).
2301 587 ▶sub _make_file {
Subroutine _make_file: called CC=2 SCAR=6.9
2302 587 my ($path, $content) = @_;
2303 587 open(my $fh, $OPEN_TRUNCATE, $path);
2304 586 binmode $fh;
2305 586 ▶ print {$fh} $content if length $content;
Branch: 1 branch
BranchTrueFalseTotal
if length $content 325 261 586
2306 586 close $fh;
2307 586 return;
2308 }
2309  
2310 # _mode_allows
2311 #
2312 # Purpose: What the mode bits alone say about $kind access for the
2313 # effective uid and groups (acl_denies). Root may read and
2314 # write anything, and search any directory, but may run a file
2315 # only if some execute bit is set. On Windows, where $> is
2316 # always 0, the owner bits decide.
2317 # Entry: $kind - read, write or exec; $stat - arrayref from stat;
2318 # $is_dir - true for a directory.
2319 # Exit: 1 or 0.
2320 27 ▶sub _mode_allows {
Subroutine _mode_allows: called CC=9 SCAR=22.0
2321 27 my ($kind, $stat, $is_dir) = @_;
2322 27 my $mode = $stat->[$STAT_MODE];
2323 27 my (undef, $euid) = _uids();
2324  
2325 27 ▶ if($euid == $ROOT_UID && $^O ne 'MSWin32') {
Branch: 1 branch
BranchTrueFalseTotal
if ($euid == $ROOT_UID and $^O ne "MSWin32") 5 22 27
Condition66%2/3
$euid == $ROOT_UID and $^O ne "MSWin32"
!ll&&!rl&&r
2205
MC/DC50%1/2
$euid == $ROOT_UID and $^O ne "MSWin32"
$euid == $ROOT_UID $^O ne "MSWin32"
Truth table66%2/3
A and B
A= $euid == $ROOT_UIDB= $^O ne "MSWin32"
ABresult
0X0
100
111
2326 5 ▶ return 1 unless $kind eq 'exec';
Branch: 1 branch
BranchTrueFalseTotal
unless $kind eq "exec" 2 3 5
2327 3 ▶ return $is_dir || ($mode & $ANY_EXEC) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$is_dir || $mode & $ANY_EXEC ? : 2 1 3
Condition100%3/3
$is_dir or $mode & $ANY_EXEC
l!l&&r!l&&!r
111
MC/DC100%2/2
$is_dir or $mode & $ANY_EXEC
$is_dir $mode & $ANY_EXEC
Truth table100%3/3
A or B
A= $is_dirB= $mode & $ANY_EXEC
ABresult
1X1
011
000
2328 }
2329 22 my %group = map { $_ => 1 } split ' ', $);
2330 my $shift = $stat->[$STAT_UID] == $euid ? $OWNER_SHIFT
2331 22 ▶ : $group{ $stat->[$STAT_GID] } ? $GROUP_SHIFT
Branch: 2 branches
BranchTrueFalseTotal
$stat->[$STAT_UID] == $euid ? : 16 6 22
$group{$stat->[$STAT_GID]} ? : 3 3 6
2332 : $OTHER_SHIFT;
2333 22 ▶ return ($mode >> $shift) & $ACCESS_BIT{$kind} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$mode >> $shift & $ACCESS_BIT{$kind} ? : 16 6 22
2334 }
2335  
2336 # -----------------------------------------------------------------------
2337 # Seams: every probe step goes through one of these, so that tests can
2338 # simulate any environment by mocking them.
2339 # -----------------------------------------------------------------------
2340  
2341 # _make_probe_dir
2342 #
2343 # Purpose: Create the probe directory P inside $dir, mode 0700.
2344 # CLEANUP is only a fallback; _cleanup removes P explicitly.
2345 # Entry: $dir - the target directory (untainted).
2346 # Exit: The path of P. Throws on failure.
2347 598 ▶sub _make_probe_dir {
Subroutine _make_probe_dir: called CC=1 SCAR=0.0
2348 598 my ($dir) = @_;
2349 598 my $probe_dir = File::Temp::tempdir($PROBE_TEMPLATE, DIR => $dir, CLEANUP => 1);
2350 591 _set_mode($probe_dir, $MODE_DIR_RWX);
2351 591 return $probe_dir;
2352 }
2353  
2354 # _try_open
2355 #
2356 # Purpose: The attempt for read, write and create: open a file.
2357 # Entry: $path; $mode - an open() mode.
2358 # Exit: (1, 0) if it opened (the handle is closed again), else
2359 # (0, errno). Never throws.
2360 363 ▶sub _try_open {
Subroutine _try_open: called CC=2 SCAR=6.9
2361 363 my ($path, $mode) = @_;
2362 17 ▶ no autodie;
Subroutine BEGIN: called CC=1 SCAR=0.0
2363 363 ▶ if(open my $fh, $mode, $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $fh, $mode, $path) 249 114 363
2364 249 close $fh;
2365 249 return (1, 0);
2366 }
2367 114 return (0, 0 + $!);
2368 }
2369  
2370 # _try_stat
2371 #
2372 # Purpose: The attempt for search: stat a file.
2373 # Entry: $path.
2374 # Exit: (1, 0) or (0, errno). Never throws.
2375 100 ▶sub _try_stat {
Subroutine _try_stat: called CC=2 SCAR=6.9
2376 100 my ($path) = @_;
2377 17 ▶ no autodie;
Subroutine BEGIN: called CC=1 SCAR=0.0
2378 100 my @stat = stat $path;
2379 100 ▶ return @stat ? (1, 0) : (0, 0 + $!);
Branch: 1 branch
BranchTrueFalseTotal
@stat ? : 66 34 100
2380 }
2381  
2382 # _try_exec
2383 #
2384 # Purpose: The attempt for exec: run the probe's script, without a shell,
2385 # with the variables in @UNSAFE_ENV removed (taint mode refuses
2386 # to run anything while they are set).
2387 # Entry: $path.
2388 # Exit: (1, 0) if it ran and exited 0; (0, errno) if it could not be
2389 # run; (0, ENOEXEC) if it ran but did not exit 0. Never throws.
2390 69 ▶sub _try_exec {
Subroutine _try_exec: called CC=3 SCAR=11.0
2391 69 my ($path) = @_;
2392 17 ▶ no autodie;
Subroutine BEGIN: called CC=1 SCAR=0.0
2393 17 ▶ no warnings 'exec'; ## no critic (TestingAndDebugging::ProhibitNoWarnings) - "Can't exec" is expected
Subroutine BEGIN: called CC=1 SCAR=0.0
2394  
2395 69 local %ENV = %ENV;
2396 69 delete @ENV{@UNSAFE_ENV};
2397 69 my $status = system { $path } $path;
2398 69 ▶ return (0, 0 + $!) if $status == -1;
Branch: 1 branch
BranchTrueFalseTotal
if $status == -1 34 35 69
2399 35 ▶ return $? == 0 ? (1, 0) : (0, $ERRNO_BAD_EXIT);
Branch: 1 branch
BranchTrueFalseTotal
$? == 0 ? : 33 2 35
2400 }
2401  
2402 # _try_unlink
2403 #
2404 # Purpose: The attempt for delete and sticky: unlink a file, optionally
2405 # as another user. To act as another user it changes directory
2406 # to the file's directory first (as root), then sets the
2407 # effective uid only for the unlink of the bare name, so that
2408 # the other user needs no access to the directories above. Both
2409 # are restored before it returns.
2410 # Entry: $path; $as - a uid to act as, or undef.
2411 # Exit: (1, 0) or (0, errno). Throws only if it cannot change
2412 # directory or effective uid, or cannot change back.
2413 102 ▶sub _try_unlink {
Subroutine _try_unlink: called CC=7 SCAR=19.5
2414 102 my ($path, $as) = @_;
2415 17 ▶ no autodie;
Subroutine BEGIN: called CC=1 SCAR=0.0
2416  
2417 102 ▶ if(!defined $as) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $as) 94 8 102
2418 94 ▶ return unlink($path) ? (1, 0) : (0, 0 + $!);
Branch: 1 branch
BranchTrueFalseTotal
unlink($path) ? : 62 32 94
2419 }
2420  
2421 8 my ($volume, $directories, $name) = File::Spec->splitpath($path);
2422 8 my $dir = File::Spec->catpath($volume, $directories, q{});
2423 8 my $cwd = _untaint(Cwd::getcwd());
2424 8 ▶ chdir $dir or die "chdir $dir: $!\n"; ## no critic (ErrorHandling::RequireCarping)
Branch: 1 branch
BranchTrueFalseTotal
chdir $dir or die "chdir ${dir}: $!\n" 6 2 8
2425  
2426 6 my ($switched, $ok, $errno) = _unlink_as($name, $as);
2427 6 ▶ chdir $cwd or die "chdir $cwd: $!\n"; ## no critic (ErrorHandling::RequireCarping)
Branch: 1 branch
BranchTrueFalseTotal
chdir $cwd or die "chdir ${cwd}: $!\n" 5 1 6
2428 5 ▶ die "cannot act as uid $as\n" unless $switched; ## no critic (ErrorHandling::RequireCarping)
Branch: 1 branch
BranchTrueFalseTotal
unless $switched 3 2 5
2429 2 ▶ return $ok ? (1, 0) : (0, $errno);
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 1 1 2
2430 }
2431  
2432 # _unlink_as
2433 #
2434 # Purpose: The privileged core of _try_unlink: set the effective uid,
2435 # unlink a name in the current directory, and set it back.
2436 # Kept this small because only real root can run it: tests mock
2437 # it to reach every other path of _try_unlink.
2438 # Entry: $name - a file name in the current directory; $uid.
2439 # Exit: ($switched, $ok, $errno): whether the effective uid could be
2440 # changed, and if so whether unlink worked and its errno.
2441 4 ▶sub _unlink_as {
Subroutine _unlink_as: called CC=2 SCAR=6.9
2442 4 my ($name, $uid) = @_;
2443 17 ▶ no autodie;
Subroutine BEGIN: called CC=1 SCAR=0.0
2444 4 local $> = $uid;
2445 4 ▶ return (0) unless $> == $uid;
Branch: 1 branch
BranchTrueFalseTotal
unless $> == $uid 3 1 4
2446 1 my $ok = unlink $name;
2447 1 return (1, $ok, 0 + $!);
2448 }
2449  
2450 # _can_switch_uid
2451 #
2452 # Purpose: The sticky probe's precondition: can this process act as
2453 # another user? Only root (real and effective) outside Windows.
2454 # Entry: None.
2455 # Exit: 1 or 0.
2456 23 ▶sub _can_switch_uid {
Subroutine _can_switch_uid: called CC=4 SCAR=13.9
2457 23 my ($ruid, $euid) = _uids();
2458 23 ▶ return $^O ne 'MSWin32' && $ruid == $ROOT_UID && $euid == $ROOT_UID ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$^O ne 'MSWin32' && $ruid == $ROOT_UID && $euid == $ROOT_UID ? : 1 22 23
Condition83%5/6
$^O ne "MSWin32" and $ruid == $ROOT_UID and $euid == $ROOT_UID
!ll&&!rl&&r
2111
$^O ne "MSWin32" and $ruid == $ROOT_UID
!ll&&!rl&&r
0212
MC/DC66%2/3
$^O ne "MSWin32" and $ruid == $ROOT_UID and $euid == $ROOT_UID
$^O ne "MSWin32" $ruid == $ROOT_UID $euid == $ROOT_UID
Truth table75%3/4
A and B and C
A= $^O ne "MSWin32"B= $ruid == $ROOT_UIDC= $euid == $ROOT_UID
ABCresult
0XX0
10X0
1100
1111
2459 }
2460  
2461 # _uids
2462 #
2463 # Purpose: The real and effective uid, through a seam, so that tests can
2464 # exercise the root branches without being root.
2465 # Entry: None.
2466 # Exit: ($<, $>).
2467 42 ▶sub _uids {
Subroutine _uids: called CC=1 SCAR=0.0
2468 42 return ($<, $>);
2469 }
2470  
2471 # _give_away
2472 #
2473 # Purpose: Give a file to another user (sticky setup). autodie.
2474 # Entry: $path; $uid.
2475 # Exit: Nothing. Throws on failure.
2476 2 ▶sub _give_away {
Subroutine _give_away: called CC=1 SCAR=0.0
2477 2 my ($path, $uid) = @_;
2478 2 chown $uid, -1, $path;
2479 1 return;
2480 }
2481  
2482 # _access
2483 #
2484 # Purpose: What the system says about $kind access to $path for this
2485 # process, using access(2), which takes ACLs into account
2486 # (acl_denies).
2487 # Entry: $kind - read, write or exec; $path.
2488 # Exit: 1 or 0.
2489 12 ▶sub _access {
Subroutine _access: called CC=4 SCAR=13.9
2490 12 my ($kind, $path) = @_;
2491 17 ▶ use filetest 'access';
Subroutine BEGIN: called CC=1 SCAR=0.0
2492 12 ▶ return ($kind eq 'read' ? -r $path : $kind eq 'write' ? -w $path : -x $path) ? 1 : 0;
Branch: 3 branches
BranchTrueFalseTotal
($kind eq 'read' ? -r $path : ($kind eq 'write' ? -w $path : -x $path)) ? : 11 1 12
$kind eq 'read' ? : 6 6 12
$kind eq 'write' ? : 4 2 6
2493 }
2494  
2495 # _set_mode
2496 #
2497 # Purpose: chmod one path.
2498 # Entry: $path; $mode.
2499 # Exit: 1. Throws (autodie) on failure.
2500 2350 ▶sub _set_mode {
Subroutine _set_mode: called CC=1 SCAR=0.0
2501 2350 my ($path, $mode) = @_;
2502 2350 chmod $mode, $path;
2503 2346 return 1;
2504 }
2505  
2506 # _mode_of
2507 #
2508 # Purpose: The permission bits of a path.
2509 # Entry: $path.
2510 # Exit: mode & 07777, or undef if stat fails ($! says why).
2511 239 ▶sub _mode_of {
Subroutine _mode_of: called CC=2 SCAR=6.9
2512 239 my ($path) = @_;
2513 239 my @stat = stat $path;
2514 239 ▶ return @stat ? $stat[$STAT_MODE] & $MODE_BITS : undef;
Branch: 1 branch
BranchTrueFalseTotal
@stat ? : 238 1 239
2515 }
2516  
2517 =head1 FAILURE POLICY
2518  
2519 =over 4
2520  
2521 =item * B<Caller errors croak>: an unknown kind, a C<dir> that is not an
2522 existing directory, a C<path> that does not exist, bad arguments
2523 (reported by Params::Validate::Strict or Params::Get), or an unknown
2524 message key. C<with_revoked> also croaks if it cannot change or restore
2525 the mode it was asked to change.
2526  
2527 =item * B<Probe errors never escape.> Anything that goes wrong inside a
2528 probe becomes a 0 answer with a reason. A helper whose job is to decide
2529 whether to skip must never be the thing that fails your test file.
2530  
2531 =item * B<No warnings.> Many suites run under L<Test::Warnings> or C<-W>,
2532 so a warning would itself fail them. Use L</why_not(kind, dir)> for
2533 diagnostics.
2534  
2535 =item * A failed restore or cleanup makes the answer 0, and is added to
2536 the reason (C<reason_cleanup_failed>).
2537  
2538 =back
2539  
2540 =head1 LIMITATIONS
2541  
2542 =over 4
2543  
2544 =item * Results are per directory (or per device, see
2545 L</set_cache_scope(scope)>), per effective user and groups, and per
2546 process.
2547  
2548 =item * A directory whose permissions or mount change after the first
2549 call keeps its cached answer until L</clear_cache()>.
2550  
2551 =item * Probing needs write access to C<dir>: the probe creates a scratch
2552 directory there. Without it the answer is 0 (C<reason_setup_failed>).
2553  
2554 =item * The probes change only mode bits. L</acl_denies(kind, path)>
2555 detects an ACL that denies access to an existing path, but no probe
2556 creates ACLs.
2557  
2558 =item * The mode check after C<chmod> compares the owner's permission
2559 bits (all bits for C<sticky>), because the probe runs as the owner of its
2560 scratch files, and because perl on Windows reports a read-only file as
2561 0444.
2562  
2563 =item * The C<sticky> probe needs root, and assumes that uids 65533 and
2564 65534 can own files. In a user namespace that maps only one uid (such as
2565 C<unshare -r>), giving the file away fails and the answer is 0 with
2566 C<reason_setup_failed>.
2567  
2568 =item * Reasons embed the system's error text in the current locale.
2569  
2570 =item * Needs perl 5.26 or later, because Params::Validate::Strict does.
2571  
2572 =back
2573  
2574 =head1 SEE ALSO
2575  
2576 L<Test::More>, L<Test2::V0>, L<Test::Warnings>, L<File::Temp>,
2577 L<filetest>.
2578  
2579 =head1 SUPPORT
2580  
2581 This module is provided as-is without any warranty.
2582  
2583 Please report bugs and feature requests at
2584 L<https://github.com/nigelhorne/Test-Permissions/issues>.
2585  
2586 =head1 AUTHOR
2587  
2588 Nigel Horne E<lt>njh@nigelhorne.comE<gt>
2589  
2590 =head1 STATE DIAGRAM
2591  
2592 The cache, for one key: a kind, the effective uid and groups, and the
2593 canonical directory (or, with the C<device> scope, its device).
2594 C<can_revoke>, C<can_revoke_*>, C<why_not>, C<skip_unless_can_revoke> and
2595 C<permissions_report> are all "queries". A call that croaks does not
2596 change the state.
2597  
2598 query: probe, answer 1
2599 +---------+ ---------------------------> +------------+
2600 | EMPTY | | CACHED_YES | --+ query: no probe
2601 +---------+ ---------------------------> +------------+ <-+
2602 ^ ^ ^ query: probe, answer 0 |
2603 | | | |
2604 | | +------------- clear_cache ------------+
2605 | | +-----------+
2606 | +-------------- clear_cache ---------- | CACHED_NO | --+ query: no probe
2607 | +-----------+ <-+
2608 +-- clear_cache (from EMPTY: no change)
2609  
2610 There is no edge between CACHED_YES and CACHED_NO: a cached answer stays
2611 until C<clear_cache>, even if the environment changes. C<set_messages>
2612 changes no state; a cached reason keeps the wording it was given when the
2613 probe ran. C<set_cache_scope> and a change of effective uid or groups do
2614 not change any key's state; they change which key later queries use.
2615  
2616 =encoding utf-8
2617  
2618 =head1 FORMAL SPECIFICATION
2619  
2620 The specification below uses Z notation. The English sections above are
2621 the normative description for everyday use.
2622  
2623 [PATH, ERRNO, CHAR, UID, GID, DEV]
2624 Kind ::= read | write | create | search | exec | delete | sticky
2625 Answer == { 0, 1 }
2626 DENIED == { EACCES, EPERM }
2627 Reason == seq₁ CHAR
2628 Scope ::= directory | device
2629  
2630 -- Outcome of one probe step.
2631 Outcome ::= ok | failed⟨⟨ERRNO⟩⟩ | threw
2632  
2633 restricted : Kind → ℕ
2634 restricted = { read ↦ 0, write ↦ 0400, create ↦ 0500, search ↦ 0,
2635 exec ↦ 0600, delete ↦ 0500, sticky ↦ 01777 }
2636 bits : Kind → ℕ
2637 bits = (λ k : Kind • 0700) ⊕ { sticky ↦ 07777 }
2638  
2639 Env ≙ [ ruid, euid : UID; egids : 𝔽 GID; windows : 𝔹 ]
2640 precondition : Kind × Env → 𝔹
2641 precondition(k, e) ⇔ k ≠ sticky ∨ (e.ruid = 0 ∧ e.euid = 0 ∧ ¬ e.windows)
2642  
2643 Probe
2644 kind? : Kind
2645 dir? : PATH
2646 env : Env
2647 setup, baseline, attempt, cleanup : Outcome
2648 gotMode : ℕ
2649 modeSet : 𝔹
2650 answer! : Answer
2651 reason! : Reason ∪ {⊥}
2652 ---------------------------------------------
2653 modeSet ⇔ gotMode ∧ bits(kind?) = restricted(kind?) ∧ bits(kind?)
2654 answer! = 1 ⇔ precondition(kind?, env)
2655 ∧ setup = ok ∧ baseline = ok ∧ modeSet
2656 ∧ (∃ e : DENIED • attempt = failed(e))
2657 ∧ cleanup = ok
2658 answer! = 1 ⇔ reason! = ⊥
2659  
2660 Key == Kind × UID × 𝔽 GID × (PATH ∪ DEV)
2661 Cache == Key ⇸ Answer × (Reason ∪ {⊥})
2662 scope : Scope
2663  
2664 key : Kind × Env × PATH → Key
2665 key(k, e, p) = (k, e.euid, e.egids, if scope = device then dev(p) else canon(p))
2666  
2667 CanRevoke
2668 ΔCache ; Probe
2669 ---------------------------------------------
2670 key(kind?, env, dir?) ∈ dom cache ⇒ cache' = cache
2671 ∧ answer! = first(cache key(kind?, env, dir?))
2672 key(kind?, env, dir?) ∉ dom cache ⇒ cache' = cache ∪ { key(kind?, env, dir?) ↦ (answer!, reason!) }
2673  
2674 WhyNot
2675 ΞCache after CanRevoke
2676 why! : Reason ∪ {⊥}
2677 ---------------------------------------------
2678 why! = second(cache key(kind?, env, dir?))
2679  
2680 SkipUnlessCanRevoke
2681 CanRevoke
2682 count? : ℕ₁
2683 skipped! : ℕ
2684 ---------------------------------------------
2685 answer! = 1 ⇒ skipped! = 0 ∧ the SKIP block continues
2686 answer! = 0 ⇒ skipped! = count? ∧ the SKIP block is left,
2687 each skip carrying second(cache key(kind?, env, dir?))
2688  
2689 ClearCache
2690 ΔCache
2691 ---------------------------------------------
2692 cache' = ∅
2693  
2694 SetCacheScope
2695 ΞCache
2696 scope?, scope, scope' : Scope
2697 ---------------------------------------------
2698 scope' = scope?
2699  
2700 SetMessages
2701 texts, texts' : KEY ⇸ seq₁ CHAR
2702 overrides? : KEY ⇸ seq CHAR
2703 ---------------------------------------------
2704 (dom overrides? ⊆ dom DEFAULTS ∧ ⊥ ∉ ran overrides? ∧ ⟨⟩ ∉ ran overrides?)
2705 ⇒ texts' = texts ⊕ overrides?
2706 ¬ (...) ⇒ texts' = texts ∧ croak
2707  
2708 AclDenies
2709 kind? : { read, write, exec }
2710 path? : PATH
2711 denied! : Answer
2712 ---------------------------------------------
2713 denied! = 1 ⇔ modeAllows(kind?, stat(path?), env) ∧ ¬ access(kind?, path?)
2714  
2715 WithRevoked
2716 kind? : Kind \ { sticky }
2717 path? : PATH
2718 code? : ⊤ → ⊤
2719 ---------------------------------------------
2720 mode'(path?) = mode(path?) -- restored, even if code? dies
2721 during code? : mode(path?) = restricted(kind?)
2722 result! = code?() ∨ code?'s exception, unchanged
2723  
2724 -- Invariant: a probe leaves the target directory as it found it.
2725 entries'(dir?) = entries(dir?)
2726  
2727 =head1 LICENSE AND COPYRIGHT
2728  
2729 Copyright 2026 Nigel Horne.
2730  
2731 Usage is subject to the GPL2 licence terms.
2732 If you use it,
2733 please let me know.
2734  
2735 =cut
2736  
2737 17 1;
↑ Summary