lib/Mogura/Scanner/Scan.pm

filter: Statementstmt 93.8% 305 / 325 Branchbran 77.0% 111 / 144 Conditioncond 63.3% 45 / 71 MC/DCmcdc 37.5% 15 / 40 Subroutinesub 96.9% 32 / 33 Podpod 0.0% 0 / 12 totaltotal 81.2% 508 / 625 CC 107 SCAR 23.4
CC
107
Cov
85%
bounded_report
29.7
run
18.1
inspect_root
17.1
CRAP 10.4
« lib/Mogura/Scanner/Command.pm ↑ Summary lib/Mogura/Server.pm »
1 package Mogura::Scanner::Scan;
2 4 ▶use Mojo::Base -base;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 4 ▶use Mojo::File qw(path);
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use Mojo::JSON qw(decode_json to_json encode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use Digest::SHA;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 4 ▶use Fcntl qw(:flock F_SETFD);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 4 ▶use Mogura::Scanner::Command;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use Mogura::Protocol qw(now valid_id);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 ▶use Mogura::ResultStream;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 4 has [qw(config store disk)];
12 4 has cache_slot => 1;
13 0 ▶has command => sub { Mogura::Scanner::Command->new };
Subroutine __ANON__: not called CC=1 SCAR=1.2
14  
15 52 ▶sub validate_request {
Subroutine validate_request: called CC=5 SCAR=17.5
Pod undocumented
16 52 my ($self, $request) = @_;
17  
18 52 ▶ die 'Invalid scan request' unless ref $request eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $request eq "HASH" 0 52 52
19 52 ▶ die 'Invalid scan request' unless valid_id($request->{id});
Branch: 1 branch
BranchTrueFalseTotal
unless valid_id($request->{"id"}) 0 52 52
20 52 ▶ die 'Invalid scan request' unless ($request->{token} // '') =~ /\A[0-9a-f]{64}\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless ($request->{"token"} // "") =~ /\A[0-9a-f]{64}\z/u 0 52 52
Condition50%1/2
$request->{"token"} // ""
l!l
520
MC/DC0%0/1
$request->{"token"} // ""
$request->{"token"}
Truth table50%1/2
A
A= $request->{"token"}
Aresult
11
00
21  
22 52 return {id => $request->{id}, token => $request->{token}};
23 }
24  
25 24 ▶sub queued {
Subroutine queued: called CC=1 SCAR=0.0
Pod undocumented
26 24 my ($self, $request) = @_;
27 24 $request = $self->validate_request($request);
28 return {
29 24 %$request,
30 created_at => now(),
31 status => 'queued',
32 phase => 'queued',
33 cleanup_status => 'not_needed',
34 warnings => []
35 };
36 }
37  
38 101 ▶sub phase {
Subroutine phase: called CC=1 SCAR=0.0
Pod undocumented
39 101 my ($self, $scan, $phase) = @_;
40 101 $scan->{phase} = $phase;
41 101 $self->store->save($scan);
42 101 $self->store->log($scan->{id}, "Phase: $phase");
43 }
44  
45 # Resolve guest symlinks inside the guest root, including absolute /usr links.
46 # Host readlink/abs_path alone would follow an absolute link into the scanner OS.
47 151 ▶sub guest_path {
Subroutine guest_path: called CC=9 SCAR=22.0
Pod undocumented
48 151 my ($self, $root, $relative) = @_;
49  
50 151 my @pending = split m{/+}, $relative;
51 151 my @components;
52 151 my $symlink_count = 0;
53 151 ▶ while (@pending) {
Branch: 1 branch
BranchTrueFalseTotal
if (@pending) 348 148 496
54 348 my $component = shift @pending;
55 348 ▶ next if $component eq '' || $component eq '.';
Branch: 1 branch
BranchTrueFalseTotal
if $component eq "" or $component eq "." 20 328 348
Condition66%2/3
$component eq "" or $component eq "."
l!l&&r!l&&!r
200328
MC/DC50%1/2
$component eq "" or $component eq "."
$component eq "" $component eq "."
Truth table66%2/3
A or B
A= $component eq ""B= $component eq "."
ABresult
1X1
011
000
56 328 ▶ if ($component eq '..') {
Branch: 1 branch
BranchTrueFalseTotal
if ($component eq "..") 2 326 328
57 2 pop @components;
58 2 next;
59 }
60  
61 326 my $candidate = path($root, @components, $component);
62 326 ▶ unless (-l $candidate) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-l $candidate) 201 125 326
63 201 push @components, $component;
64 201 next;
65 }
66  
67 125 $symlink_count++;
68 125 ▶ die 'Too many guest symlinks' if $symlink_count > 40;
Branch: 1 branch
BranchTrueFalseTotal
if $symlink_count > 40 3 122 125
69 122 my $link = readlink $candidate;
70 122 ▶ die 'Unreadable guest symlink' unless defined $link;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $link 0 122 122
71  
72 # Absolute links restart at the guest root; relative links retain the
73 # resolved guest directory. Neither case can escape through host /usr.
74 122 ▶ @components = () if $link =~ m{\A/};
Branch: 1 branch
BranchTrueFalseTotal
if $link =~ m[\A/]u 1 121 122
75 122 unshift @pending, split m{/+}, $link;
76 }
77 148 return path($root, @components);
78 }
79  
80 33 ▶sub inspect_root {
Subroutine inspect_root: called CC=17 SCAR=28.4
Pod undocumented
81 33 my ($self, $root, $excluded) = @_;
82  
83 33 my @warnings = (
84 'Only the selected root filesystem was inspected; separate /boot and EFI areas are excluded.',
85 'Detected files do not establish running software, completeness, or freedom from vulnerabilities.',
86 );
87 33 for my $directory (qw(etc usr var)) {
88 99 my $available = eval { -d $self->guest_path($root, $directory) };
89 99 ▶ push @warnings, "Uninspected directory: /$directory is missing or inaccessible."
Branch: 1 branch
BranchTrueFalseTotal
unless $available 4 95 99
90 unless $available;
91 }
92  
93 # fstab is evidence about scan scope, never a source of mount commands.
94 # Missing scope evidence must not discard software visible on this root.
95 33 my $contents = eval {
96 33 my $fstab = $self->guest_path($root, 'etc/fstab');
97 31 ▶ die 'missing, inaccessible, or too large' unless -f $fstab && -s $fstab < 1048576;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $fstab and -s $fstab < 1048576 3 28 31
Condition100%3/3
-f $fstab and -s $fstab < 1048576
!ll&&!rl&&r
2128
MC/DC100%2/2
-f $fstab and -s $fstab < 1048576
-f $fstab -s $fstab < 1048576
Truth table100%3/3
A and B
A= -f $fstabB= -s $fstab < 1048576
ABresult
0X0
100
111
98 28 $fstab->slurp;
99 };
100 33 ▶ unless (defined $contents) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $contents) 5 28 33
101 5 push @warnings,
102 'Cannot inspect /etc/fstab: missing, unreadable, or too large; separate filesystems may be uninspected.';
103 5 return \@warnings;
104 }
105 28 my $line_number = 0;
106 28 for my $line (split /\n/, $contents) {
107 47 $line_number++;
108 47 $line =~ s/#.*//;
109 47 ▶ next unless $line =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /\S/u 1 46 47
110 46 $line =~ s/^\s+//;
111 46 my @fields = split /\s+/, $line;
112 46 ▶ unless (@fields >= 4) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@fields >= 4) 1 45 46
113 1 push @warnings,
114 "Cannot inspect /etc/fstab line $line_number: unrecognizable entry; its filesystem may be uninspected.";
115 1 next;
116 }
117  
118 45 my ($mountpoint, $filesystem) = @fields[1, 2];
119 45 $mountpoint =~ s/\\([0-7]{3})/chr(oct($1))/ge;
120 45 ▶ next if $mountpoint eq '/' || $mountpoint eq '/boot' || $mountpoint eq '/boot/efi';
Branch: 1 branch
BranchTrueFalseTotal
if $mountpoint eq "/" or $mountpoint eq "/boot" or $mountpoint eq "/boot/efi" 26 19 45
Condition66%4/6
$mountpoint eq "/" or $mountpoint eq "/boot" or $mountpoint eq "/boot/efi"
l!l&&r!l&&!r
26019
$mountpoint eq "/" or $mountpoint eq "/boot"
l!l&&r!l&&!r
26019
MC/DC33%1/3
$mountpoint eq "/" or $mountpoint eq "/boot" or $mountpoint eq "/boot/efi"
$mountpoint eq "/" $mountpoint eq "/boot" $mountpoint eq "/boot/efi"
Truth table50%2/4
A or B or C
A= $mountpoint eq "/"B= $mountpoint eq "/boot"C= $mountpoint eq "/boot/efi"
ABCresult
1XX1
01X1
0011
0000
121 19 ▶ next if $filesystem eq 'swap';
Branch: 1 branch
BranchTrueFalseTotal
if $filesystem eq "swap" 0 19 19
122  
123 # Resolve components so /var/log/../lib still produces a scope warning.
124 19 my $resolved = eval { '' . $self->guest_path($root, $mountpoint) };
125 next if grep {
126 19 ▶ my $directory = '' . path($root, substr($_, 1));
Branch: 1 branch
BranchTrueFalseTotal
if grep {my $directory = '' . path($root, substr($_, 1)); defined $resolved and $resolved eq $directory || index($resolved, "$directory/") == 0;} @$excluded 4 15 19
127 44 ▶ defined($resolved) && ($resolved eq $directory || index($resolved, "$directory/") == 0)
Condition83%5/6
defined $resolved && ($resolved eq $directory || index($resolved, "$directory/") == 0)
!ll&&!rl&&r
0404
$resolved eq $directory or index($resolved, "$directory/") == 0
l!l&&r!l&&!r
3140
MC/DC66%2/3
defined $resolved && ($resolved eq $directory || index($resolved, "$directory/") == 0)
defined $resolved $resolved eq $directory index($resolved, "$directory/") == 0
Truth table75%3/4
A && B or C
A= defined $resolvedB= $resolved eq $directoryC= index($resolved, "$directory/") == 0
ABCresult
0XX0
1000
11X1
1011
128 } @$excluded;
129 15 ▶ next if $filesystem =~ /\A(?:
Branch: 1 branch
BranchTrueFalseTotal
if $filesystem =~ /\A(?: proc | sysfs | devtmpfs | devpts | tmpfs | cgroup2? | debugfs | securityfs | pstore | mqueue | hugetlbfs )\z/ux 0 15 15
130 proc | sysfs | devtmpfs | devpts | tmpfs | cgroup2? | debugfs |
131 securityfs | pstore | mqueue | hugetlbfs
132 )\z/x;
133 15 push @warnings,
134 "Uninspected separate filesystem: $mountpoint ($filesystem); fstab is never mounted; scanning only files available on the selected root.";
135 }
136 28 return \@warnings;
137 }
138  
139 35 ▶sub exclusions {
Subroutine exclusions: called CC=8 SCAR=21.2
Pod undocumented
140 35 my ($self, $root, $warnings) = @_;
141 35 my @paths;
142 my %seen;
143 PATH:
144 35 for my $path (@{$self->config->exclude_paths},
145 qw(/var/log /var/crash /var/lib/systemd/coredump))
146 {
147 127 ▶ next if $seen{$path}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$path}++ 1 126 127
148 126 my $directory = path($root);
149 126 for my $component (split m{/}, substr($path, 1)) {
150 244 $directory = $directory->child($component);
151 244 ▶ unless (lstat $directory) {
Branch: 1 branch
BranchTrueFalseTotal
unless (lstat $directory) 114 130 244
152 114 ▶ last if $!{ENOENT} || $!{ENOTDIR};
Branch: 1 branch
BranchTrueFalseTotal
if $!{"ENOENT"} or $!{"ENOTDIR"} 114 0 114
Condition33%1/3
$!{"ENOENT"} or $!{"ENOTDIR"}
l!l&&r!l&&!r
11400
MC/DC0%0/2
$!{"ENOENT"} or $!{"ENOTDIR"}
$!{"ENOENT"} $!{"ENOTDIR"}
Truth table33%1/3
A or B
A= $!{"ENOENT"}B= $!{"ENOTDIR"}
ABresult
1X1
011
000
153 0 push @$warnings, "Cannot verify exclusion $path at $directory: $!";
154 0 next PATH;
155 }
156 130 ▶ if (-l _) {
Branch: 1 branch
BranchTrueFalseTotal
if (-l _) 7 123 130
157 7 push @$warnings, "Skipped exclusion $path: $component is a symbolic link.";
158 7 next PATH;
159 }
160 }
161 119 push @paths, $path;
162 }
163 35 return \@paths;
164 }
165  
166 86 ▶sub syft_pattern {
Subroutine syft_pattern: called CC=1 SCAR=0.0
Pod undocumented
167 86 my ($path) = @_;
168 86 $path =~ s/([\\*?\[\]{}])/\\$1/g;
169 86 return ".$path";
170 }
171  
172 35 ▶sub publish {
Subroutine publish: called CC=5 SCAR=16.5
Pod undocumented
173 35 my ($self, $temporary, $final, $kind) = @_;
174 35 my $data = Mogura::ResultStream->valid_artifact($temporary, $kind);
175 34 ▶ $self->_verify_grype_database($data->{descriptor}{db}) if $kind eq 'grype';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "grype" 9 25 34
176 33 ▶ path($temporary)->open('<')->sync or die "Sync artifact: $!";
Branch: 1 branch
BranchTrueFalseTotal
path($temporary)->open("<")->sync or die "Sync artifact: $!" 33 0 33
177 33 ▶ chmod 0640, $temporary or die "chmod artifact: $!";
Branch: 1 branch
BranchTrueFalseTotal
chmod 0640, $temporary or die "chmod artifact: $!" 33 0 33
178 33 ▶ rename $temporary, $final or die "publish artifact: $!";
Branch: 1 branch
BranchTrueFalseTotal
rename $temporary, $final or die "publish artifact: $!" 33 0 33
179 33 return $data;
180 }
181  
182 26 ▶sub cleanup {
Subroutine cleanup: called CC=6 SCAR=18.0
Pod undocumented
183 26 my ($self, $scan, $target, $mountpoint) = @_;
184  
185 26 ▶ return 1 if $scan->{cleanup_status} eq 'not_needed';
Branch: 1 branch
BranchTrueFalseTotal
if $scan->{"cleanup_status"} eq "not_needed" 1 25 26
186 25 ▶ return 1 if $scan->{cleanup_status} eq 'unmounted';
Branch: 1 branch
BranchTrueFalseTotal
if $scan->{"cleanup_status"} eq "unmounted" 8 17 25
187  
188 # Even a full database/log filesystem must not prevent an unmount attempt.
189 17 my $phase_saved = eval {
190 17 $self->phase($scan, 'unmounting');
191 17 1;
192 };
193 0 ▶ push @{$scan->{warnings}}, "Could not persist cleanup phase: $@" unless $phase_saved;
Branch: 1 branch
BranchTrueFalseTotal
unless $phase_saved 0 17 17
194  
195 17 my $unmounted = eval {
196 17 $self->disk->unmount($target, $mountpoint);
197 15 1;
198 };
199 17 ▶ if ($unmounted) {
Branch: 1 branch
BranchTrueFalseTotal
if ($unmounted) { } 15 2 17
200 15 $scan->{cleanup_status} = 'unmounted';
201 15 ▶ rmdir $mountpoint if -d $mountpoint;
Branch: 1 branch
BranchTrueFalseTotal
if -d $mountpoint 15 0 15
202 }
203 else {
204 2 $scan->{cleanup_status} = 'needs_cleanup';
205 2 push @{$scan->{warnings}}, "Unmount failed: $@";
206 }
207 17 $self->store->save($scan);
208 17 return $unmounted;
209 }
210  
211 24 ▶sub run {
Subroutine run: called CC=18 SCAR=29.0
Pod undocumented
212 24 my ($self, $request) = @_;
213  
214 24 $request = $self->validate_request($request);
215  
216 # Descendants retain this lock if the supervisor exits during a command.
217 24 my $scan_lock = $self->_acquire_lock('scan-' . $request->{id});
218 24 my $scan = $self->_start_scan($request);
219 23 my $mountpoint = path($self->config->mounts, $scan->{id});
220 23 my $scan_root = $mountpoint;
221 23 my ($target, $error, $failed_phase);
222 23 local $self->{stop_requested} = 0;
223 23 my ($host_scan, $disk_lock);
224  
225 4 ▶ local $SIG{TERM} = local $SIG{INT} = local $SIG{HUP} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
226 4 $self->{stop_requested} = 1;
227 4 die "Scan interrupted by stop request\n";
228 23 };
229  
230 # Keep the success path in execution order. Every exception, including a
231 # stop request or command timeout, rejoins the same cleanup path below.
232 23 my $succeeded = eval {
233 23 $self->phase($scan, 'validating');
234 23 $target = $self->disk->resolve($request->{token});
235 22 ▶ $host_scan = ($target->{kind} // '') eq 'host';
Condition100%2/2
$target->{"kind"} // ""
l!l
517
MC/DC100%1/1
$target->{"kind"} // ""
$target->{"kind"}
Truth table100%2/2
A
A= $target->{"kind"}
Aresult
11
00
236 my $disk_key =
237 $host_scan
238 ? 'host'
239 22 ▶ : ($target->{identity}{disk}{'maj:min'} // $target->{identity}{disk}{name});
Branch: 1 branch
BranchTrueFalseTotal
$host_scan ? : 5 17 22
Condition33%1/3
$target->{"identity"}{"disk"}{"maj:min"} // $target->{"identity"}{"disk"}{"name"}
l!l&&r!l&&!r
0170
MC/DC0%0/2
$target->{"identity"}{"disk"}{"maj:min"} // $target->{"identity"}{"disk"}{"name"}
$target->{"identity"}{"disk"}{"maj:min"} $target->{"identity"}{"disk"}{"name"}
Truth table33%1/3
A // B
A= $target->{"identity"}{"disk"}{"maj:min"}B= $target->{"identity"}{"disk"}{"name"}
ABresult
1X1
011
000
240 22 $disk_lock = $self->_acquire_lock('disk-' . Digest::SHA::sha256_hex($disk_key));
241 22 $scan->{target} = $target->{identity};
242 22 $self->store->save($scan);
243  
244 22 ▶ if ($host_scan) {
Branch: 1 branch
BranchTrueFalseTotal
if ($host_scan) { } 5 17 22
245  
246 # The running root is read in place. Never change its block-device
247 # flags, remount it, or pass it through guest cleanup handling.
248 5 $scan_root = path('/');
249 5 push @{$scan->{warnings}},
250 'Live filesystem: files may change during scanning; this is not a snapshot.';
251 }
252 else {
253 17 $target = $self->disk->make_readonly($target);
254 16 $self->_mount_root($scan, $target, $mountpoint);
255 }
256  
257 20 my $paths = $self->exclusions($scan_root, $scan->{warnings});
258 20 ▶ if ($host_scan) {
Branch: 1 branch
BranchTrueFalseTotal
if ($host_scan) { } 5 15 20
259 5 my $host_paths = $self->disk->host_exclusions;
260 5 push @$paths, @$host_paths;
261 5 push @{$scan->{warnings}},
262 5 map { "Uninspected live filesystem path (excluded): $_" } @$host_paths;
263 }
264 else {
265 15 $self->phase($scan, 'inspecting');
266 15 push @{$scan->{warnings}}, @{$self->inspect_root($scan_root, $paths)};
267 }
268 20 ▶ die "Scan interrupted by stop request\n" if $self->{stop_requested};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"stop_requested"} 1 19 20
269 19 my %patterns = map { syft_pattern($_) => 1 } @$paths;
270 19 $scan->{exclusions} = [sort keys %patterns];
271 19 my ($tool_config, $command_options) = $self->_prepare_tools($scan);
272 19 $self->_generate_sboms($scan, $target, $scan_root, $tool_config, $command_options);
273  
274 # Grype reads only the saved SBOM. Release the disk before database
275 # downloads and matching, and never continue after an unmount failure.
276 12 ▶ die 'Unmount failed; vulnerability matching was not started'
Branch: 1 branch
BranchTrueFalseTotal
unless $host_scan or $self->cleanup($scan, $target, $mountpoint) 1 11 12
Condition100%3/3
$host_scan or $self->cleanup($scan, $target, $mountpoint)
l!l&&r!l&&!r
381
MC/DC100%2/2
$host_scan or $self->cleanup($scan, $target, $mountpoint)
$host_scan $self->cleanup($scan, $target, $mountpoint)
Truth table100%3/3
A or B
A= $host_scanB= $self->cleanup($scan, $target, $mountpoint)
ABresult
1X1
011
000
277 unless $host_scan || $self->cleanup($scan, $target, $mountpoint);
278 11 ▶ die "Scan interrupted by stop request\n" if $self->{stop_requested};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"stop_requested"} 0 11 11
279 11 $self->_match_vulnerabilities($scan, $tool_config, $command_options);
280 8 $scan->{status} = 'completed';
281 8 1;
282 };
283 23 ▶ unless ($succeeded) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($succeeded) 15 8 23
284 15 ▶ $error = $@ || 'Scan failed';
Condition50%1/2
$@ || 'Scan failed'
l!l
150
MC/DC0%0/1
$@ || 'Scan failed'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
285 15 $failed_phase = $scan->{phase};
286 }
287  
288 # Repeated stop requests must not interrupt the bounded unmount attempt.
289 23 local $SIG{TERM} = local $SIG{INT} = local $SIG{HUP} = 'IGNORE';
290 23 ▶ $self->_cleanup_after_scan($scan, $target, $mountpoint) if $target && !$host_scan;
Branch: 1 branch
BranchTrueFalseTotal
if $target and not $host_scan 17 6 23
Condition100%3/3
$target and not $host_scan
!ll&&!rl&&r
1517
MC/DC100%2/2
$target and not $host_scan
$target not $host_scan
Truth table100%3/3
A and not(B)
A= $targetB= not $host_scan
ABresult
0X0
100
111
291 23 ▶ $self->_record_failure($scan, $error, $failed_phase, $self->{stop_requested}) if $error;
Branch: 1 branch
BranchTrueFalseTotal
if $error 15 8 23
292  
293 23 ▶ if ($scan->{status} eq 'completed' && !$host_scan && $scan->{cleanup_status} ne 'unmounted') {
Branch: 1 branch
BranchTrueFalseTotal
if ($scan->{"status"} eq "completed" and not $host_scan and $scan->{"cleanup_status"} ne "unmounted") 0 23 23
Condition83%5/6
$scan->{"status"} eq "completed" and not $host_scan and $scan->{"cleanup_status"} ne "unmounted"
!ll&&!rl&&r
1760
$scan->{"status"} eq "completed" and not $host_scan
!ll&&!rl&&r
1526
MC/DC0%0/3
$scan->{"status"} eq "completed" and not $host_scan and $scan->{"cleanup_status"} ne "unmounted"
$scan->{"status"} eq "completed" not $host_scan $scan->{"cleanup_status"} ne "unmounted"
Truth table75%3/4
A and not(B) and C
A= $scan->{"status"} eq "completed"B= not $host_scanC= $scan->{"cleanup_status"} ne "unmounted"
ABCresult
0XX0
10X0
1100
1111
294 0 $scan->{status} = 'partial';
295 }
296 23 $self->_append_log_warnings($scan);
297 23 $scan->{finished_at} = now();
298 23 $scan->{phase} = 'finished';
299 23 return $self->save_finished($scan);
300 }
301  
302 27 ▶sub save_finished {
Subroutine save_finished: called CC=2 SCAR=7.0
Pod undocumented
303 27 my ($self, $scan) = @_;
304 27 my $report = bounded_report($scan);
305 27 ▶ $self->store->log($scan->{id}, to_json($scan)) if $report != $scan;
Branch: 1 branch
BranchTrueFalseTotal
if $report != $scan 0 27 27
306 27 return $self->store->save($report);
307 }
308  
309 28 ▶sub bounded_report {
Subroutine bounded_report: called CC=6 SCAR=33.9
Pod undocumented
310 28 my ($scan) = @_;
311 28 ▶ return $scan if length(encode_json($scan)) <= 196608;
Branch: 1 branch
BranchTrueFalseTotal
if length encode_json($scan) <= 196608 28 0 28
312  
313 # Full diagnostics are written to the downloadable log before final delivery.
314 my $report =
315 0 ▶ {map { $_ => substr($scan->{$_} // '', 0, 512) }
Condition0%0/2
$scan->{$_} // ""
l!l
00
MC/DC0%0/1
$scan->{$_} // ""
$scan->{$_}
Truth table0%0/2
A
A= $scan->{$_}
Aresult
11
00
316 qw(id token status phase started_at finished_at failed_phase cleanup_status error syft_version grype_version sbom_sha256)
317 };
318 0 ▶ $report->{sequence} = $scan->{sequence} // 0;
Condition0%0/2
$scan->{"sequence"} // 0
l!l
00
MC/DC0%0/1
$scan->{"sequence"} // 0
$scan->{"sequence"}
Truth table0%0/2
A
A= $scan->{"sequence"}
Aresult
11
00
319 0 ▶ my @warnings = @{$scan->{warnings} // []};
Condition0%0/2
$scan->{"warnings"} // []
l!l
00
MC/DC0%0/1
$scan->{"warnings"} // []
$scan->{"warnings"}
Truth table0%0/2
A
A= $scan->{"warnings"}
Aresult
11
00
320 0 ▶ splice @warnings, 20 if @warnings > 20;
Branch: 1 branch
BranchTrueFalseTotal
if @warnings > 20 0 0 0
321 0 $report->{warnings} = [map { substr($_, 0, 256) } @warnings];
322 0 push @{$report->{warnings}}, 'Large scan report: see the scan log for full diagnostics.';
323 0 return $report;
324 }
325  
326 86 ▶sub _acquire_lock {
Subroutine _acquire_lock: called CC=4 SCAR=14.0
327 86 my ($self, $name) = @_;
328 86 my $directory = path($self->config->runtime, 'locks')->make_path({mode => 0750});
329 86 ▶ open my $lock, '>>', $directory->child($name) or die "Scan lock: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $lock, ">>", $directory->child($name) or die "Scan lock: $!" 86 0 86
330 86 ▶ flock($lock, LOCK_EX | LOCK_NB) or die 'Scan or disk is already being processed';
Branch: 1 branch
BranchTrueFalseTotal
flock $lock, 6 or die "Scan or disk is already being processed" 85 1 86
331  
332 # Keep ownership if a scanner subprocess outlives its scan process.
333 85 ▶ fcntl($lock, F_SETFD, 0) or die "Preserve scan lock: $!";
Branch: 1 branch
BranchTrueFalseTotal
fcntl $lock, 2, 0 or die "Preserve scan lock: $!" 85 0 85
334 85 return $lock;
335 }
336  
337 24 ▶sub _start_scan {
Subroutine _start_scan: called CC=3 SCAR=11.0
338 24 my ($self, $request) = @_;
339  
340 24 ▶ my $scan = $self->store->get($request->{id}) // $self->queued($request);
Condition66%2/3
$self->store->get($request->{"id"}) // $self->queued($request)
l!l&&r!l&&!r
1230
MC/DC0%0/2
$self->store->get($request->{"id"}) // $self->queued($request)
$self->store->get($request->{"id"}) $self->queued($request)
Truth table66%2/3
A // B
A= $self->store->get($request->{"id"})B= $self->queued($request)
ABresult
1X1
011
000
341 24 ▶ die 'Scan has already been processed' unless $scan->{status} eq 'queued';
Branch: 1 branch
BranchTrueFalseTotal
unless $scan->{"status"} eq "queued" 1 23 24
342  
343 23 $scan->{status} = 'running';
344 23 $scan->{started_at} = now();
345 23 return $self->store->save($scan);
346 }
347  
348 16 ▶sub _mount_root {
Subroutine _mount_root: called CC=3 SCAR=11.6
349 16 my ($self, $scan, $target, $mountpoint) = @_;
350  
351 16 $mountpoint->make_path({mode => 0700});
352 16 for my $mount (@{$self->disk->mount_table}) {
353 0 ▶ die 'Mountpoint already in use' if $mount->{target} eq "$mountpoint";
Branch: 1 branch
BranchTrueFalseTotal
if $mount->{"target"} eq "$mountpoint" 0 0 0
354 }
355  
356 # Persist cleanup intent before mount: a command can create a mount and
357 # still fail or be interrupted before returning to this process.
358 16 $self->phase($scan, 'mounting');
359 16 $scan->{cleanup_status} = 'mounted';
360 16 $self->store->save($scan);
361 16 $self->disk->mount($target, $mountpoint);
362 }
363  
364 19 ▶sub _prepare_tools {
Subroutine _prepare_tools: called CC=1 SCAR=0.0
365 19 my ($self, $scan) = @_;
366  
367 # Explicit configuration and a private working directory prevent either
368 # CLI from discovering configuration inside the scanned filesystem.
369 19 my $directory = $self->store->directory($scan->{id});
370 19 my $work = $directory->child('work')->make_path({mode => 0700});
371 19 my $tool_config = $work->child('tools.yaml');
372 19 $tool_config->spurt("{}\n");
373  
374 19 my $options = {
375 cwd => "$work",
376 timeout => $self->config->command_timeout,
377 log => '' . $directory->child('scan.log'),
378 env => {
379 SYFT_CHECK_FOR_APP_UPDATE => 'false',
380 GRYPE_CHECK_FOR_APP_UPDATE => 'false',
381 GRYPE_DB_CACHE_DIR => $self->config->state . '/grype-db/slot-' . $self->cache_slot,
382 GRYPE_DB_VALIDATE_AGE => 'true',
383 GRYPE_DB_VALIDATE_BY_HASH_ON_START => 'true',
384 },
385 };
386 19 return ($tool_config, $options);
387 }
388  
389 18 ▶sub _record_tool_versions {
Subroutine _record_tool_versions: called CC=4 SCAR=13.9
390 18 my ($self, $scan, $options) = @_;
391  
392 # Version lookup is best effort; the generated documents also identify
393 # their producer, and a failed lookup must not discard usable SBOMs.
394 18 for my $tool (qw(syft grype)) {
395 35 my $version = eval {
396 35 my $json = $self->command->run([$self->config->$tool, 'version', '-o', 'json'],
397 %$options, timeout => 30,);
398 34 decode_json($json);
399 };
400 35 ▶ die "Scan interrupted by stop request\n" if $self->{stop_requested};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"stop_requested"} 1 34 35
401 34 ▶ $scan->{"${tool}_version"} = $version->{version} if ref $version eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $version eq "HASH" 34 0 34
402 }
403 }
404  
405 19 ▶sub _generate_sboms {
Subroutine _generate_sboms: called CC=12 SCAR=24.9
406 19 my ($self, $scan, $target, $scan_root, $tool_config, $options) = @_;
407  
408 19 $self->phase($scan, 'sbom');
409 19 ▶ $self->disk->verify_mount($target, $scan_root) unless ($target->{kind} // '') eq 'host';
Branch: 1 branch
BranchTrueFalseTotal
unless ($target->{"kind"} // "") eq "host" 14 5 19
Condition100%2/2
$target->{"kind"} // ""
l!l
514
MC/DC100%1/1
$target->{"kind"} // ""
$target->{"kind"}
Truth table100%2/2
A
A= $target->{"kind"}
Aresult
11
00
410 18 $self->_record_tool_versions($scan, $options);
411  
412 17 my $directory = $self->store->directory($scan->{id});
413 17 my $syft_output = $directory->child('sbom.syft.json.part');
414 17 my $cdx_output = $directory->child('sbom.cdx.json.part');
415 $self->command->run(
416 [
417 $self->config->syft,
418 'scan',
419 "dir:$scan_root",
420 '--config',
421 "$tool_config",
422 '-o',
423 "syft-json=$syft_output",
424 '-o',
425 "cyclonedx-json=$cdx_output",
426 78 ▶ (map { ('--exclude', $_) } @{$scan->{exclusions} // []}),
Branch: 1 branch
BranchTrueFalseTotal
($target->{'kind'} // '') eq 'host' ? : 5 12 17
Condition75%3/4
$scan->{"exclusions"} // []
l!l
170
$target->{"kind"} // ""
l!l
512
MC/DC0%0/1
$scan->{"exclusions"} // []
$scan->{"exclusions"}
MC/DC100%1/1
$target->{"kind"} // ""
$target->{"kind"}
Truth table50%1/2
A
A= $scan->{"exclusions"}
Aresult
11
00
Truth table100%2/2
A
A= $target->{"kind"}
Aresult
11
00
427 17 (($target->{kind} // '') eq 'host' ? ('--parallelism', '2') : ()),
428 ],
429 %$options
430 );
431  
432 # Publish each valid format independently. If the other output is invalid,
433 # the usable SBOM survives and the result is reported as partial.
434 13 my @outputs = (
435 [$syft_output, $directory->child('sbom.syft.json'), 'syft'],
436 [$cdx_output, $directory->child('sbom.cdx.json'), 'cdx'],
437 );
438 13 my @validation_errors;
439 13 for my $output (@outputs) {
440 26 my $valid = eval {
441 26 my $data = $self->publish(@$output);
442 25 ▶ $scan->{syft_version} = $data->{descriptor}{version} if $output->[2] eq 'syft';
Branch: 1 branch
BranchTrueFalseTotal
if $output->[2] eq "syft" 13 12 25
443 25 1;
444 };
445 26 ▶ push @validation_errors, $@ unless $valid;
Branch: 1 branch
BranchTrueFalseTotal
unless $valid 1 25 26
446 }
447 13 ▶ die join('', @validation_errors) if @validation_errors;
Branch: 1 branch
BranchTrueFalseTotal
if @validation_errors 1 12 13
448  
449 12 my $saved_sbom = $directory->child('sbom.syft.json');
450 12 ▶ open my $handle, '<:raw', $saved_sbom or die "SBOM hash: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $handle, "<:raw", $saved_sbom or die "SBOM hash: $!" 12 0 12
451 12 $scan->{sbom_sha256} = Digest::SHA->new(256)->addfile($handle)->hexdigest;
452 12 ▶ close $handle or die "Close SBOM: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $handle or die "Close SBOM: $!" 12 0 12
453  
454 }
455  
456 11 ▶sub _match_vulnerabilities {
Subroutine _match_vulnerabilities: called CC=1 SCAR=0.0
457 11 my ($self, $scan, $tool_config, $options) = @_;
458  
459 11 $self->phase($scan, 'vulnerabilities');
460 11 my $directory = $self->store->directory($scan->{id});
461 11 my $output = $directory->child('vulnerabilities.grype.json.part');
462 11 $self->command->run(
463 [
464 $self->config->grype, 'sbom:' . $directory->child('sbom.syft.json'),
465 '--config', "$tool_config", '-o', 'json',
466 ],
467 %$options,
468 stdout => "$output"
469 );
470  
471 9 my $grype = $self->publish($output, $directory->child('vulnerabilities.grype.json'), 'grype');
472 8 my $database = $grype->{descriptor}{db};
473  
474 8 $scan->{grype_version} = $grype->{descriptor}{version};
475 8 $scan->{grype_db} = $database;
476 }
477  
478 9 ▶sub _verify_grype_database {
Subroutine _verify_grype_database: called CC=10 SCAR=26.2
479 9 my ($self, $database) = @_;
480  
481 # Current Grype nests validation under status; older documents place the
482 # same metadata at the top level. Preserve the original document unchanged.
483 9 my $status = $database;
484 9 ▶ if (ref($database) eq 'HASH' && ref($database->{status}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $database eq "HASH" and ref $database->{"status"} eq "HASH") 9 0 9
Condition33%1/3
ref $database eq "HASH" and ref $database->{"status"} eq "HASH"
!ll&&!rl&&r
009
MC/DC0%0/2
ref $database eq "HASH" and ref $database->{"status"} eq "HASH"
ref $database eq "HASH" ref $database->{"status"} eq "HASH"
Truth table33%1/3
A and B
A= ref $database eq "HASH"B= ref $database->{"status"} eq "HASH"
ABresult
0X0
100
111
485 9 $status = $database->{status};
486 }
487  
488 9 my $error = 'Grype database identity or validation unavailable';
489 9 ▶ die $error unless ref $status eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $status eq "HASH" 0 9 9
490 9 ▶ die $error unless $status->{built} && defined($status->{schemaVersion});
Branch: 1 branch
BranchTrueFalseTotal
unless $status->{"built"} and defined $status->{"schemaVersion"} 0 9 9
Condition33%1/3
$status->{"built"} and defined $status->{"schemaVersion"}
!ll&&!rl&&r
009
MC/DC0%0/2
$status->{"built"} and defined $status->{"schemaVersion"}
$status->{"built"} defined $status->{"schemaVersion"}
Truth table33%1/3
A and B
A= $status->{"built"}B= defined $status->{"schemaVersion"}
ABresult
0X0
100
111
491 9 ▶ die $error if $status->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $status->{"error"} 0 9 9
492 9 ▶ die $error unless $status->{valid} || ($status->{status} // '') eq 'valid';
Branch: 1 branch
BranchTrueFalseTotal
unless $status->{"valid"} or ($status->{"status"} // "") eq "valid" 1 8 9
Condition60%3/5
$status->{"valid"} or ($status->{"status"} // "") eq "valid"
l!l&&r!l&&!r
801
$status->{"status"} // ""
l!l
01
MC/DC50%1/2
$status->{"valid"} or ($status->{"status"} // "") eq "valid"
$status->{"valid"} $status->{"status"}
Truth table66%2/3
A or B
A= $status->{"valid"}B= $status->{"status"}
ABresult
1X1
011
000
493 }
494  
495 17 ▶sub _cleanup_after_scan {
Subroutine _cleanup_after_scan: called CC=2 SCAR=8.1
496 17 my ($self, $scan, $target, $mountpoint) = @_;
497  
498 17 my $cleanup_checked = eval {
499 17 $self->cleanup($scan, $target, $mountpoint);
500 17 1;
501 };
502 17 ▶ return if $cleanup_checked;
Branch: 1 branch
BranchTrueFalseTotal
if $cleanup_checked 17 0 17
503  
504 0 $scan->{cleanup_status} = 'needs_cleanup';
505 0 push @{$scan->{warnings}}, "Cleanup could not be verified: $@";
506 }
507  
508 15 ▶sub _record_failure {
Subroutine _record_failure: called CC=4 SCAR=13.9
509 15 my ($self, $scan, $error, $failed_phase, $interrupted) = @_;
510  
511 15 $scan->{error} = "$error";
512 15 $scan->{failed_phase} = $failed_phase;
513  
514 # Processing outcome and cleanup safety are independent: retaining a valid
515 # SBOM makes a failure partial, but never makes a remaining mount safe.
516 15 ▶ if ($interrupted) {
Branch: 2 branches
BranchTrueFalseTotal
if ($interrupted) { } 4 11 15
elsif ($self->store->artifact($scan->{'id'}, 'syft') or $self->store->artifact($scan->{'id'}, 'cdx')) { } 5 6 11
517 4 $scan->{status} = 'interrupted';
518 }
519 ▶ elsif ($self->store->artifact($scan->{id}, 'syft')
Condition66%2/3
$self->store->artifact($scan->{"id"}, "syft") or $self->store->artifact($scan->{"id"}, "cdx")
l!l&&r!l&&!r
506
MC/DC50%1/2
$self->store->artifact($scan->{"id"}, "syft") or $self->store->artifact($scan->{"id"}, "cdx")
$self->store->artifact($scan->{"id"}, "syft") $self->store->artifact($scan->{"id"}, "cdx")
Truth table66%2/3
A or B
A= $self->store->artifact($scan->{"id"}, "syft")B= $self->store->artifact($scan->{"id"}, "cdx")
ABresult
1X1
011
000
520 || $self->store->artifact($scan->{id}, 'cdx'))
521 {
522 5 $scan->{status} = 'partial';
523 }
524 else {
525 6 $scan->{status} = 'failed';
526 }
527 15 $self->store->log($scan->{id}, $error);
528 }
529  
530 23 ▶sub _append_log_warnings {
Subroutine _append_log_warnings: called CC=6 SCAR=18.1
531 23 my ($self, $scan) = @_;
532  
533 23 my $file = $self->store->artifact($scan->{id}, 'log');
534 23 ▶ return unless $file;
Branch: 1 branch
BranchTrueFalseTotal
unless $file 0 23 23
535  
536 23 ▶ open my $handle, '<:encoding(UTF-8)', $file or die "Log warnings: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $handle, "<:encoding(UTF-8)", $file or die "Log warnings: $!" 23 0 23
537 23 my @warnings;
538 23 ▶ while (my $line = <$handle>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $handle)) 131 23 154
539 131 ▶ next unless $line =~ m{\b(?:WARN(?:ING)?|ERROR|permission denied|input/output error)\b}i;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ m[\b(?:WARN(?:ING)?|ERROR|permission denied|input/output error)\b]iu 130 1 131
540 1 chomp $line;
541 1 push @warnings, substr($line, 0, 1000);
542 1 ▶ last if @warnings >= 20;
Branch: 1 branch
BranchTrueFalseTotal
if @warnings >= 20 0 1 1
543 }
544 23 push @{$scan->{warnings}}, @warnings;
545 }
546  
547 4 1;
« lib/Mogura/Scanner/Command.pm ↑ Summary lib/Mogura/Server.pm »