Net/Amazon/S3/Signature/V4Implementation.pm

filter: Statementstmt 91.9% 148 / 161 Branchbran 55.2% 21 / 38 Conditioncond 47.3% 9 / 19 MC/DCmcdc 33.3% 4 / 12 Subroutinesub 96.3% 26 / 27 Podpod 66.6% 2 / 3 totaltotal 80.7% 210 / 260 SCAR 35.3
CC
29
Cov
82%
_simplify_uri
56.0
_augment_uri
10.4
_sort_query_string
5.0
CRAP 34.2
« Shared/Examples/Net/Amazon/S3.pm ↑ Summary Net/Amazon/S3.pm »
1 package Net::Amazon::S3::Signature::V4Implementation;
2 # ABSTRACT: Implements the Amazon Web Services signature version 4, AWS4-HMAC-SHA256 (copy of Net::Amazon::Signature::V4)
3 99 $Net::Amazon::S3::Signature::V4Implementation::VERSION = '0.991';
4  
5 99 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 99 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 99 ▶use sort 'stable';
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 99 ▶use Digest::SHA qw/sha256_hex hmac_sha256 hmac_sha256_hex/;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 99 ▶use Time::Piece ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 99 ▶use URI::Escape;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 99 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 99 ▶use URI::QueryParam;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 99 our $ALGORITHM = 'AWS4-HMAC-SHA256';
16 99 our $MAX_EXPIRES = 604800; # Max, 7 days
17  
18 99 our $X_AMZ_ALGORITHM = 'X-Amz-Algorithm';
19 99 our $X_AMZ_CONTENT_SHA256 = 'X-Amz-Content-Sha256';
20 99 our $X_AMZ_CREDENTIAL = 'X-Amz-Credential';
21 99 our $X_AMZ_DATE = 'X-Amz-Date';
22 99 our $X_AMZ_EXPIRES = 'X-Amz-Expires';
23 99 our $X_AMZ_SIGNEDHEADERS = 'X-Amz-SignedHeaders';
24 99 our $X_AMZ_SIGNATURE = 'X-Amz-Signature';
25  
26  
27  
28 sub new {
29 7 ▶ my $class = shift;
Subroutine new: called CC=1 SCAR=0.0
Pod undocumented
30 7 my ( $access_key_id, $secret, $endpoint, $service ) = @_;
31 7 my $self = {
32 access_key_id => $access_key_id,
33 secret => $secret,
34 endpoint => $endpoint,
35 service => $service,
36 };
37 7 bless $self, $class;
38 7 return $self;
39 }
40  
41  
42 sub sign {
43 1 ▶ my ( $self, $request ) = @_;
Subroutine sign: called CC=1 SCAR=0.0
Pod documented
44  
45 1 $request = $self->_augment_request( $request );
46  
47 1 my $authz = $self->_authorization( $request );
48 1 $request->header( Authorization => $authz );
49 1 return $request;
50 }
51  
52  
53 sub sign_uri {
54 6 ▶ my ( $self, $uri, $expires_in, $for_method ) = @_;
Subroutine sign_uri: called CC=1 SCAR=0.0
Pod documented
55  
56 6 my $request = $self->_augment_uri( $uri, $expires_in, $for_method );
57  
58 6 my $signature = $self->_signature( $request );
59  
60 6 $uri = $request->uri;
61 6 my $query = $uri->query;
62 6 $uri->query( undef );
63 6 $uri = $uri . '?' . $self->_sort_query_string( $query );
64 6 $uri .= "&$X_AMZ_SIGNATURE=$signature";
65  
66 6 return $uri;
67 }
68  
69 # _headers_to_sign:
70 # Return the sorted lower case headers as required by the generation of canonical headers
71  
72 sub _headers_to_sign {
73 15 ▶ my $req = shift;
Subroutine _headers_to_sign: called CC=2 SCAR=6.9
74  
75 15 ▶ my @headers_to_sign = $req->uri->query_param( $X_AMZ_SIGNEDHEADERS )
Branch: 1 branch
BranchTrueFalseTotal
$req->uri->query_param($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_SIGNEDHEADERS) ? : 12 3 15
76 ? $req->uri->query_param( $X_AMZ_SIGNEDHEADERS )
77 : $req->headers->header_field_names
78 ;
79  
80 15 return sort { $a cmp $b } map { lc } @headers_to_sign
81 }
82  
83 # _augment_request:
84 # Append mandatory header fields
85  
86 sub _augment_request {
87 1 ▶ my ( $self, $request ) = @_;
Subroutine _augment_request: called CC=3 SCAR=11.4
88  
89 1 ▶ $request->header($X_AMZ_DATE => $self->_format_amz_date( $self->_req_timepiece($request) ))
Branch: 1 branch
BranchTrueFalseTotal
unless $request->header($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_DATE) 1 0 1
90 unless $request->header($X_AMZ_DATE);
91  
92 1 ▶ $request->header($X_AMZ_CONTENT_SHA256 => sha256_hex($request->content))
Branch: 1 branch
BranchTrueFalseTotal
unless $request->header($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_CONTENT_SHA256) 1 0 1
93 unless $request->header($X_AMZ_CONTENT_SHA256);
94  
95 1 return $request;
96 }
97  
98 # _augment_uri:
99 # Append mandatory uri parameters
100  
101 sub _augment_uri {
102 6 ▶ my ($self, $uri, $expires_in, $method) = @_;
Subroutine _augment_uri: called CC=8 SCAR=23.4
103  
104 6 ▶ my $request = HTTP::Request->new( $method || GET => $uri );
Condition50%1/2
$method || 'GET'
l!l
60
MC/DC0%0/1
$method || 'GET'
$method
Truth table50%1/2
A
A= $method
Aresult
11
00
105  
106 6 ▶ $request->uri->query_param( $X_AMZ_DATE => $self->_format_amz_date( $self->_now ) )
Branch: 1 branch
BranchTrueFalseTotal
unless $request->uri->query_param($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_DATE) 6 0 6
107 unless $request->uri->query_param( $X_AMZ_DATE );
108  
109 6 ▶ $request->uri->query_param( $X_AMZ_ALGORITHM => $ALGORITHM )
Branch: 1 branch
BranchTrueFalseTotal
unless $request->uri->query_param($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_ALGORITHM) 6 0 6
110 unless $request->uri->query_param( $X_AMZ_ALGORITHM );
111  
112 6 ▶ $request->uri->query_param( $X_AMZ_CREDENTIAL => $self->_credential( $request ) )
Branch: 1 branch
BranchTrueFalseTotal
unless $request->uri->query_param($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_CREDENTIAL) 6 0 6
113 unless $request->uri->query_param( $X_AMZ_CREDENTIAL );
114  
115 6 ▶ $request->uri->query_param( $X_AMZ_EXPIRES => $expires_in || $MAX_EXPIRES )
Branch: 1 branch
BranchTrueFalseTotal
unless $request->uri->query_param($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_EXPIRES) 6 0 6
Condition33%1/3
$expires_in || $Net::Amazon::S3::Signature::V4Implementation::MAX_EXPIRES
l!l&&r!l&&!r
600
MC/DC0%0/2
$expires_in || $Net::Amazon::S3::Signature::V4Implementation::MAX_EXPIRES
$expires_in $Net::Amazon::S3::Signature::V4Implementation::MAX_EXPIRES
Truth table33%1/3
A || B
A= $expires_inB= $Net::Amazon::S3::Signature::V4Implementation::MAX_EXPIRES
ABresult
1X1
011
000
116 unless $request->uri->query_param( $X_AMZ_EXPIRES );
117 6 ▶ $request->uri->query_param( $X_AMZ_EXPIRES => $MAX_EXPIRES )
Branch: 1 branch
BranchTrueFalseTotal
if $request->uri->query_param($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_EXPIRES) > $Net::Amazon::S3::Signature::V4Implementation::MAX_EXPIRES 0 6 6
118 if $request->uri->query_param( $X_AMZ_EXPIRES ) > $MAX_EXPIRES;
119  
120 6 $request->uri->query_param( $X_AMZ_SIGNEDHEADERS => 'host' );
121  
122 6 return $request;
123 }
124  
125 # _canonical_request:
126 # Construct the canonical request string from an HTTP::Request.
127  
128 sub _canonical_request {
129 7 ▶ my ( $self, $req ) = @_;
Subroutine _canonical_request: called CC=5 SCAR=16.1
130  
131 7 my $creq_method = $req->method;
132  
133 7 ▶ my ( $creq_canonical_uri, $creq_canonical_query_string ) =
Branch: 1 branch
BranchTrueFalseTotal
$req->uri =~ /([^?]*)\?(.*)$/ ? : 6 1 7
134 ( $req->uri =~ m@([^?]*)\?(.*)$@ )
135 ? ( $1, $2 )
136 : ( $req->uri, '' );
137 7 $creq_canonical_uri =~ s@^https?://[^/]*/?@/@;
138  
139 # Documentation says "do not normalize URI paths for requests to Amazon S3"
140 # https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
141  
142 #$creq_canonical_uri = _simplify_uri( $creq_canonical_uri );
143  
144 7 $creq_canonical_query_string = $self->_sort_query_string( $creq_canonical_query_string );
145  
146 # Ensure Host header is present as its required
147 7 ▶ if (!$req->header('host')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($req->header("host")) 7 0 7
148 7 ▶ my $host = $req->uri->_port
Branch: 1 branch
BranchTrueFalseTotal
$req->uri->_port ? : 2 5 7
149 ? $req->uri->host_port
150 : $req->uri->host
151 ;
152 7 $req->header('Host' => $host);
153 }
154 7 ▶ my $creq_payload_hash = $req->header($X_AMZ_CONTENT_SHA256)
Condition100%2/2
$req->header($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_CONTENT_SHA256) || 'UNSIGNED-PAYLOAD'
l!l
16
MC/DC100%1/1
$req->header($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_CONTENT_SHA256) || 'UNSIGNED-PAYLOAD'
$req->header($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_CONTENT_SHA256)
Truth table100%2/2
A
A= $req->header($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_CONTENT_SHA256)
Aresult
11
00
155 # Signed uri doesn't have content
156 || 'UNSIGNED-PAYLOAD';
157  
158 # There's a bug in AMS4 which causes requests without x-amz-date set to be rejected
159 # so we always add one if its not present.
160 7 my $amz_date = $req->header($X_AMZ_DATE);
161 7 my @sorted_headers = _headers_to_sign( $req );
162 my $creq_canonical_headers = join '',
163 map {
164 7 sprintf "%s:%s\x0a",
165 lc,
166 13 join ',', sort {$a cmp $b } _trim_whitespace($req->header($_) )
167 }
168 @sorted_headers;
169 7 my $creq_signed_headers = $self->_signed_headers( $req );
170 7 my $creq = join "\x0a",
171 $creq_method, $creq_canonical_uri, $creq_canonical_query_string,
172 $creq_canonical_headers, $creq_signed_headers, $creq_payload_hash;
173  
174 7 return $creq;
175 }
176  
177 # _string_to_sign
178 # Construct the string to sign.
179  
180 sub _string_to_sign {
181 7 ▶ my ( $self, $req ) = @_;
Subroutine _string_to_sign: called CC=1 SCAR=0.0
182 7 my $dt = $self->_req_timepiece( $req );
183 7 my $creq = $self->_canonical_request($req);
184 7 my $sts_request_date = $self->_format_amz_date( $dt );
185 7 my $sts_credential_scope = join '/', $dt->strftime('%Y%m%d'), $self->{endpoint}, $self->{service}, 'aws4_request';
186 7 my $sts_creq_hash = sha256_hex( $creq );
187  
188 7 my $sts = join "\x0a", $ALGORITHM, $sts_request_date, $sts_credential_scope, $sts_creq_hash;
189 7 return $sts;
190 }
191  
192 # _authorization
193 # Construct the authorization string
194  
195 sub _signature {
196 7 ▶ my ( $self, $req ) = @_;
Subroutine _signature: called CC=1 SCAR=0.0
197  
198 7 my $dt = $self->_req_timepiece( $req );
199 7 my $sts = $self->_string_to_sign( $req );
200 7 my $k_date = hmac_sha256( $dt->strftime('%Y%m%d'), 'AWS4' . $self->{secret} );
201 7 my $k_region = hmac_sha256( $self->{endpoint}, $k_date );
202 7 my $k_service = hmac_sha256( $self->{service}, $k_region );
203 7 my $k_signing = hmac_sha256( 'aws4_request', $k_service );
204  
205 7 my $authz_signature = hmac_sha256_hex( $sts, $k_signing );
206 7 return $authz_signature;
207 }
208  
209 sub _credential {
210 7 ▶ my ( $self, $req ) = @_;
Subroutine _credential: called CC=1 SCAR=0.0
211  
212 7 my $dt = $self->_req_timepiece( $req );
213  
214 7 my $authz_credential = join '/', $self->{access_key_id}, $dt->strftime('%Y%m%d'), $self->{endpoint}, $self->{service}, 'aws4_request';
215 7 return $authz_credential;
216 }
217  
218 sub _signed_headers {
219 8 ▶ my ( $self, $req ) = @_;
Subroutine _signed_headers: called CC=1 SCAR=0.0
220  
221 8 my $authz_signed_headers = join ';', _headers_to_sign( $req );
222 8 return $authz_signed_headers;
223 }
224  
225 sub _authorization {
226 1 ▶ my ( $self, $req ) = @_;
Subroutine _authorization: called CC=1 SCAR=0.0
227  
228 1 my $authz_signature = $self->_signature( $req );
229 1 my $authz_credential = $self->_credential( $req );
230 1 my $authz_signed_headers = $self->_signed_headers( $req );
231  
232 1 my $authz = "$ALGORITHM Credential=$authz_credential,SignedHeaders=$authz_signed_headers,Signature=$authz_signature";
233 1 return $authz;
234  
235 }
236  
237 sub _simplify_uri {
238 0 ▶ my $orig_uri = shift;
Subroutine _simplify_uri: not called CC=7 SCAR=40.3
239 0 my @parts = split /\//, $orig_uri;
240 0 my @simple_parts = ();
241 0 for my $part ( @parts ) {
242 0 ▶ if ( ! length $part || $part eq '.' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not length $part or $part eq '.') { } 0 0 0
elsif ($part eq '..') { } 0 0 0
Condition0%0/3
not length $part or $part eq "."
l!l&&r!l&&!r
000
MC/DC0%0/2
not length $part or $part eq "."
not length $part $part eq "."
Truth table0%0/3
not(A) or B
A= not length $partB= $part eq "."
ABresult
1X1
011
000
243 } elsif ( $part eq '..' ) {
244 0 pop @simple_parts;
245 } else {
246 0 push @simple_parts, $part;
247 }
248 }
249 0 my $simple_uri = '/' . join '/', @simple_parts;
250 0 ▶ $simple_uri .= '/' if $orig_uri =~ m@/$@ && $simple_uri !~ m@/$@;
Branch: 1 branch
BranchTrueFalseTotal
if $orig_uri =~ m[/$] and not $simple_uri =~ m[/$] 0 0 0
Condition0%0/3
$orig_uri =~ m[/$] and not $simple_uri =~ m[/$]
!ll&&!rl&&r
000
MC/DC0%0/2
$orig_uri =~ m[/$] and not $simple_uri =~ m[/$]
$orig_uri =~ m[/$] not $simple_uri =~ m[/$]
Truth table0%0/3
A and not(B)
A= $orig_uri =~ m[/$]B= not $simple_uri =~ m[/$]
ABresult
0X0
100
111
251 0 return $simple_uri;
252 }
253 sub _sort_query_string {
254 13 ▶ my $self = shift;
Subroutine _sort_query_string: called CC=5 SCAR=16.2
255 13 ▶ return '' unless $_[0];
Branch: 1 branch
BranchTrueFalseTotal
unless $_[0] 1 12 13
256 12 my @params;
257 12 for my $param ( split /&/, $_[0] ) {
258 my ( $key, $value ) =
259 60 map { tr/+/ /; uri_escape( uri_unescape( $_ ) ) } # escape all non-unreserved chars
260 split /=/, $param;
261 60 ▶ push @params, [$key, (defined $value ? $value : '')];
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 60 0 60
262 #push @params, [$key, $value];
263 }
264 return join '&',
265 60 map { join '=', grep defined, @$_ }
266 12 ▶ sort { ( $a->[0] cmp $b->[0] ) || ( $a->[1] cmp $b->[1] ) }
Branch: 1 branch
BranchTrueFalseTotal
$Net::Amazon::S3::Signature::V4Implementation::a->[0] cmp $Net::Amazon::S3::Signature::V4Implementation::b->[0] or $Net::Amazon::S3::Signature::V4Implementation::a->[1] cmp $Net::Amazon::S3::Signature::V4Implementation::b->[1] 0 108 108
267 @params;
268 }
269 sub _trim_whitespace {
270 13 ▶ return map { my $str = $_; $str =~ s/^\s*//; $str =~ s/\s*$//; $str } @_;
Subroutine _trim_whitespace: called CC=1 SCAR=0.0
271 }
272 sub _str_to_timepiece {
273 21 ▶ my $date = shift;
Subroutine _str_to_timepiece: called CC=2 SCAR=8.4
274 21 ▶ if ( $date =~ m/^\d{8}T\d{6}Z$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($date =~ /^\d{8}T\d{6}Z$/) { } 21 0 21
275 # assume basic ISO 8601, as demanded by AWS
276 21 return Time::Piece->strptime($date, '%Y%m%dT%H%M%SZ');
277 } else {
278 # assume the format given in the AWS4 test suite
279 0 $date =~ s/^.{5}//; # remove weekday, as Amazon's test suite contains internally inconsistent dates
280 0 return Time::Piece->strptime($date, '%d %b %Y %H:%M:%S %Z');
281 }
282 }
283  
284 sub _format_amz_date {
285 14 ▶ my ($self, $dt) = @_;
Subroutine _format_amz_date: called CC=1 SCAR=0.0
286  
287 14 $dt->strftime('%Y%m%dT%H%M%SZ');
288 }
289  
290 sub _now {
291 7 ▶ return scalar Time::Piece->gmtime;
Subroutine _now: called CC=1 SCAR=0.0
292 }
293  
294 sub _req_timepiece {
295 22 ▶ my ($self, $req) = @_;
Subroutine _req_timepiece: called CC=4 SCAR=13.9
296 22 ▶ my $x_date = $req->header($X_AMZ_DATE) || $req->uri->query_param($X_AMZ_DATE);
Condition100%3/3
$req->header($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_DATE) || $req->uri->query_param($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_DATE)
l!l&&r!l&&!r
3181
MC/DC100%2/2
$req->header($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_DATE) || $req->uri->query_param($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_DATE)
$req->header($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_DATE) $req->uri->query_param($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_DATE)
Truth table100%3/3
A || B
A= $req->header($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_DATE)B= $req->uri->query_param($Net::Amazon::S3::Signature::V4Implementation::X_AMZ_DATE)
ABresult
1X1
011
000
297 22 ▶ my $date = $x_date || $req->header('Date');
Condition66%2/3
$x_date || $req->header('Date')
l!l&&r!l&&!r
2101
MC/DC50%1/2
$x_date || $req->header('Date')
$x_date $req->header('Date')
Truth table66%2/3
A || B
A= $x_dateB= $req->header('Date')
ABresult
1X1
011
000
298 22 ▶ if (!$date) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($date) 1 21 22
299 # No date set by the caller so set one up
300 1 my $piece = $self->_now;
301 1 $req->date($piece->epoch);
302 1 return $piece
303 }
304 21 return _str_to_timepiece($date);
305 }
306  
307 99 1;
308  
309 __END__
310  
311 =pod
312  
313 =encoding UTF-8
314  
315 =head1 NAME
316  
317 Net::Amazon::S3::Signature::V4Implementation - Implements the Amazon Web Services signature version 4, AWS4-HMAC-SHA256 (copy of Net::Amazon::Signature::V4)
318  
319 =head1 VERSION
320  
321 version 0.991
322  
323 =head1 DESCRIPTION
324  
325 This package clones L<Net::Amazon::Signature::V4> 0.19 adding support for
326 signing URIs (GET request)
327  
328 Until https://github.com/Grinnz/Net-Amazon-Signature-V4/pull/5 will be merged
329 we have to maintain our clone.
330  
331 =head1 Net::Amazon::Signature::S4 AUTHORS
332  
333 Tim Nordenfur, C<< <tim at gurka.se> >>
334  
335 Maintained by Dan Book, C<< <dbook at cpan.org> >>
336  
337 =head2 sign( $request )
338  
339 Signs a request with your credentials by appending the Authorization header. $request should be an HTTP::Request. The signed request is returned.
340  
341 =head2 sign_uri( $uri, $expires_in?, $for_method? )
342  
343 Signs an uri with your credentials by appending the Authorization query parameters.
344  
345 C<< $expires_in >> integer value in range 1..604800 (1 second .. 7 days).
346  
347 C<< $expires_in >> default value is its maximum: 604800
348  
349 C<< $for_method >> HTTP method this uri should be signed for, default C<GET>
350  
351 The signed uri is returned.
352  
353 =head1 AUTHOR
354  
355 Branislav Zahradník <barney@cpan.org>
356  
357 =head1 COPYRIGHT AND LICENSE
358  
359 This software is copyright (c) 2022 by Amazon Digital Services, Leon Brocard, Brad Fitzpatrick, Pedro Figueiredo, Rusty Conover, Branislav Zahradník.
360  
361 This is free software; you can redistribute it and/or modify it under
362 the same terms as the Perl 5 programming language system itself.
363  
364 =cut
« Shared/Examples/Net/Amazon/S3.pm ↑ Summary Net/Amazon/S3.pm »