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

filter: Statementstmt 89.6% 112 / 125 Branchbran 81.2% 26 / 32 Conditioncond 66.6% 10 / 15 MC/DCmcdc 40.0% 4 / 10 Subroutinesub 94.1% 16 / 17 Podpod 100% 2 / 2 totaltotal 84.5% 170 / 201 SCAR 32.4
CC
24
Cov
86%
_simplify_uri
8.0
_canonical_request
7.2
new
5.1
CRAP 25.6
↑ 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.20
20  
21 =cut
22  
23 2 our $VERSION = '0.20';
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=7 SCAR=19.7
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 $req->header('Host' => $req->uri->host);
119 }
120 93 my $creq_payload_hash = $req->header('x-amz-content-sha256');
121 93 ▶ if (!$creq_payload_hash) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($creq_payload_hash) 31 62 93
122 31 $creq_payload_hash = sha256_hex($req->content);
123 # X-Amz-Content-Sha256 must be specified now
124 31 $req->header('X-Amz-Content-Sha256' => $creq_payload_hash);
125 }
126  
127 # There's a bug in AMS4 which causes requests without x-amz-date set to be rejected
128 # so we always add one if its not present.
129 93 my $amz_date = $req->header('x-amz-date');
130 93 ▶ if (!$amz_date) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($amz_date) 31 62 93
131 31 $req->header('X-Amz-Date' => _req_timepiece($req)->strftime('%Y%m%dT%H%M%SZ'));
132 }
133 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
134 0 $req->header('X-Amz-Security-Token' => $self->{security_token});
135 }
136 93 my @sorted_headers = _headers_to_sign( $req );
137 my $creq_canonical_headers = join '',
138 map {
139 93 sprintf "%s:%s\x0a",
140 lc,
141 393 join ',', sort {$a cmp $b } _trim_whitespace($req->header($_) )
142 }
143 @sorted_headers;
144 93 my $creq_signed_headers = join ';', map {lc} @sorted_headers;
145 93 my $creq = join "\x0a",
146 $creq_method, $creq_canonical_uri, $creq_canonical_query_string,
147 $creq_canonical_headers, $creq_signed_headers, $creq_payload_hash;
148 93 return $creq;
149 }
150  
151 # _string_to_sign
152 # Construct the string to sign.
153  
154 sub _string_to_sign {
155 62 ▶ my ( $self, $req ) = @_;
Subroutine _string_to_sign: called CC=1 SCAR=0.0
156 62 my $dt = _req_timepiece( $req );
157 62 my $creq = $self->_canonical_request($req);
158 62 my $sts_request_date = $dt->strftime( '%Y%m%dT%H%M%SZ' );
159 62 my $sts_credential_scope = join '/', $dt->strftime('%Y%m%d'), $self->{endpoint}, $self->{service}, 'aws4_request';
160 62 my $sts_creq_hash = sha256_hex( $creq );
161  
162 62 my $sts = join "\x0a", $ALGORITHM, $sts_request_date, $sts_credential_scope, $sts_creq_hash;
163 62 return $sts;
164 }
165  
166 # _authorization
167 # Construct the authorization string
168  
169 sub _authorization {
170 31 ▶ my ( $self, $req ) = @_;
Subroutine _authorization: called CC=1 SCAR=0.0
171  
172 31 my $dt = _req_timepiece( $req );
173 31 my $sts = $self->_string_to_sign( $req );
174 31 my $k_date = hmac_sha256( $dt->strftime('%Y%m%d'), 'AWS4' . $self->{secret} );
175 31 my $k_region = hmac_sha256( $self->{endpoint}, $k_date );
176 31 my $k_service = hmac_sha256( $self->{service}, $k_region );
177 31 my $k_signing = hmac_sha256( 'aws4_request', $k_service );
178  
179 31 my $authz_signature = hmac_sha256_hex( $sts, $k_signing );
180 31 my $authz_credential = join '/', $self->{access_key_id}, $dt->strftime('%Y%m%d'), $self->{endpoint}, $self->{service}, 'aws4_request';
181 31 my $authz_signed_headers = join ';', _headers_to_sign( $req );
182  
183 31 my $authz = "$ALGORITHM Credential=$authz_credential,SignedHeaders=$authz_signed_headers,Signature=$authz_signature";
184 31 return $authz;
185  
186 }
187  
188 =head1 AUTHOR
189  
190 Tim Nordenfur, C<< <tim at gurka.se> >>
191  
192 Maintained by Dan Book, C<< <dbook at cpan.org> >>
193  
194 =cut
195  
196 sub _simplify_uri {
197 93 ▶ my $self = shift;
Subroutine _simplify_uri: called CC=8 SCAR=20.8
198 93 my $orig_uri = shift;
199 93 my @parts = split /\//, $orig_uri;
200 93 my @simple_parts = ();
201 93 for my $part ( @parts ) {
202 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
203 } elsif ( $part eq '..' ) {
204 9 pop @simple_parts;
205 } else {
206 33 ▶ if ( $self->{no_escape_uri} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'no_escape_uri'}) { } 0 33 33
207 0 push @simple_parts, $part;
208 }
209 else {
210 33 push @simple_parts, uri_escape($part);
211 }
212 }
213 }
214 93 my $simple_uri = '/' . join '/', @simple_parts;
215 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
216 93 return $simple_uri;
217 }
218 sub _sort_query_string {
219 93 ▶ return '' unless $_[0];
Subroutine _sort_query_string: called CC=5 SCAR=16.1
Branch: 1 branch
BranchTrueFalseTotal
unless $_[0] 63 30 93
220 30 my @params;
221 30 for my $param ( split /&/, $_[0] ) {
222 my ( $key, $value ) =
223 42 map { tr/+/ /; uri_escape( uri_unescape( $_ ) ) } # escape all non-unreserved chars
224 split /=/, $param;
225 42 ▶ push @params, [$key, (defined $value ? $value : '')];
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 36 6 42
226 }
227 return join '&',
228 42 map { join '=', @$_ }
229 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
230 @params;
231 }
232 sub _trim_whitespace {
233 393 ▶ return map { my $str = $_; $str =~ s/^\s*//; $str =~ s/\s*$//; $str } @_;
Subroutine _trim_whitespace: called CC=1 SCAR=0.0
234 }
235 sub _str_to_timepiece {
236 124 ▶ my $date = shift;
Subroutine _str_to_timepiece: called CC=2 SCAR=6.9
237 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
238 # assume basic ISO 8601, as demanded by AWS
239 93 return Time::Piece->strptime($date, '%Y%m%dT%H%M%SZ');
240 } else {
241 # assume the format given in the AWS4 test suite
242 31 $date =~ s/^.{5}//; # remove weekday, as Amazon's test suite contains internally inconsistent dates
243 31 return Time::Piece->strptime($date, '%d %b %Y %H:%M:%S %Z');
244 }
245 }
246 sub _req_timepiece {
247 124 ▶ my $req = shift;
Subroutine _req_timepiece: called CC=3 SCAR=12.6
248 124 my $x_date = $req->header('X-Amz-Date');
249 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
250 124 ▶ if (!$date) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($date) 0 124 124
251 # No date set by the caller so set one up
252 0 my $piece = Time::Piece::gmtime;
253 0 $req->date($piece->epoch);
254 0 return $piece
255 }
256 124 return _str_to_timepiece($date);
257 }
258  
259 =head1 BUGS
260  
261 Please report any bugs or feature requests to C<bug-Net-Amazon-Signature-V4 at rt.cpan.org>, or through
262 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
263 automatically be notified of progress on your bug as I make changes.
264  
265  
266  
267  
268 =head1 SUPPORT
269  
270 You can find documentation for this module with the perldoc command.
271  
272 perldoc Net::Amazon::Signature::V4
273  
274  
275 You can also look for information at:
276  
277 =over 4
278  
279 =item * RT: CPAN's request tracker (report bugs here)
280  
281 L<https://rt.cpan.org/Public/Dist/Display.html?Name=Net-Amazon-Signature-V4>
282  
283 =item * Source on GitHub
284  
285 L<https://github.com/Grinnz/Net-Amazon-Signature-V4>
286  
287 =item * Search CPAN
288  
289 L<https://metacpan.org/release/Net-Amazon-Signature-V4>
290  
291 =back
292  
293 =head1 LICENSE AND COPYRIGHT
294  
295 This software is copyright (c) 2012 by Tim Nordenfur.
296  
297 This is free software; you can redistribute it and/or modify it under
298 the same terms as the Perl 5 programming language system itself.
299  
300  
301 =cut
302  
303 2 1; # End of Net::Amazon::Signature::V4
↑ Summary