blib/lib/Net/Amazon/Signature/V4.pm

filter: Statementstmt 88.8% 112 / 126 Branchbran 76.4% 26 / 34 Conditioncond 66.6% 10 / 15 MC/DCmcdc 40.0% 4 / 10 Subroutinesub 94.1% 16 / 17 Podpod 100% 2 / 2 totaltotal 83.3% 170 / 204 CC 25 SCAR 16.1
CC
25
Cov
85%
_canonical_request
8.7
_simplify_uri
8.0
new
5.1
CRAP 5.0
↑ Summary
1 package Net::Amazon::Signature::V4;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use sort 'stable';
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 2 ▶use Digest::SHA qw/sha256_hex hmac_sha256 hmac_sha256_hex/;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use Time::Piece ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use URI::Escape;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 2 our $ALGORITHM = 'AWS4-HMAC-SHA256';
12  
13 =head1 NAME
14  
15 Net::Amazon::Signature::V4 - Implements the Amazon Web Services signature version 4, AWS4-HMAC-SHA256
16  
17 =head1 VERSION
18  
19 Version 0.21
20  
21 =cut
22  
23 2 our $VERSION = '0.21';
24  
25  
26 =head1 SYNOPSIS
27  
28 use Net::Amazon::Signature::V4;
29  
30 my $sig = Net::Amazon::Signature::V4->new( $access_key_id, $secret, $endpoint, $service );
31 my $req = HTTP::Request->parse( $request_string );
32 my $signed_req = $sig->sign( $req );
33 ...
34  
35 =head1 DESCRIPTION
36  
37 This module signs an HTTP::Request to Amazon Web Services by appending an Authorization header. Amazon Web Services signature version 4, AWS4-HMAC-SHA256, is used.
38  
39 The primary purpose of this module is to be used by Net::Amazon::Glacier.
40  
41 =head1 METHODS
42  
43 =head2 new
44  
45 my $sig = Net::Amazon::Signature::V4->new( $access_key_id, $secret, $endpoint, $service );
46 my $sig = Net::Amazon::Signature::V4->new({
47 access_key_id => $access_key_id,
48 secret => $secret,
49 endpoint => $endpoint,
50 service => $service,
51 });
52  
53 Constructs the signature object, which is used to sign requests.
54  
55 Note that the access key ID is an alphanumeric string, not your account ID. The endpoint could be "eu-west-1", and the service could be "glacier".
56  
57 Since version 0.20, parameters can be passed in a hashref. The keys C<access_key_id>, C<secret>, C<endpoint>, and C<service> are required.
58 C<security_token>, if passed, will be applied to each signed request as the C<X-Amz-Security-Token> header.
59  
60 =cut
61  
62 sub new {
63 1 ▶ my $class = shift;
Subroutine new: called CC=4 SCAR=16.3
Pod documented
64 1 my $self = {};
65 1 ▶ if (@_ == 1 and ref $_[0] eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1 and ref $_[0] eq 'HASH') { } 0 1 1
Condition33%1/3
@_ == 1 and ref $_[0] eq "HASH"
!ll&&!rl&&r
100
MC/DC0%0/2
@_ == 1 and ref $_[0] eq "HASH"
@_ == 1 ref $_[0] eq "HASH"
Truth table33%1/3
A and B
A= @_ == 1B= ref $_[0] eq "HASH"
ABresult
0X0
100
111
66 0 @$self{keys %{$_[0]}} = values %{$_[0]};
67 } else {
68 1 @$self{qw(access_key_id secret endpoint service)} = @_;
69 }
70 # The URI should not be double escaped for the S3 service
71 1 ▶ $self->{no_escape_uri} = ( lc($self->{service}) eq 's3' ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
lc $self->{'service'} eq 's3' ? : 0 1 1
72 1 bless $self, $class;
73 1 return $self;
74 }
75  
76 =head2 sign
77  
78 my $signed_request = $sig->sign( $request );
79  
80 Signs a request with your credentials by appending the Authorization header. $request should be an HTTP::Request. The signed request is returned.
81  
82 =cut
83  
84 sub sign {
85 0 ▶ my ( $self, $request ) = @_;
Subroutine sign: not called CC=1 SCAR=6.9
Pod documented
86 0 my $authz = $self->_authorization( $request );
87 0 $request->header( Authorization => $authz );
88 0 return $request;
89 }
90  
91 # _headers_to_sign:
92 # Return the sorted lower case headers as required by the generation of canonical headers
93  
94 sub _headers_to_sign {
95 124 ▶ my $req = shift;
Subroutine _headers_to_sign: called CC=1 SCAR=0.0
96  
97 124 return sort { $a cmp $b } map { lc } $req->headers->header_field_names;
98 }
99  
100 # _canonical_request:
101 # Construct the canonical request string from an HTTP::Request.
102  
103 sub _canonical_request {
104 93 ▶ my ( $self, $req ) = @_;
Subroutine _canonical_request: called CC=8 SCAR=21.6
105  
106 93 my $creq_method = $req->method;
107  
108 93 ▶ my ( $creq_canonical_uri, $creq_canonical_query_string ) =
Branch: 1 branch
BranchTrueFalseTotal
$req->uri =~ /([^?]*)\?(.*)$/ ? : 30 63 93
109 ( $req->uri =~ m@([^?]*)\?(.*)$@ )
110 ? ( $1, $2 )
111 : ( $req->uri, '' );
112 93 $creq_canonical_uri =~ s@^https?://[^/]*/?@/@;
113 93 $creq_canonical_uri = $self->_simplify_uri( $creq_canonical_uri );
114 93 $creq_canonical_query_string = _sort_query_string( $creq_canonical_query_string );
115  
116 # Ensure Host header is present as its required
117 93 ▶ if (!$req->header('host')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($req->header("host")) 0 93 93
118 0 ▶ my $host = $req->uri->_port ? $req->uri->host_port : $req->uri->host;
Branch: 1 branch
BranchTrueFalseTotal
$req->uri->_port ? : 0 0 0
119 0 $req->header('Host' => $host);
120 }
121 93 my $creq_payload_hash = $req->header('x-amz-content-sha256');
122 93 ▶ if (!$creq_payload_hash) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($creq_payload_hash) 31 62 93
123 31 $creq_payload_hash = sha256_hex($req->content);
124 # X-Amz-Content-Sha256 must be specified now
125 31 $req->header('X-Amz-Content-Sha256' => $creq_payload_hash);
126 }
127  
128 # There's a bug in AMS4 which causes requests without x-amz-date set to be rejected
129 # so we always add one if its not present.
130 93 my $amz_date = $req->header('x-amz-date');
131 93 ▶ if (!$amz_date) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($amz_date) 31 62 93
132 31 $req->header('X-Amz-Date' => _req_timepiece($req)->strftime('%Y%m%dT%H%M%SZ'));
133 }
134 93 ▶ if (defined $self->{security_token} and !defined $req->header('X-Amz-Security-Token')) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"security_token"} and not defined $req->header("X-Amz-Security-Token")) 0 93 93
Condition33%1/3
defined $self->{"security_token"} and not defined $req->header("X-Amz-Security-Token")
!ll&&!rl&&r
9300
MC/DC0%0/2
defined $self->{"security_token"} and not defined $req->header("X-Amz-Security-Token")
defined $self->{"security_token"} not defined $req->header("X-Amz-Security-Token")
Truth table33%1/3
A and not(B)
A= defined $self->{"security_token"}B= not defined $req->header("X-Amz-Security-Token")
ABresult
0X0
100
111
135 0 $req->header('X-Amz-Security-Token' => $self->{security_token});
136 }
137 93 my @sorted_headers = _headers_to_sign( $req );
138 my $creq_canonical_headers = join '',
139 map {
140 93 sprintf "%s:%s\x0a",
141 lc,
142 393 join ',', sort {$a cmp $b } _trim_whitespace($req->header($_) )
143 }
144 @sorted_headers;
145 93 my $creq_signed_headers = join ';', map {lc} @sorted_headers;
146 93 my $creq = join "\x0a",
147 $creq_method, $creq_canonical_uri, $creq_canonical_query_string,
148 $creq_canonical_headers, $creq_signed_headers, $creq_payload_hash;
149 93 return $creq;
150 }
151  
152 # _string_to_sign
153 # Construct the string to sign.
154  
155 sub _string_to_sign {
156 62 ▶ my ( $self, $req ) = @_;
Subroutine _string_to_sign: called CC=1 SCAR=0.0
157 62 my $dt = _req_timepiece( $req );
158 62 my $creq = $self->_canonical_request($req);
159 62 my $sts_request_date = $dt->strftime( '%Y%m%dT%H%M%SZ' );
160 62 my $sts_credential_scope = join '/', $dt->strftime('%Y%m%d'), $self->{endpoint}, $self->{service}, 'aws4_request';
161 62 my $sts_creq_hash = sha256_hex( $creq );
162  
163 62 my $sts = join "\x0a", $ALGORITHM, $sts_request_date, $sts_credential_scope, $sts_creq_hash;
164 62 return $sts;
165 }
166  
167 # _authorization
168 # Construct the authorization string
169  
170 sub _authorization {
171 31 ▶ my ( $self, $req ) = @_;
Subroutine _authorization: called CC=1 SCAR=0.0
172  
173 31 my $dt = _req_timepiece( $req );
174 31 my $sts = $self->_string_to_sign( $req );
175 31 my $k_date = hmac_sha256( $dt->strftime('%Y%m%d'), 'AWS4' . $self->{secret} );
176 31 my $k_region = hmac_sha256( $self->{endpoint}, $k_date );
177 31 my $k_service = hmac_sha256( $self->{service}, $k_region );
178 31 my $k_signing = hmac_sha256( 'aws4_request', $k_service );
179  
180 31 my $authz_signature = hmac_sha256_hex( $sts, $k_signing );
181 31 my $authz_credential = join '/', $self->{access_key_id}, $dt->strftime('%Y%m%d'), $self->{endpoint}, $self->{service}, 'aws4_request';
182 31 my $authz_signed_headers = join ';', _headers_to_sign( $req );
183  
184 31 my $authz = "$ALGORITHM Credential=$authz_credential,SignedHeaders=$authz_signed_headers,Signature=$authz_signature";
185 31 return $authz;
186  
187 }
188  
189 =head1 AUTHOR
190  
191 Tim Nordenfur, C<< <tim at gurka.se> >>
192  
193 Maintained by Dan Book, C<< <dbook at cpan.org> >>
194  
195 =cut
196  
197 sub _simplify_uri {
198 93 ▶ my $self = shift;
Subroutine _simplify_uri: called CC=8 SCAR=20.8
199 93 my $orig_uri = shift;
200 93 my @parts = split /\//, $orig_uri;
201 93 my @simple_parts = ();
202 93 for my $part ( @parts ) {
203 78 ▶ if ( $part eq '' || $part eq '.' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($part eq '' or $part eq '.') { } 36 42 78
elsif ($part eq '..') { } 9 33 42
Condition100%3/3
$part eq "" or $part eq "."
l!l&&r!l&&!r
30642
MC/DC100%2/2
$part eq "" or $part eq "."
$part eq "" $part eq "."
Truth table100%3/3
A or B
A= $part eq ""B= $part eq "."
ABresult
1X1
011
000
204 } elsif ( $part eq '..' ) {
205 9 pop @simple_parts;
206 } else {
207 33 ▶ if ( $self->{no_escape_uri} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'no_escape_uri'}) { } 0 33 33
208 0 push @simple_parts, $part;
209 }
210 else {
211 33 push @simple_parts, uri_escape($part);
212 }
213 }
214 }
215 93 my $simple_uri = '/' . join '/', @simple_parts;
216 93 ▶ $simple_uri .= '/' if $orig_uri =~ m@/$@ && $simple_uri !~ m@/$@;
Branch: 1 branch
BranchTrueFalseTotal
if $orig_uri =~ m[/$] and not $simple_uri =~ m[/$] 3 90 93
Condition100%3/3
$orig_uri =~ m[/$] and not $simple_uri =~ m[/$]
!ll&&!rl&&r
21693
MC/DC100%2/2
$orig_uri =~ m[/$] and not $simple_uri =~ m[/$]
$orig_uri =~ m[/$] not $simple_uri =~ m[/$]
Truth table100%3/3
A and not(B)
A= $orig_uri =~ m[/$]B= not $simple_uri =~ m[/$]
ABresult
0X0
100
111
217 93 return $simple_uri;
218 }
219 sub _sort_query_string {
220 93 ▶ return '' unless $_[0];
Subroutine _sort_query_string: called CC=5 SCAR=16.1
Branch: 1 branch
BranchTrueFalseTotal
unless $_[0] 63 30 93
221 30 my @params;
222 30 for my $param ( split /&/, $_[0] ) {
223 my ( $key, $value ) =
224 42 map { tr/+/ /; uri_escape( uri_unescape( $_ ) ) } # escape all non-unreserved chars
225 split /=/, $param;
226 42 ▶ push @params, [$key, (defined $value ? $value : '')];
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 36 6 42
227 }
228 return join '&',
229 42 map { join '=', @$_ }
230 30 ▶ sort { ( $a->[0] cmp $b->[0] ) || ( $a->[1] cmp $b->[1] ) }
Branch: 1 branch
BranchTrueFalseTotal
$Net::Amazon::Signature::V4::a->[0] cmp $Net::Amazon::Signature::V4::b->[0] or $Net::Amazon::Signature::V4::a->[1] cmp $Net::Amazon::Signature::V4::b->[1] 6 6 12
231 @params;
232 }
233 sub _trim_whitespace {
234 393 ▶ return map { my $str = $_; $str =~ s/^\s*//; $str =~ s/\s*$//; $str } @_;
Subroutine _trim_whitespace: called CC=1 SCAR=0.0
235 }
236 sub _str_to_timepiece {
237 124 ▶ my $date = shift;
Subroutine _str_to_timepiece: called CC=2 SCAR=6.9
238 124 ▶ if ( $date =~ m/^\d{8}T\d{6}Z$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($date =~ /^\d{8}T\d{6}Z$/) { } 93 31 124
239 # assume basic ISO 8601, as demanded by AWS
240 93 return Time::Piece->strptime($date, '%Y%m%dT%H%M%SZ');
241 } else {
242 # assume the format given in the AWS4 test suite
243 31 $date =~ s/^.{5}//; # remove weekday, as Amazon's test suite contains internally inconsistent dates
244 31 return Time::Piece->strptime($date, '%d %b %Y %H:%M:%S %Z');
245 }
246 }
247 sub _req_timepiece {
248 124 ▶ my $req = shift;
Subroutine _req_timepiece: called CC=3 SCAR=12.6
249 124 my $x_date = $req->header('X-Amz-Date');
250 124 ▶ my $date = $x_date || $req->header('Date');
Condition66%2/3
$x_date || $req->header('Date')
l!l&&r!l&&!r
93310
MC/DC0%0/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
251 124 ▶ if (!$date) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($date) 0 124 124
252 # No date set by the caller so set one up
253 0 my $piece = Time::Piece::gmtime;
254 0 $req->date($piece->epoch);
255 0 return $piece
256 }
257 124 return _str_to_timepiece($date);
258 }
259  
260 =head1 BUGS
261  
262 Please report any bugs or feature requests to C<bug-Net-Amazon-Signature-V4 at rt.cpan.org>, or through
263 the web interface at L<https://rt.cpan.org/Public/Bug/Report.html?Queue=Net-Amazon-Signature-V4>. I will be notified, and then you'll
264 automatically be notified of progress on your bug as I make changes.
265  
266  
267  
268  
269 =head1 SUPPORT
270  
271 You can find documentation for this module with the perldoc command.
272  
273 perldoc Net::Amazon::Signature::V4
274  
275  
276 You can also look for information at:
277  
278 =over 4
279  
280 =item * RT: CPAN's request tracker (report bugs here)
281  
282 L<https://rt.cpan.org/Public/Dist/Display.html?Name=Net-Amazon-Signature-V4>
283  
284 =item * Source on GitHub
285  
286 L<https://github.com/Grinnz/Net-Amazon-Signature-V4>
287  
288 =item * Search CPAN
289  
290 L<https://metacpan.org/release/Net-Amazon-Signature-V4>
291  
292 =back
293  
294 =head1 LICENSE AND COPYRIGHT
295  
296 This software is copyright (c) 2012 by Tim Nordenfur.
297  
298 This is free software; you can redistribute it and/or modify it under
299 the same terms as the Perl 5 programming language system itself.
300  
301  
302 =cut
303  
304 2 1; # End of Net::Amazon::Signature::V4
↑ Summary