blib/lib/Test/CPAN/Health/Check/SecurityAdvisories.pm

filter: Statementstmt 100% 9 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 100% 12 / 12 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/Test/CPAN/Health/Check/ReverseDeps.pm ↑ Summary blib/lib/Test/CPAN/Health/Check/SemVer.pm »
1 package Test::CPAN::Health::Check::SecurityAdvisories;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 use Carp qw(croak carp);
8 use Readonly;
9 use Params::Validate::Strict qw(validate_strict);
10  
11 use parent 'Test::CPAN::Health::Check';
12  
13 our $VERSION = '0.1.0';
14  
15 # Weight is high because a known CVE is an objective, concrete risk.
16 # The Report applies a hard cap of 60 on the overall score when this fails.
17 Readonly::Scalar my $WEIGHT => 10;
18 Readonly::Scalar my $CVSS_CRITICAL => 9.0;
19 Readonly::Scalar my $CVSS_HIGH => 7.0;
20 Readonly::Scalar my $CVSS_MEDIUM => 4.0;
21  
22 =head1 NAME
23  
24 Test::CPAN::Health::Check::SecurityAdvisories - Check for known CVEs in the distribution and its dependencies
25  
26 =head1 SYNOPSIS
27  
28 use Test::CPAN::Health::Check::SecurityAdvisories;
29  
30 my $check = Test::CPAN::Health::Check::SecurityAdvisories->new;
31 my $result = $check->run($dist);
32  
33 =head1 DESCRIPTION
34  
35 Consults the L<CPAN::Audit> advisory database to check whether the
36 distribution under analysis, or any of its declared runtime or test
37 dependencies, have known CVEs or security advisories.
38  
39 The L<CPAN::Audit> database is bundled with the module and does not require
40 a network connection during the check itself. An optional call to
41 C<cpan-audit update> (or the equivalent) can refresh the database from the
42 CPAN Security Group's upstream advisory repository.
43  
44 Scoring:
45  
46 =over 4
47  
48 =item * 100 -- no advisories found in distribution or any dependency.
49  
50 =item * 50 -- advisories found only in indirect/test dependencies.
51  
52 =item * 0 -- advisories found in the distribution itself or a direct
53 runtime dependency. The Report hard-caps the overall score at 60.
54  
55 =back
56  
57 The C<ReverseDeps> context value (populated by an earlier check) is used
58 to scale the urgency message: a distribution with many downstream users
59 carries a higher implicit risk.
60  
61 =head1 LIMITATIONS
62  
63 =over 4
64  
65 =item * C<CPAN::Audit> only covers advisories that have been submitted to
66 the CPAN Security Advisory database. Not all CVEs are catalogued there.
67  
68 =item * Version range matching follows L<CPAN::Audit>'s own logic; unusually
69 formatted version strings may produce false negatives.
70  
71 =item * This check is skipped when C<no_network> is set B<and> the local
72 advisory database is absent (i.e. C<CPAN::Audit> is not installed).
73  
74 =back
75  
76 =cut
77  
78 sub id { return 'security_advisories' }
79 sub name { return 'Security Advisories' }
80 sub description { return 'Checks for known CVEs in the distribution and its dependencies' }
81 sub weight { return $WEIGHT }
82 sub category { return 'security' }
83  
84 =head2 run
85  
86 =head3 PURPOSE
87  
88 Scan the distribution and its full dependency tree against the CPAN::Audit
89 advisory database. Classify findings by severity and affected dep type
90 (self / direct runtime / test / indirect).
91  
92 =head3 API SPECIFICATION
93  
94 =head4 INPUT
95  
96 dist Test::CPAN::Health::Distribution required
97 context Hashref optional prior check results;
98 reads context->{reverse_deps}
99  
100 =head4 OUTPUT
101  
102 L<Test::CPAN::Health::Result> with:
103  
104 check_id 'security_advisories'
105 status 'pass' | 'fail' | 'skip' | 'error'
106 score 0 | 50 | 100
107 summary human-readable verdict
108 details list of "MODULE vVERSION: CVE-XXXX-YYYY (CVSS N.N)" strings
109 url link to CPAN Security Advisory page for the distribution
110  
111 =head3 MESSAGES
112  
113 Code | Severity | Message | Resolution
114 ------+----------+------------------------------------+---------------------
115 SEC01 | SKIP | CPAN::Audit not available | cpanm CPAN::Audit
116 SEC02 | PASS | No known advisories found |
117 SEC03 | FAIL | {n} advisories in dist/direct deps | Update affected modules
118 SEC04 | FAIL | {n} advisories in test/indirect | Update affected modules
119  
120 =head3 FORMAL SPECIFICATION
121  
122 -- Z schema (placeholder) --
123 SecurityAdvisoriesOp
124 dist : Distribution
125 advisories : seq Advisory
126 direct_hits : seq Advisory
127 indirect_hits: seq Advisory
128 score : {0, 50, 100}
129 status : {pass, fail, skip, error}
130 -------------------------------------------------------
131 advisories = CPAN::Audit.scan(dist.meta.prereqs)
132 direct_hits = {a : advisories | a.dep_type in {self, runtime}}
133 indirect_hits = advisories \ direct_hits
134 #direct_hits > 0 => status = fail /\ score = 0
135 #indirect_hits > 0 /\ #direct_hits = 0 => status = fail /\ score = 50
136 #advisories = 0 => status = pass /\ score = 100
137  
138 =head3 SIDE EFFECTS
139  
140 Reads the CPAN::Audit SQLite/JSON advisory database from disk.
141  
142 =head3 USAGE EXAMPLE
143  
144 my $result = $check->run($dist, \%context);
145  
146 =cut
147  
148 sub run {
149 my ($self, $dist, $context) = @_;
150  
151 croak 'dist must be a Test::CPAN::Health::Distribution'
152 unless ref($dist) && $dist->isa('Test::CPAN::Health::Distribution');
153  
154 $context //= {};
155  
156 # Strategy:
157 # 1. Verify CPAN::Audit is available; skip gracefully if not.
158 # 2. Extract prereqs from CPAN::Meta (runtime + test phases).
159 # 3. Instantiate CPAN::Audit and call audit_distributions() or
160 # equivalent to scan all name+version pairs.
161 # 4. Classify each finding as direct (self/runtime) or indirect
162 # (test/develop/indirect).
163 # 5. Score: any direct hit => 0; only indirect => 50; clean => 100.
164 # 6. Annotate each detail line with the CVE id and CVSS score.
165 # 7. Attach the MetaCPAN advisory URL for the distribution itself.
166  
167 my $loaded = eval { require CPAN::Audit; 1 };
168 unless ($loaded) {
169 return $self->_skip('CPAN::Audit is not installed (cpanm CPAN::Audit to enable this check)');
170 }
171  
172 my $meta = $dist->meta;
173 unless (defined $meta) {
174 return $self->_skip('No META file -- cannot determine dependency tree');
175 }
176  
177 my ($direct_advisories, $indirect_advisories) = $self->_scan_advisories($meta);
178  
179 my $reverse_dep_count = do {
180 my $rd = $context->{reverse_deps};
181 defined $rd ? ($rd->data->{count} // 0) : 0;
182 };
183  
184 if (@{$direct_advisories}) {
185 return $self->_result(
186 status => 'fail',
187 score => 0,
188 summary => sprintf(
189 '%d known advisor%s in %s or direct runtime dependencies%s',
190 scalar @{$direct_advisories},
191 @{$direct_advisories} == 1 ? 'y' : 'ies',
192 $dist->name,
193 $reverse_dep_count > 0
194 ? sprintf(' (%d downstream users affected)', $reverse_dep_count)
195 : '',
196 ),
197 details => [
198 (map { _format_advisory($_) } @{$direct_advisories}),
199 (map { _format_advisory($_) } @{$indirect_advisories}),
200 ],
201 url => _advisory_url($dist->name),
202 data => { name => $self->name, count => scalar(@{$direct_advisories}) + scalar(@{$indirect_advisories}) },
203 );
204 }
205  
206 if (@{$indirect_advisories}) {
207 return $self->_result(
208 status => 'fail',
209 score => 50,
210 summary => sprintf(
211 '%d known advisor%s in test or indirect dependencies',
212 scalar @{$indirect_advisories},
213 @{$indirect_advisories} == 1 ? 'y' : 'ies',
214 ),
215 details => [ map { _format_advisory($_) } @{$indirect_advisories} ],
216 url => _advisory_url($dist->name),
217 data => { name => $self->name, count => scalar @{$indirect_advisories} },
218 );
219 }
220  
221 return $self->_result(
222 status => 'pass',
223 score => 100,
224 summary => 'No known security advisories found',
225 data => { name => $self->name, count => 0 },
226 );
227 }
228  
229 # ---------------------------------------------------------------------------
230 # Private helpers
231 # ---------------------------------------------------------------------------
232  
233 # Scan all prereqs via CPAN::Audit.
234 # Returns two arrayrefs: (direct_advisories, indirect_advisories).
235 # Each advisory is a hashref: { module, version, cve, cvss, description }.
236 sub _scan_advisories {
237 my ($self, $meta) = @_;
238  
239 # Strategy:
240 # CPAN::Audit->new->audit() accepts a list of [Module, version] pairs
241 # and returns a data structure of findings.
242 # We separate runtime prereqs (direct) from test/develop (indirect).
243  
244 my @direct = ();
245 my @indirect = ();
246  
247 my $prereqs = $meta->effective_prereqs;
248  
249 # Collect direct runtime dependencies
250 my $runtime = $prereqs->requirements_for('runtime', 'requires');
251 my %direct_modules = map { $_ => $runtime->requirements_for_module($_) }
252 $runtime->required_modules;
253  
254 # Collect indirect (test + develop) dependencies
255 my %indirect_modules;
256 for my $phase (qw(test develop)) {
257 my $req = $prereqs->requirements_for($phase, 'requires');
258 for my $mod ($req->required_modules) {
259 next if $direct_modules{$mod}; # already counted as direct
260 $indirect_modules{$mod} = $req->requirements_for_module($mod);
261 }
262 }
263  
264 # advisories_for() is on CPAN::Audit::Query, not CPAN::Audit itself.
265 # Load the DB via CPANSA::DB (preferred) or the deprecated CPAN::Audit::DB.
266 my $db;
267 if (eval { require CPANSA::DB; 1 }) {
268 $db = CPANSA::DB->db;
269 } elsif (eval { require CPAN::Audit::DB; 1 }) {
270 $db = CPAN::Audit::DB->db;
271 } else {
272 $db = {};
273 }
274  
275 require CPAN::Audit::Query;
276 my $query = CPAN::Audit::Query->new(db => $db);
277  
278 # Scan direct dependencies
279 for my $mod (keys %direct_modules) {
280 my $ver = _effective_version($mod, $direct_modules{$mod});
281 next unless defined $ver;
282 my @findings = $query->advisories_for($mod, $ver);
283 push @direct, map { { module => $mod, version => $ver, %{$_} } } @findings;
284 }
285  
286 # Scan indirect dependencies
287 for my $mod (keys %indirect_modules) {
288 my $ver = _effective_version($mod, $indirect_modules{$mod});
289 next unless defined $ver;
290 my @findings = $query->advisories_for($mod, $ver);
291 push @indirect, map { { module => $mod, version => $ver, %{$_} } } @findings;
292 }
293  
294 return (\@direct, \@indirect);
295 }
296  
297 sub _format_advisory {
298 my ($adv) = @_;
299  
300 # CPAN::Audit::Query returns: id, description, cves (arrayref), severity,
301 # affected_versions, fixed_versions, references, distribution, reported.
302 my $id = $adv->{id} // 'ADVISORY';
303 my $cve = ref($adv->{cves}) && @{$adv->{cves}} ? $adv->{cves}[0] : undef;
304 my $label = $cve ? "$id ($cve)" : $id;
305 my $severity = defined $adv->{severity} ? sprintf(' [%s]', uc $adv->{severity}) : '';
306  
307 return sprintf('%s %s: %s%s -- %s',
308 $adv->{module},
309 $adv->{version} // '?',
310 $label,
311 $severity,
312 $adv->{description} // 'see advisory URL',
313 );
314 }
315  
316 # Return the version to pass to advisories_for().
317 #
318 # Two cases where the META-declared version is wrong to use:
319 #
320 # 1. 'perl' -- the declared minimum is a lower bound (e.g. 5.014), not the
321 # interpreter actually running. Scanning 5.014 floods results with CVEs
322 # fixed long ago. Use the running interpreter version instead.
323 #
324 # 2. Version '0' (no constraint) -- means "any version is acceptable", so
325 # advisories_for receives '0' and returns every advisory ever filed for the
326 # module. Instead load the module and read its actual VERSION; if it is not
327 # installed, return undef so the caller can skip it.
328 sub _effective_version {
329 my ($mod, $declared) = @_;
330  
331 return sprintf('%.6f', $]) if $mod eq 'perl';
332  
333 if (!defined $declared || $declared eq '0') {
334 return _installed_version($mod);
335 }
336  
337 return $declared;
338 }
339  
340 # Try to load a module and return its $VERSION string, or undef if not installed.
341 sub _installed_version {
342 my ($mod) = @_;
343 (my $file = "$mod.pm") =~ s{ :: }{/}gx;
344 my $ok = eval { require $file; 1 };
345 return $ok ? $mod->VERSION : undef;
346 }
347  
348 sub _advisory_url {
349 my ($dist_name) = @_;
350  
351 (my $slug = $dist_name) =~ s/ :: /-/gx;
352  
353 return "https://security.metacpan.org/advisories/$slug";
354 }
355  
356 =head1 AUTHOR
357  
358 Nigel Horne, C<< <njh at nigelhorne.com> >>
359  
360 =head1 LICENSE AND COPYRIGHT
361  
362 Copyright (C) 2025-2026 Nigel Horne.
363  
364 This program is free software; you can redistribute it and/or modify it
365 under the terms of the GNU General Public License as published by the Free
366 Software Foundation; either version 2 of the License, or (at your option)
367 any later version.
368  
369 =cut
370  
371 1;
« blib/lib/Test/CPAN/Health/Check/ReverseDeps.pm ↑ Summary blib/lib/Test/CPAN/Health/Check/SemVer.pm »