lib/GDPR/IAB/TCFv2/CMPValidator.pm

filter: Statementstmt 98.8% 86 / 87 Branchbran 86.0% 43 / 50 Conditioncond 77.7% 14 / 18 MC/DCmcdc 50.0% 6 / 12 Subroutinesub 100% 15 / 15 Podpod 100% 6 / 6 totaltotal 90.4% 170 / 188 CC 32 SCAR 15.3
CC
32
Cov
92%
_validate_http_options
8.0
new
7.0
load_from_data
5.0
CRAP 4.6
« blib/lib/GDPR/IAB/TCFv2/Parser.pm ↑ Summary blib/lib/GDPR/IAB/TCFv2/PublisherTC.pm »
1 package GDPR::IAB::TCFv2::CMPValidator 0.512;
2  
3 11 ▶use v5.12;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 11 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 11 ▶use Carp qw<croak carp>;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 11 ▶use Scalar::Util qw<blessed>;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # JSON::PP and Time::Piece are loaded lazily (see load_from_data and
10 # _parse_date). They are listed under META "recommends" rather than
11 # hard-required so the base parser doesn't pull them in for callers
12 # that never opt into CMPValidator. The HTTP::Tiny dependency is
13 # handled the same way in load_from_url.
14  
15 sub new {
16 31 ▶ my ($klass, %args) = @_;
Subroutine new: called CC=7 SCAR=19.5
Pod documented
17  
18 31 _validate_http_options(\%args);
19  
20 my $self = {
21 cmps => {},
22 last_updated => undef,
23 now => $args{now},
24 verify_ssl => exists $args{verify_ssl} ? $args{verify_ssl} : 1,
25 timeout => exists $args{timeout} ? $args{timeout} : 30,
26 http_client => $args{http_client},
27 26 ▶ };
Branch: 2 branches
BranchTrueFalseTotal
exists $args{'verify_ssl'} ? : 9 17 26
exists $args{'timeout'} ? : 10 16 26
28 26 bless $self, $klass;
29  
30 26 ▶ if (defined $args{file}) {
Branch: 3 branches
BranchTrueFalseTotal
if (defined $args{'file'}) { } 18 8 26
elsif (defined $args{'url'}) { } 5 3 8
elsif (defined $args{'data'}) { } 3 0 3
31 18 $self->load_from_file($args{file});
32 }
33 elsif (defined $args{url}) {
34  
35 # Network fetch is opt-in. A library that silently dials out
36 # over the network when handed an arbitrary URL is a footgun
37 # (proxy traversal, blocked egress, surprise latency, supply-
38 # chain risk). Force the caller to pass network_ok => 1 so the
39 # decision is intentional.
40 croak "CMPValidator: refusing to fetch '$args{url}' because "
41 . "network_ok was not set. Pass network_ok => 1 to enable "
42 . "URL loading, or use file => '...' / data => '...' instead."
43 5 ▶ unless $args{network_ok};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"network_ok"} 2 3 5
44  
45 3 $self->load_from_url($args{url});
46 }
47 elsif (defined $args{data}) {
48 3 $self->load_from_data($args{data});
49 }
50  
51 18 return $self;
52 }
53  
54 sub _validate_http_options {
55 31 ▶ my ($args) = @_;
Subroutine _validate_http_options: called CC=8 SCAR=20.8
56  
57 31 ▶ return unless exists $args->{http_client};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $args->{"http_client"} 24 7 31
58  
59 7 my $client = $args->{http_client};
60 7 ▶ croak "http_client must be a blessed object responding to ->get(\$url); got "
Branch: 2 branches
BranchTrueFalseTotal
unless builtin::blessed($client) and $client->can("get") 3 4 7
defined $client ? : 1 0 1
Condition83%5/6
builtin::blessed($client) and $client->can("get")
!ll&&!rl&&r
214
ref $client || (defined $client ? 'a non-reference' : 'undef')
l!l&&r!l&&!r
210
MC/DC100%2/2
builtin::blessed($client) and $client->can("get")
builtin::blessed($client) $client->can("get")
MC/DC0%0/2
ref $client || (defined $client ? 'a non-reference' : 'undef')
ref $client (defined $client ? 'a non-reference' : 'undef')
Truth table100%3/3
A and B
A= builtin::blessed($client)B= $client->can("get")
ABresult
0X0
100
111
Truth table66%2/3
A || B
A= ref $clientB= (defined $client ? 'a non-reference' : 'undef')
ABresult
1X1
011
000
61 . (ref($client) || (defined $client ? "a non-reference" : "undef"))
62 unless blessed($client) && $client->can('get');
63  
64 croak "http_client and verify_ssl/timeout are mutually exclusive: configure SSL/timeout on the http_client itself"
65 4 ▶ if exists $args->{verify_ssl} || exists $args->{timeout};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args->{"verify_ssl"} or exists $args->{"timeout"} 2 2 4
Condition100%3/3
exists $args->{"verify_ssl"} or exists $args->{"timeout"}
l!l&&r!l&&!r
112
MC/DC100%2/2
exists $args->{"verify_ssl"} or exists $args->{"timeout"}
exists $args->{"verify_ssl"} exists $args->{"timeout"}
Truth table100%3/3
A or B
A= exists $args->{"verify_ssl"}B= exists $args->{"timeout"}
ABresult
1X1
011
000
66  
67 2 return;
68 }
69  
70 sub load_from_file {
71 18 ▶ my ($self, $path) = @_;
Subroutine load_from_file: called CC=2 SCAR=6.9
Pod documented
72  
73 18 ▶ open my $fh, '<', $path or croak "Could not open CMP list file '$path': $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $path or croak("Could not open CMP list file '${path}': $!") 2 16 18
74 16 my $content = do { local $/ = undef; <$fh> };
75 16 close $fh;
76  
77 16 return $self->load_from_data($content);
78 }
79  
80 sub load_from_url {
81 3 ▶ my ($self, $url) = @_;
Subroutine load_from_url: called CC=4 SCAR=13.9
Pod documented
82  
83 3 my $client = $self->{http_client};
84 3 ▶ unless (defined $client) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $client) 1 2 3
85 1 ▶ eval { require HTTP::Tiny; 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require HTTP::Tiny; 1 } } or croak("HTTP::Tiny is required to load CMP list from URL. Please install it or use a local file instead.") 0 1 1
86 or croak "HTTP::Tiny is required to load CMP list from URL. " . "Please install it or use a local file instead.";
87  
88 # env_proxy => 1: honor https_proxy / http_proxy / no_proxy.
89 # verify_SSL => 1 (default): pin the secure default regardless
90 # of the installed HTTP::Tiny version (older versions defaulted
91 # to 0).
92 1 $client = HTTP::Tiny->new(env_proxy => 1, verify_SSL => $self->{verify_ssl}, timeout => $self->{timeout},);
93 }
94  
95 3 my $response = $client->get($url);
96 3 ▶ croak "Failed to fetch CMP list from '$url': $response->{reason}" unless $response->{success};
Branch: 1 branch
BranchTrueFalseTotal
unless $response->{"success"} 2 1 3
97  
98 1 return $self->load_from_data($response->{content});
99 }
100  
101 sub load_from_data {
102 20 ▶ my ($self, $json_text) = @_;
Subroutine load_from_data: called CC=5 SCAR=16.1
Pod documented
103  
104 20 ▶ eval { require JSON::PP; 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require JSON::PP; 1 } } or croak("JSON::PP is required to decode the CMP list. Please install it (it is core in Perl 5.14+).") 0 20 20
105 or croak "JSON::PP is required to decode the CMP list. " . "Please install it (it is core in Perl 5.14+).";
106  
107 20 my $data = eval { JSON::PP->new->utf8->decode($json_text) };
108 20 ▶ croak "Failed to decode CMP list JSON: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 19 20
109  
110 19 ▶ croak "Invalid CMP list format: missing 'cmps' key" unless ref $data eq 'HASH' && $data->{cmps};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" and $data->{"cmps"} 1 18 19
Condition66%2/3
ref $data eq "HASH" and $data->{"cmps"}
!ll&&!rl&&r
0118
MC/DC50%1/2
ref $data eq "HASH" and $data->{"cmps"}
ref $data eq "HASH" $data->{"cmps"}
Truth table66%2/3
A and B
A= ref $data eq "HASH"B= $data->{"cmps"}
ABresult
0X0
100
111
111  
112 18 $self->{cmps} = $data->{cmps};
113 18 $self->{last_updated} = $data->{lastUpdated};
114  
115 18 $self->_check_age();
116  
117 18 return $self;
118 }
119  
120 sub is_valid {
121 1045 ▶ my ($self, $cmp_id) = @_;
Subroutine is_valid: called CC=5 SCAR=16.1
Pod documented
122  
123 1045 my $cmp = $self->{cmps}->{$cmp_id};
124 1045 ▶ return 0 unless $cmp;
Branch: 1 branch
BranchTrueFalseTotal
unless $cmp 838 207 1045
125  
126 207 ▶ if ($cmp->{deletedDate}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cmp->{"deletedDate"}) 3 204 207
127 3 my $deleted = $self->_parse_date($cmp->{deletedDate});
128 3 ▶ return 0 if $deleted && $deleted <= $self->_now();
Branch: 1 branch
BranchTrueFalseTotal
if $deleted and $deleted <= $self->_now 2 1 3
Condition66%2/3
$deleted and $deleted <= $self->_now
!ll&&!rl&&r
012
MC/DC50%1/2
$deleted and $deleted <= $self->_now
$deleted $deleted <= $self->_now
Truth table66%2/3
A and B
A= $deletedB= $deleted <= $self->_now
ABresult
0X0
100
111
129 }
130  
131 205 return 1;
132 }
133  
134 sub last_updated_epoch {
135 18 ▶ my ($self) = @_;
Subroutine last_updated_epoch: called CC=2 SCAR=7.1
Pod documented
136 18 ▶ return unless $self->{last_updated};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"last_updated"} 0 18 18
137 18 return $self->_parse_date($self->{last_updated});
138 }
139  
140 sub _check_age {
141 18 ▶ my ($self) = @_;
Subroutine _check_age: called CC=3 SCAR=11.0
142  
143 18 my $epoch = $self->last_updated_epoch();
144 18 ▶ return unless $epoch;
Branch: 1 branch
BranchTrueFalseTotal
unless $epoch 0 18 18
145  
146 18 my $age_days = ($self->_now() - $epoch) / 86400;
147 18 ▶ if ($age_days > 28) {
Branch: 1 branch
BranchTrueFalseTotal
if ($age_days > 28) 8 10 18
148 8 carp sprintf "CMP list is older than 28 days (last updated: %s)", $self->{last_updated};
149 }
150 18 return;
151 }
152  
153 sub _now {
154 21 ▶ my ($self) = @_;
Subroutine _now: called CC=2 SCAR=7.1
155 21 ▶ return $self->{now} // time();
Condition66%2/3
$self->{"now"} // time
l!l&&r!l&&!r
1560
MC/DC0%0/2
$self->{"now"} // time
$self->{"now"} time
Truth table66%2/3
A // B
A= $self->{"now"}B= time
ABresult
1X1
011
000
156 }
157  
158 sub _load_time_piece {
159 21 ▶ return 1 if $INC{'Time/Piece.pm'};
Subroutine _load_time_piece: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
if $INC{"Time/Piece.pm"} 12 9 21
160 9 require Time::Piece;
161 9 return 1;
162 }
163  
164 sub _parse_date {
165 21 ▶ my ($self, $date_str) = @_;
Subroutine _parse_date: called CC=2 SCAR=7.1
166  
167 # IAB Registry timestamps come as "2020-04-27T20:27:54Z" or
168 # "2020-04-27T20:27:54.2Z". Strip the optional fractional seconds
169 # and the timezone suffix (always Z in the IAB feed) before handing
170 # to Time::Piece, which doesn't grok %z portably.
171 21 ▶ if ($date_str =~ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($date_str =~ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/u) 21 0 21
172 21 $self->_load_time_piece();
173  
174 21 my $t_str = "$1-$2-$3 $4:$5:$6";
175 21 my $epoch = eval { Time::Piece->strptime($t_str, "%Y-%m-%d %H:%M:%S")->epoch; };
176 21 return $epoch;
177 }
178 0 return;
179 }
180  
181 11 1;
182  
183 __END__
184  
185 =encoding utf8
186  
187 =head1 NAME
188  
189 GDPR::IAB::TCFv2::CMPValidator - IAB Registry-based Consent Management Platform validation
190  
191 =head1 SYNOPSIS
192  
193 use GDPR::IAB::TCFv2::CMPValidator;
194  
195 # Load from a local snapshot of the IAB CMP registry JSON
196 my $cmp_validator = GDPR::IAB::TCFv2::CMPValidator->new(
197 file => '/path/to/cmp-list.json',
198 );
199  
200 if ( $cmp_validator->is_valid(21) ) {
201 print "CMP 21 exists and has not been retired\n";
202 }
203  
204 # Compose with the main validator
205 use GDPR::IAB::TCFv2::Validator;
206  
207 my $validator = GDPR::IAB::TCFv2::Validator->new(
208 vendor_id => 284,
209 cmp_validator => $cmp_validator,
210 );
211  
212 my $tc_string = '...';
213 my $result = $validator->validate($tc_string);
214 warn "compliance failed: $result\n" unless $result;
215  
216 =head1 DESCRIPTION
217  
218 C<GDPR::IAB::TCFv2::CMPValidator> validates the C<cmp_id> embedded in a
219 TC string against a snapshot of the IAB TCF CMP registry. A registered
220 CMP that has been retired (the JSON record carries a C<deletedDate> in
221 the past) is treated as invalid.
222  
223 This module B<does not refresh the registry on its own>. The caller is
224 responsible for periodically downloading a fresh copy of
225 L<https://cmplist.consensu.org/v2/cmp-list.json> (or wherever the IAB
226 publishes the current registry) and pointing this validator at it.
227  
228 =head1 NETWORK FETCH IS OPT-IN
229  
230 The C<url> form does not fetch by default. A library that silently
231 dials out over the network on construction is a footgun -- it traps
232 on blocked egress, surprises operators with latency, and broadens the
233 supply-chain surface. To enable, pass C<network_ok =E<gt> 1> alongside
234 C<url>:
235  
236 GDPR::IAB::TCFv2::CMPValidator->new(
237 url => 'https://cmplist.consensu.org/v2/cmp-list.json',
238 network_ok => 1,
239 );
240  
241 Without C<network_ok>, passing C<url> croaks with a message pointing
242 the caller at C<file =E<gt> ...> / C<data =E<gt> ...> instead.
243  
244 =head1 CONSTRUCTOR
245  
246 =head2 new
247  
248 my $v = GDPR::IAB::TCFv2::CMPValidator->new( %args );
249  
250 Recognized keys:
251  
252 =over 4
253  
254 =item *
255  
256 C<file> -- path to a local JSON file in the IAB CMP-list shape. Read
257 synchronously via C<load_from_file>.
258  
259 =item *
260  
261 C<data> -- raw JSON text in the same shape. Parsed via
262 C<load_from_data>.
263  
264 =item *
265  
266 C<url> -- HTTP(S) URL of the registry. B<Requires> C<network_ok =E<gt> 1>
267 to actually fetch (see L</NETWORK FETCH IS OPT-IN>). Uses L<HTTP::Tiny>
268 when allowed; croaks if the module is not installed.
269  
270 =item *
271  
272 C<network_ok> -- boolean. Without it, the C<url> path croaks rather
273 than dialing out.
274  
275 =item *
276  
277 C<verify_ssl> -- boolean, default C<1>. Convenience option for the
278 default L<HTTP::Tiny> client: when true, server certificates are
279 verified. Disable only when targeting a CMP server with a self-signed
280 or otherwise non-public-CA certificate. Mutually exclusive with
281 C<http_client> (configure SSL on the injected client itself).
282  
283 =item *
284  
285 C<timeout> -- integer seconds, default C<30>. Convenience option for
286 the default L<HTTP::Tiny> client. Mutually exclusive with
287 C<http_client>.
288  
289 =item *
290  
291 C<http_client> -- a pre-built object that responds to
292 C<-E<gt>get($url)> in the L<HTTP::Tiny>-compatible shape (see
293 L</INJECTING AN HTTP CLIENT>). When provided, the validator uses this
294 object verbatim and does not construct its own L<HTTP::Tiny>; the
295 C<verify_ssl> and C<timeout> options are not accepted in this case
296 (passing either alongside C<http_client> croaks).
297  
298 =item *
299  
300 C<now> -- B<test only.> Override the wall clock used for
301 C<deletedDate> comparisons and the 28-day staleness check
302 (e.g. C<now =E<gt> 1776254400> pins comparisons to 2026-04-15).
303 Production code should leave this unset; the validator reads the real
304 wall clock by default.
305  
306 =back
307  
308 =head1 METHODS
309  
310 =head2 is_valid
311  
312 my $ok = $v->is_valid($cmp_id);
313  
314 Returns true when the registry knows about C<$cmp_id> and the entry
315 either carries no C<deletedDate> or its C<deletedDate> is still in the
316 future relative to L</now>.
317  
318 =head2 last_updated_epoch
319  
320 Returns the registry's C<lastUpdated> timestamp as a Unix epoch, or
321 undef when the field is absent or unparseable.
322  
323 =head2 load_from_file($path)
324  
325 Drop-in load that re-reads the registry from C<$path>. Useful when
326 the file has been refreshed out-of-band.
327  
328 =head2 load_from_data($json_text)
329  
330 Re-load from a raw JSON string.
331  
332 =head2 load_from_url($url)
333  
334 Fetch and load from C<$url>. Bypasses the C<network_ok> gate -- the
335 intent is that the caller has already validated they want to make a
336 network call. Uses the C<http_client> passed to the constructor when
337 present; otherwise constructs a default L<HTTP::Tiny> with
338 C<env_proxy =E<gt> 1>, C<verify_SSL> from C<verify_ssl>, and C<timeout>
339 from C<timeout>.
340  
341 =head1 NETWORK PROXIES
342  
343 When C<load_from_url> uses the default L<HTTP::Tiny> client (i.e. no
344 C<http_client> was injected), the standard HTTP-proxy environment
345 variables are honored automatically:
346  
347 =over 4
348  
349 =item *
350  
351 C<https_proxy> -- proxy for C<https://> URLs.
352  
353 =item *
354  
355 C<http_proxy> -- proxy for C<http://> URLs.
356  
357 =item *
358  
359 C<all_proxy> -- fallback for both.
360  
361 =item *
362  
363 C<no_proxy> -- comma-separated host/domain patterns to bypass
364 (e.g. C<localhost,*.internal>).
365  
366 =back
367  
368 Lowercase names are the canonical form. HTTP::Tiny accepts uppercase
369 as well, but the lowercase variants are preferred (some hardened
370 environments treat the uppercase form as a security risk because of
371 historical CGI injection bugs).
372  
373 When an injected C<http_client> is used, this module does no proxy
374 configuration of its own: configure the client however you need before
375 handing it in.
376  
377 =head1 INJECTING AN HTTP CLIENT
378  
379 For test fakes, custom CA bundles, signed-request middleware, or any
380 other case the convenience options do not cover, hand the validator a
381 pre-built object via C<http_client>:
382  
383 package FakeHttp;
384 sub new { bless { responses => $_[1] }, $_[0] }
385 sub get { my $self = shift; shift @{ $self->{responses} } }
386  
387 my $cmp_validator = GDPR::IAB::TCFv2::CMPValidator->new(
388 url => 'https://does-not-matter.example/',
389 network_ok => 1,
390 http_client => FakeHttp->new( [
391 { success => 1, content => '{"cmps": {"7": {"id": 7}}}' },
392 ] ),
393 );
394  
395 The injected object must be a blessed reference that responds to a
396 C<-E<gt>get($url)> method returning a hashref in the L<HTTP::Tiny>
397 shape: at minimum, C<success> (boolean), C<content> (response body on
398 success), and C<reason> (error text on failure). The constructor
399 verifies the object is blessed and L<UNIVERSAL/can> a C<get> method,
400 so AUTOLOAD-using classes must override C<can> to advertise their
401 methods (the standard Perl convention).
402  
403 =head1 STALE DATA WARNING
404  
405 When the registry's C<lastUpdated> is older than 28 days (relative to
406 L</now>), the constructor emits a warning via C<Carp::carp>. Suppress
407 with a local C<$SIG{__WARN__}> if your audit pipeline does not benefit
408 from it.
409  
410 =head1 SEE ALSO
411  
412 L<GDPR::IAB::TCFv2::Validator> for the rule engine that composes this
413 class as the C<cmp_validator> rule.
414  
415 =cut
« blib/lib/GDPR/IAB/TCFv2/Parser.pm ↑ Summary blib/lib/GDPR/IAB/TCFv2/PublisherTC.pm »