AWS-Signature-V4

 view release on metacpan or  search on metacpan

cpanfile  view on Meta::CPAN

# Crypto for the X.509 variant (RSA and ECDSA signing, key/certificate
# parsing); CryptX provides Crypt::PK::RSA and Crypt::PK::ECC
requires 'CryptX', '0.091';
requires 'Moo', '2.005005';
requires 'namespace::clean', '0.27';
requires 'Ouch', '0.0501';

# Much faster crc32c checksums, used when installed
recommends 'String::CRC32C';

on develop => sub {
   requires 'Template::Perlish', '1.64';
};

on test => sub {
   requires 'Test2::V0';
   requires 'File::Temp';
   requires 'Test::Pod';
};

eg/03-s3-put-object-from-file.pl  view on Meta::CPAN


if ($ENV{DRY_RUN}) {
   say "PUT $url";
   say "$_: $r->{headers}{$_}" for sort keys $r->{headers}->%*;
   exit 0;
}
my $response = HTTP::Tiny->new(verify_SSL => 1)->request(
   PUT => $url,
   {
      headers => \%headers,
      content => sub {
         my $n = read($fh, my $buf, 64 * 1024);
         return $n ? $buf : undef;
      },
   }
);
die "$response->{status} $response->{reason}\n$response->{content}\n"
   unless $response->{success};
say "uploaded $file to s3://$bucket/$key";

eg/05-s3-chunked-upload.pl  view on Meta::CPAN

   while (read($fh, my $buf, $chunk_size)) { $sent += length $chunker->chunk($buf) }
   $sent += length $chunker->finish;
   say "\nbody: $sent bytes (announced: $r->{headers}{'content-length'})";
   exit 0;
}
my $done;
my $response = HTTP::Tiny->new(verify_SSL => 1)->request(
   PUT => $url,
   {
      headers => \%headers,
      content => sub {
         return if $done;
         my $n = read($fh, my $buf, $chunk_size);
         return $chunker->chunk($buf) if $n;
         $done = 1;
         return $chunker->finish;    # last, empty chunk (dies if sizes disagree)
      },
   }
);
die "$response->{status} $response->{reason}\n$response->{content}\n"
   unless $response->{success};

eg/07-rolesanywhere-x509.pl  view on Meta::CPAN

      certificate_file => $ENV{CERT_FILE} // die("CERT_FILE?\n"),
      private_key_file => $ENV{KEY_FILE}  // die("KEY_FILE?\n"),
      (defined $ENV{CHAIN_FILE}   ? (chain_files          => $ENV{CHAIN_FILE})   : ()),
      (defined $ENV{KEY_PASSWORD} ? (private_key_password => $ENV{KEY_PASSWORD}) : ()),
   },
);
say {*STDERR} 'algorithm: ', $signer->algorithm;

# the ARNs are required; only a dry run, which sends nothing, makes do
# with a placeholder just to show the shape of the request
sub arn {
   my ($name, $placeholder) = @_;
   return $ENV{$name} if defined $ENV{$name} && length $ENV{$name};
   die "$name?\n" unless $ENV{DRY_RUN};
   return $placeholder;
}

my $url  = "https://rolesanywhere.$region.amazonaws.com/sessions";
my $body = encode_json({
   trustAnchorArn  => arn(TRUST_ANCHOR_ARN => 'arn:aws:rolesanywhere:...:trust-anchor/...'),
   profileArn      => arn(PROFILE_ARN      => 'arn:aws:rolesanywhere:...:profile/...'),

eg/08-x509-custom-signer.pl  view on Meta::CPAN

use Crypt::PK::RSA;

my $key = Crypt::PK::RSA->new($ENV{KEY_FILE} // die "KEY_FILE?\n");

my $signer = AWS::Signature::V4->new(
   service => 'rolesanywhere',
   region  => 'eu-west-1',
   x509    => {
      key_type         => 'RSA',
      certificate_file => $ENV{CERT_FILE} // die("CERT_FILE?\n"),
      signer           => sub ($bytes) {
         say STDERR 'signer called on ', length($bytes), ' bytes';
         # RSA: PKCS#1 v1.5 over SHA-256. For ECDSA return the DER signature.
         # Raw bytes: decode first a signature that comes in base64 or hex.
         return $key->sign_message($bytes, 'SHA256', 'v1.5');
      },
   },
);

my $r = $signer->sign(
   method => 'GET',

eg/10-s3-content-encoding-probe.pl  view on Meta::CPAN

gzip \$plain, \my $gz or die "gzip failed: $GzipError\n";
my $chunk_size = 64 * 1024;    # one data chunk: the last one, so S3's
my $size       = length $gz;   # 8 KiB minimum does not apply to it
my $chunks     = int($size / $chunk_size) + ($size % $chunk_size ? 1 : 0);

my $http = HTTP::Tiny->new(verify_SSL => 1);
my $base = "https://$bucket.s3.$region.amazonaws.com/";

# HTTP::Tiny adds the Host header itself and refuses to be given one; it
# is signed all the same, and it will have the same value
sub without_host {
   my ($r) = @_;
   my %headers = $r->{headers}->%*;
   delete $headers{host};
   return \%headers;
}

# S3 reports failures as XML; the first two fields are the useful ones.
# HTTP::Tiny never reached it when the status is 599, and then the reason
# (no route, TLS refused, name not resolved) is in the content instead
sub s3_error {
   my ($response) = @_;
   my $content = $response->{content} // '';
   my ($code) = $content =~ m{<Code>([^<]*)</Code>};
   my ($msg)  = $content =~ m{<Message>([^<]*)</Message>};
   return one_line(defined $msg && length $msg ? "$code: $msg" : $code) if defined $code;
   return '' unless ($response->{status} // 0) == 599;
   return one_line($content);
}

# the S3 error code on its own (NoSuchBucket, AccessDenied, ...). Its
# presence is what tells a refusal by S3 apart from a failure that never
# reached it, which is the difference between an answer and a bad run
sub s3_code {
   my ($response) = @_;
   my ($code) = ($response->{content} // '') =~ m{<Code>([^<]*)</Code>};
   return undef unless defined $code && length $code;
   return one_line($code);
}

# the status line comes from the other end as well: HTTP::Tiny takes the
# reason as [^\r\n]*, so it can carry control characters, terminal escapes
# and any length at all, and it goes in the report like everything else
sub status_of {
   my ($response) = @_;
   return one_line(($response->{status} // 0) . ' ' . ($response->{reason} // ''));
}

# every word of this is written by the other end of the connection, and it
# is quoted in a report that gets read as evidence: keep it to one bounded
# line of printable ASCII, so that it cannot forge a line of that report
# (a <Message> holding a newline and "verdict: ..." otherwise would)
sub one_line {
   my ($text) = @_;
   return '' unless defined $text && length $text;
   $text =~ s{\s+}{ }g;
   $text =~ s{[^\x20-\x7E]}{.}g;
   $text =~ s{\A\s+}{};
   $text =~ s{\s+\z}{};
   $text = substr($text, 0, 197) . '...' if length $text > 200;
   return redact($text);
}

# both kinds of error quote the URL or the key back at us, and the report
# is meant to be pasted: keep the bucket and the key out of it
sub redact {
   my ($text) = @_;
   return $text unless defined $text && length $text;
   $text =~ s{\Q$bucket\E}{BUCKET}g;
   $text =~ s{\Q$prefix\E}{KEY-PREFIX/}g;
   return $text;
}

# HTTP::Tiny lowercases header names and gives an array reference when a
# header appears more than once
sub header_of {
   my ($response, $name) = @_;
   my $v = $response->{headers}{$name};
   return '(none)' unless defined $v;
   # also written by the other end, so it goes through the same sieve
   return one_line(ref $v eq 'ARRAY' ? join(',', $v->@*) : $v);
}

my @cases = (
   {name => 'A control', key => $prefix . 'control', extra => {}},
   {name => 'B gzip',    key => $prefix . 'gzip',    extra => {'Content-Encoding' => 'gzip'}},
);

# undef when the key can be used, otherwise why it cannot. This program
# deletes what it uploads, so it must only ever touch keys that hold
# nothing: anything short of a clear "not there" is taken as occupied
sub key_in_the_way {
   my ($key) = @_;
   my $url = $base . $key;
   my $r = $signer->sign(method => 'HEAD', url => $url);
   my $head = $http->request(HEAD => $url, {headers => without_host($r)});
   return undef if ($head->{status} // 0) == 404;
   return 'an object is already there' if $head->{success};
   # without s3:ListBucket, S3 answers HEAD on a key that is not there
   # with 403 rather than 404, so a free key cannot be told from a
   # forbidden one -- and Get/Put/DeleteObject alone, which is all this
   # program needs, is exactly the case where that happens

lib/AWS/Signature/V4.pm  view on Meta::CPAN

         >
      },

      payload => [ qw< body body_fh payload_hash unsigned_payload > ],
      streaming => [ qw< decoded_content_length checksum trailers > ],
   },

   MAX_EPOCH => 253402300799,    # 9999-12-31T23:59:59Z
};

sub _copy ($value) { ref $value eq 'HASH' ? {$value->%*} : $value }

sub _hash_or_undef ($name, $value) {
   fail 400, qq{"$name" must be a hash reference}
      unless !defined $value || ref $value eq 'HASH';
}

# arguments of sign/presign as a hash: name => value pairs or a hash
# reference; undefined values are like missing ones, unknown names an error
sub _args ($what, @args) {
   @args = $args[0]->%* if @args == 1 && ref $args[0] eq 'HASH';
   fail 400, "$what takes name => value pairs or a hash reference" if @args % 2;
   my %args = @args;
   defined $args{$_} or delete $args{$_} for keys %args;

   # go looking for argument names that are outside the allowed ones
   my $allowed = ALLOWED_ARGS->{$what}
      or die "ALLOWED_ARGS does not support <$what>";
   if (my @l = grep { ! $allowed->{$_} } keys(%args)) {
      fail 400, "unsupported for $what: " . _shown_list(@l);
   }
   return %args;
}

sub _check_url ($url) {
   defined $url or fail 400, 'missing parameter "url"';
   fail 400, 'url must be a string' if ref $url;
   fail 400, 'url must be ASCII: percent-encode non-ASCII characters'
      if $url =~ m{[^\x00-\x7F]};
   fail 400, 'url must not contain control characters: percent-encode them'
      if $url =~ m{[\x00-\x1F\x7F]};
   return $url;
}

# an HTTP token (RFC 9110), like header names and methods
sub _is_token ($s) {
   defined $s && !ref $s && $s =~ m{\A[!#\$%&'*+.^_`|~0-9A-Za-z-]+\z};
}

sub _method ($method) {
   fail 400, 'invalid method ' . shown($method) . ': it must be an HTTP token'
      unless _is_token($method);
   return uc $method;
}

sub _is_count ($n) {
   defined $n && !ref $n && $n =~ m{\A (?: 0 | [1-9][0-9]* ) \z}mxs;
}

# headers as a hash or array of pairs, to a hash with lowercase names;
# undefined values are skipped, like missing headers
sub _headers_hash ($in) {
   my @pairs;
   if (ref $in eq 'HASH') {
      @pairs = map { $_ => $in->{$_} } sort keys $in->%*;    # repeatable order
   }
   elsif (ref $in eq 'ARRAY') {
      fail 400, '"headers" as an array reference must hold name => value pairs'
         if $in->@* % 2;
      @pairs = $in->@*;
   }
   elsif (defined $in) {

lib/AWS/Signature/V4.pm  view on Meta::CPAN

      _check_header_value($k, $_) for @values;
      next unless @values;
      $v = join ',', @values;
      $k = lc $k;
      $h{$k} = exists $h{$k} ? "$h{$k},$v" : $v;
   }
   return %h;
}

# so that it cannot change the canonical request
sub _check_header_name ($name) {
   fail 400, 'invalid header name ' . shown($name) unless _is_token($name);
}

# what is wrong with a value that gets signed, if anything: CR, LF and NUL
# would forge lines in the canonical request, and a character beyond a byte
# cannot go on the wire (in a query string _uri_encode would turn it into an
# invalid percent escape, silently mangling e.g. a session token)
sub _bad_value ($value) {
   return 'no CR, LF or NUL' if $value =~ m{[\r\n\0]};
   return 'a byte string, encode characters first' if $value =~ m{[^\x00-\xFF]};
   return undef;
}

# so that it cannot inject headers or lines in the canonical request
sub _check_header_value ($name, $value) {
   my $invalid = ref $value ? 'a string or an array reference of strings'
      : _bad_value($value) // return;
   fail 400, 'invalid value for header ' . shown($name) . ": $invalid";
}

# the same, for what presign signs into the query string instead of headers
sub _check_query_values (@pairs) {
   while (my ($name, $value) = splice @pairs, 0, 2) {
      my $invalid = ref $value ? 'a string' : _bad_value($value // '') // next;
      fail 400, 'invalid value for query parameter ' . shown($name) . ": $invalid";
   }
}

# all the headers to send, including those that the module adds itself
sub _check_header_values ($h) {
   _check_header_value($_, $h->{$_}) for sort keys $h->%*;
}

# sorted, lowercase names of the headers to sign. Always included: host, all
# the x-amz-* headers (AWS wants them signed) and the names in @also
sub _signed_headers ($h, $names, @also) {
   fail 400, '"signed_headers" must be an array reference' unless ref $names eq 'ARRAY';
   my %signed = map { $_ => 1 } 'host', @also, grep { m{\Ax-amz-} } keys $h->%*;
   for my $name ($names->@*) {
      _check_header_name($name);
      $signed{lc $name} = 1;
   }
   for my $name (sort keys %signed) {
      fail 400, 'cannot sign missing header ' . shown($name) unless exists $h->{$name};
   }
   return sort keys %signed;
}

sub _is_sha256 ($hash) { $hash =~ m{\A[0-9a-f]{64}\z}mxs }

# a hex SHA-256 (lowercased), UNSIGNED-PAYLOAD or a STREAMING-* marker
sub _check_payload_hash ($what, $value) {
   if (!ref $value) {
      return lc $value if $value =~ m{\A[0-9A-Fa-f]{64}\z};
      return $value if $value =~ m{\A(?:UNSIGNED-PAYLOAD|STREAMING-[A-Z0-9-]+)\z};
   }
   fail 400, "$what must be a SHA-256 in hex, UNSIGNED-PAYLOAD or a STREAMING-* marker";
}

# the payload hash in the x-amz-content-sha256 header provided by the
# caller, if any; it is put back later, when needed
sub _given_payload_hash ($h) {
   my $given = delete $h->{'x-amz-content-sha256'} // return undef;
   return _check_payload_hash('the x-amz-content-sha256 header', $given);
}

# payload hash from the arguments, undef if they say nothing about it
sub _payload_hash ($args) {
   return _check_payload_hash('"payload_hash"', $args->{payload_hash})
      if defined $args->{payload_hash};
   return 'UNSIGNED-PAYLOAD' if $args->{unsigned_payload};
   return _body_hash($args);
}

# the payload hash from the arguments and the one in the header must agree;
# the default applies if there is neither
sub _agree ($from_args, $given, $default) {
   return $from_args // $default unless defined $given;
   fail 400, 'the x-amz-content-sha256 header does not match the payload'
      if defined $from_args && $from_args ne $given;
   return $given;
}

# hex SHA-256 of the "body" or "body_fh" argument, undef if none is given
sub _body_hash ($args) {
   my $fh = $args->{body_fh};
   fail 400, 'give either "body" or "body_fh", not both'
      if defined $fh && defined $args->{body};
   return _fh_hash($fh) if defined $fh;
   return undef unless defined $args->{body};

   # the hash must match what goes on the wire, so no characters allowed;
   # a copy is made only for internally-UTF-8 strings, never modify input
   my $ref = _body_ref($args);
   return sha256_hex($$ref // '') unless utf8::is_utf8($$ref);
   my $copy = $$ref;
   utf8::downgrade($copy, 1)
      or fail 400, 'body must be a byte string: encode characters first';
   return sha256_hex($copy);
}

sub _is_fh_raw ($fh) {
   my @layers = PerlIO::get_layers($fh, details => 1);
   while (@layers > 0) {
      my ($name, $arg, $flags) = splice(@layers, 0, 3);
      return if ($arg // '') =~ m{ utf | encode }imxs;
      return if ($flags & 0x00008000); # PERLIO_F_UTF8 flag

      # in Windows, crlf is not removed by "<:raw" but just disabled by
      # a flag set to 0. If it's still set to 1 we have a problem.
      #
      # From https://metacpan.org/pod/PerlIO#:crlf

lib/AWS/Signature/V4.pm  view on Meta::CPAN

      #    the defaults, it also acts like the :perlio layer, and removing
      #    the CRLF translation (such as with :raw) will only unset the
      #    CRLF translation flag.
      return if ($name eq 'crlf') && ($flags & 0x00000010); 
   }
   return 'raw!';
}


# the handle is hashed from where it is to its end, then put back there
sub _fh_hash ($fh) {
   openhandle($fh) or fail 400, '"body_fh" must be an open filehandle';

   # I eventually discovered that this protection check actually fails in
   # Windows as the crlf is never really stripped away by mode "<:raw" nor
   # by binmode, it's just "silenced". Moving the test over to a more
   # accurate function.
   fail 400, '"body_fh" must be a binary handle: binmode it'
      unless _is_fh_raw($fh);


   my $pos = tell $fh;
   fail 400, '"body_fh" must be seekable (a file, not a pipe or a socket)'
      unless $pos >= 0 && seek $fh, $pos, 0;
   my $sha = Digest::SHA->new(256);
   eval { $sha->addfile($fh); 1 } or fail 400, qq{"body_fh" cannot be read: $!};
   seek $fh, $pos, 0 or fail 400, qq{"body_fh" cannot be put back where it was: $!};
   return $sha->hexdigest;
}

# names of the trailers: built-in checksum first, then the declared ones
sub _trailer_names ($args) {
   my @names;
   if (defined(my $algo = $args->{checksum})) {
      fail 400, 'unknown checksum ' . shown($algo) . ' (supported: '
         . join(', ', AWS::Signature::V4::Checksum->supported_algorithms) . ')'
         unless AWS::Signature::V4::Checksum->is_supported_algorithm($algo);
      push @names, "x-amz-checksum-$algo";
   }
   my $trailers = $args->{trailers} // [];
   fail 400, '"trailers" must be an array reference' unless ref $trailers eq 'ARRAY';
   for my $name (map { lc($_ // '') } $trailers->@*) {
      _check_trailer_name($name);
      fail 400, "trailer '$name' declared twice" if grep { $_ eq $name } @names;
      push @names, $name;
   }
   return @names;
}

sub _check_trailer_name ($name) {
   fail 400, 'invalid trailer name ' . shown($name) unless $name =~ m{\A[a-z0-9][a-z0-9-]*\z};
}

sub _canonical_query ($query) {
   return '' unless defined $query && length $query;
   my @pairs = map {
      my ($k, $v) = split /=/, $_, 2;
      [_uri_encode(_uri_decode($k)), _uri_encode(_uri_decode($v // ''))];
   } grep { length } split /&/, $query;
   return join '&', map { "$_->[0]=$_->[1]" }
      sort { $a->[0] cmp $b->[0] || $a->[1] cmp $b->[1] } @pairs;
}

sub _uri_encode ($s) {
   $s =~ s{([^A-Za-z0-9\-_.~])}{sprintf '%%%02X', ord $1}gmse;
   return $s;
}

sub _uri_decode ($s) {
   $s =~ s{%([0-9A-Fa-f]{2})}{chr hex $1}gse;
   return $s;
}

# body is either a plain scalar or a reference to one; only in the latter
# case the caller's data is not copied at all
sub _body_ref ($args) {
   my $body = $args->{body};
   return \$args->{body} unless ref $body;
   fail 400, 'body must be a scalar or a reference to a scalar'
      unless ref($body) eq 'SCALAR';
   return $body;
}

# AWS trims and collapses spaces, so ASCII whitespace only (/a): with
# unicode_strings, \s would also take the bytes 0xA0 and 0x85 of UTF-8 text
sub _trim ($v) {
   $v =~ s{\A\s+|\s+\z}{}gmxa;  # remove leading/trailing whitespaces
   $v =~ s{\s+}{ }gas;          # normalize internal whitespaces
   return $v;
}

# (host, path, query) of a url; the host is lowercased and the port is
# removed if it is the default one, as user agents do before sending it
sub _split_url ($url) {
   # every part is optional, so this always matches
   my ($scheme, $auth, $path, $query) =
      $url =~ m{\A (?: ([A-Za-z][A-Za-z0-9+.-]*) :// ([^/?\#]*) )?
                   ([^?\#]*) (?: \? ([^\#]*) )? }x;
   fail 400, 'url path must start with "/": give an absolute url, or a path with a Host header'
      if length $path && $path !~ m{\A/};
   fail 400, 'url query must not contain "+": write %20 for a space, %2B for a plus sign'
      if defined $query && $query =~ m{\+};
   return (undef, $path, $query) unless defined $auth && length $auth;

lib/AWS/Signature/V4.pm  view on Meta::CPAN

      fail 400, "invalid port: $port" if $port < 1 || $port > 65535;
      my $lcscheme = lc($scheme);
      my $default = $lcscheme eq 'https' ? 443
         : $lcscheme eq 'http'           ? 80
         :                                 0;
      $host .= ':' . $port if $port != $default;
   }
   return ($host, $path, $query);
}

sub _shown_list (@list) {
   return join ', ',
      map { join '', q{"}, shown($_), q{"} }
      sort { $a cmp $b } @list;
}


use namespace::clean;    # imported or plain functions must not become methods


has service => (is => 'ro');
has region  => (is => 'ro');

# credentials: {access_key_id, secret_access_key, session_token?}
has credentials => (is => 'ro', coerce => \&_copy, isa => sub { _hash_or_undef(credentials => @_) });

# Certificate-based variant, as used by IAM Roles Anywhere.
#   certificate / certificate_file: PEM or DER text, or path of a file with it
#   chain / chain_files: optional arrayref of PEM/DER intermediate certificates,
#                or of paths of files with them; a PEM item can be a bundle.
#                chain can also be a plain string: a PEM-encoded bundle, and
#                chain_files a plain string: the path of one file
#   key_type:    'RSA' or 'ECDSA'
#   signer:      sub ($bytes_to_sign) -> signature (DER for ECDSA, PKCS#1 v1.5
#                for RSA), computed with SHA-256; or, alternatively,
#   private_key_file / private_key: PEM or DER key (path or content), signed
#                with CryptX; private_key_password if it is encrypted
has x509 => (is => 'ro', coerce => \&_copy, isa => sub { _hash_or_undef(x509 => @_) });

# S3 is the odd one out: this is the only place that knows how to tell. S3
# Object Lambda, S3 on Outposts and S3 Express sign with names of their own,
# under the same rules.
has _is_s3 => (is => 'lazy', init_arg => undef);
sub _build__is_s3 ($self) { $self->service =~ m{\As3(?:-object-lambda|-outposts|express)?\z} }

has double_encode  => (is => 'ro', lazy => 1, default => sub ($self) { !$self->_is_s3 });
has normalize_path => (is => 'ro', lazy => 1, default => sub ($self) { !$self->_is_s3 });
has payload_header => (is => 'ro', lazy => 1, default => sub ($self) { $self->_is_s3 });

# FIXME review this decision: "undef" in Perl has a history of meaning
# "false" but here we're saying that it means "do the default".
# an undefined option is like a missing one: the default applies
around BUILDARGS => sub ($orig, $class, @args) {
   my $args = $class->$orig(@args);
   defined $args->{$_} or delete $args->{$_}
      for qw< double_encode normalize_path payload_header >;
   return $args;
};

# The variant in use, credentials or x509, which knows how to sign and what
# goes with the request: see AWS::Signature::V4::Credentials and ::X509
has _auth => (is => 'lazy', init_arg => undef);

sub BUILD ($self, $args) {
   for my $name (qw< service region >) {
      my $value = $self->$name;
      defined($value) || fail 400, qq{missing parameter "$name"};
      fail 400, qq{invalid "$name" } . shown($value)
         . ': only letters, digits, ".", "_" and "-" are allowed'
         unless $value =~ m{\A[-A-Za-z0-9._]+\z};
   }

   # make sure the caller provides us *exactly* one of credentials/X509
   my $x509_params = $self->x509;

lib/AWS/Signature/V4.pm  view on Meta::CPAN


   $self->_auth;    # force building and fail fast

   # after using the parameters, we get rid of sensitive data in the input
   # hash for X509
   delete($x509_params->{$_}) for qw< private_key private_key_password >;

   return;
}

sub _build__auth ($self) {
   return $self->credentials
      ? AWS::Signature::V4::Credentials->new($self->credentials->%*)
      : AWS::Signature::V4::X509->new($self->x509->%*);
}

sub algorithm ($self) { $self->_auth->algorithm }

# sign(method => ..., url => ..., headers => ..., body => ..., time => ...)
# Returns a hashref:
#   headers:        all headers to set on the request (name => value)
#                   including Authorization, X-Amz-Date, Host if missing...
#   authorization:  value of the Authorization header
#   signature, canonical_request, string_to_sign, signed_headers, scope
sub sign ($self, @args) {
   my %args = _args(sign => @args);

   # some arguments apply to the "payload" variant and some to the
   # "streaming" variant only, we need some more input validation.
   # $not_allowed below collects the name of the parameter that are not
   # allowed for the variant that is requested.
   my $streaming = $args{streaming};
   my $not_allowed = ALLOWED_ARGS->{$streaming ? 'payload' : 'streaming'};
   my @misplaced = grep { exists $args{$_} } $not_allowed->@*;
   fail 400, qq{"$misplaced[0]" }

lib/AWS/Signature/V4.pm  view on Meta::CPAN

      checksum => $args{checksum}, trailer_names => \@trailer_names,
   ) if $streaming;
   return $r;
}

# presign(method => 'GET', url => ..., expires => 3600, time => ...)
# Returns a hashref:
#   url:            the URL, with the signature in its query string
#   headers:        headers that the client must send with it (Host, ...)
#   signature, canonical_request, string_to_sign, signed_headers, scope
sub presign ($self, @args) {
   my %args = _args(presign => @args);
   my $method = _method($args{method} // 'GET');
   my ($h, $path, $query, $amzdate, $scope) = $self->_request(\%args);

   my $expires = $args{expires} // 3600;
   fail 400, 'expires must be an integer between 1 and 604800 seconds'
      unless $expires =~ m{\A[0-9]+\z} && $expires >= 1 && $expires <= 604800;

   for my $pair (split m{&}, $query // '') {
      my ($name) = split m{=}, $pair, 2;

lib/AWS/Signature/V4.pm  view on Meta::CPAN

   # whatever is not allowed in a URL path (e.g. a space) is percent-encoded
   my ($prefix) = $args{url} =~ m{\A([^?\#]*)};
   $prefix =~ s{([^A-Za-z0-9\-._~!\$&'()*+,;=:@/%\[\]])}{sprintf '%%%02X', ord $1}ge;
   $r->{url} = "$prefix?$canonical_query&X-Amz-Signature=$r->{signature}";
   $r->{headers} = $h;
   return $r;
}

# pieces of the request that sign and presign have in common: the headers
# (with host), the path and query from the url, the date and the scope
sub _request ($self, $args) {
   my ($host, $path, $query) = _split_url(_check_url($args->{url}));
   my %h = _headers_hash($args->{headers});
   $h{host} //= $host;
   length($h{host} // '')
      or fail 400, 'url has no host: give an absolute url or a Host header';

   my $epoch = $args->{time} // time;
   fail 400, 'time must be an epoch in seconds, e.g. from time()'
      unless !ref $epoch && $epoch =~ m{\A[0-9]+(?:\.[0-9]*)?\z} && $epoch <= MAX_EPOCH;
   my $amzdate = strftime('%Y%m%dT%H%M%SZ', gmtime int $epoch);
   my $scope   = join '/', substr($amzdate, 0, 8), $self->region, $self->service, 'aws4_request';
   return (\%h, $path, $query, $amzdate, $scope);
}

# canonical request, string to sign and signature, as returned to the caller
sub _signed ($self, $method, $path, $canonical_query, $h, $signed, $payload_hash, $amzdate, $scope) {
   my $signed_headers = join ';', $signed->@*;
   my $canonical_request = join "\n",
      $method,
      $self->_canonical_path($path),
      $canonical_query,
      join('', map { "$_:" . _trim($h->{$_}) . "\n" } $signed->@*),    # ends with blank line
      $signed_headers,
      $payload_hash;
   my $string_to_sign = join "\n",
      $self->algorithm, $amzdate, $scope, sha256_hex($canonical_request);

lib/AWS/Signature/V4.pm  view on Meta::CPAN

      signature         => $self->_auth->signature($scope, $string_to_sign),
      signed_headers    => $signed_headers,
      scope             => $scope,
      canonical_request => $canonical_request,
      string_to_sign    => $string_to_sign,
   };
}

# size of an aws-chunked body: every chunk but the last one is $chunk_size
#   signed => 1 (default) or 0, checksum => $algo, trailers => {name => length}
sub encoded_length ($class, $decoded, $chunk_size, @args) {
   fail 400, 'the decoded size must be a non-negative integer'
      unless _is_count($decoded);
   fail 400, 'the chunk size must be a positive integer'
      unless _is_count($chunk_size) && $chunk_size > 0;

   fail 400, 'encoded_length named options must be name => value pairs' if @args % 2;
   my %opts = _args(encoded_length => @args);

   my $signed = exists($opts{signed}) ? ($opts{signed} || 0) : 1;
   fail 400, 'signed must be false, 1, "signed", or "unsigned"'

lib/AWS/Signature/V4.pm  view on Meta::CPAN

   for my $given (sort keys $declared->%*) {
      my $name = lc $given;
      _check_trailer_name($name);
      # sign() refuses the same repetition, so do not count a line twice
      fail 400, "trailer '$name' declared twice" if $seen{$name}++;
      fail 400, 'the length of trailer ' . shown($given) . ' must be a non-negative integer'
         unless _is_count($declared->{$given});
      $trailer += length($name) + 1 + $declared->{$given} + 2;
   }

   my $chunk = sub ($size) {    # everything around the data of a chunk
      length(sprintf '%x', $size) + ($signed ? 17 + 64 : 0) + 2 + 2;
   };
   my $total = 0;
   my $full = int($decoded / $chunk_size);
   $total += $full * ($chunk->($chunk_size) + $chunk_size);
   my $rest = $decoded - $full * $chunk_size;
   $total += $chunk->($rest) + $rest if $rest;

   # final chunk: "0[;chunk-signature=..]\r\n", trailers, [signature line,] "\r\n"
   $total += 1 + ($signed ? 17 + 64 : 0) + 2 + $trailer + 2;
   $total += length('x-amz-trailer-signature') + 1 + 64 + 2 if $signed && $trailer;
   return $total;
}

# the path is empty or starts with "/", see _split_url
sub _canonical_path ($self, $path) {
   $path = '/' unless length $path;
   my $trailing = $path =~ m{/\z} && $path ne '/';
   my @parts = split m{/}, $path, -1;
   shift @parts;    # leading empty item, before the first /
   pop @parts if @parts && $parts[-1] eq '';    # trailing, re-added below

   if ($self->normalize_path) {
      my @out;
      for my $p (@parts) {
         next if $p eq '' || $p eq '.';

lib/AWS/Signature/V4/Checksum.pm  view on Meta::CPAN


use namespace::clean;

has algorithm => (is => 'ro', required => 1);

# running state: the CRCs keep a number, the SHA ones a Digest::SHA object
has _crc => (is => 'rw', lazy => 1, builder => 1);
has _sha => (is => 'lazy');

# the algorithm is given as the only, positional, argument: new('crc32')
around BUILDARGS => sub ($orig, $class, @args) {
   return {algorithm => $args[0]} if @args == 1 && !ref $args[0];
   return $class->$orig(@args);
};

sub _build__crc ($self) { $self->algorithm eq 'crc32c' ? 0xFFFFFFFF : 0 }
sub _build__sha ($self) { Digest::SHA->new($self->algorithm eq 'sha1' ? 1 : 256) }

sub encoded_size ($class, $algo) { 4 * int((SIZE_FOR->{$algo} + 2) / 3) }

sub add ($self, $ref) {    # $ref: reference to a byte string
   fail 400, 'checksum data must be a reference to a byte string'
      unless ref $ref eq 'SCALAR' && defined $$ref;
   utf8::is_utf8($$ref) && !utf8::downgrade(my $copy = $$ref, 1)
      and fail 400, 'checksum data must be a byte string: encode characters first';
   my $algo = $self->algorithm;
   if ($algo eq 'crc32') {
      $self->_crc(Compress::Raw::Zlib::crc32($$ref, $self->_crc));
   }
   elsif ($algo eq 'crc32c') {
      $self->_crc(_crc32c($self->_crc, $ref));
   }
   else { $self->_sha->add($$ref) }
   return $self;
}

# register after the data; String::CRC32C wants and gives it inverted
sub _crc32c ($crc, $ref) {
   if (my $xs = CRC32C_XS) {
      return $xs->($$ref, $crc ^ 0xFFFFFFFF) ^ 0xFFFFFFFF;
   }

   state $T0 = [
      map {
         my $c = $_;
         $c = ($c & 1) ? (($c >> 1) ^ 0x82F63B78) : ($c >> 1) for 1 .. 8;
         $c;
      } 0 .. 255

lib/AWS/Signature/V4/Checksum.pm  view on Meta::CPAN

         $crc = $T3->[$c & 0xFF]
                ^ $T2->[($c >> 8) & 0xFF]
                ^ $T1->[($c >> 16) & 0xFF]
                ^ $T0->[$c >> 24];
      }
   }
   $crc = $T0->[($crc ^ $_) & 0xFF] ^ ($crc >> 8) for unpack 'C*', substr $$ref, $words;
   return $crc;
}

sub base64 ($self) {
   my $algo = $self->algorithm;
   my $raw =
        $algo eq 'crc32'  ? pack('N', $self->_crc)
      : $algo eq 'crc32c' ? pack('N', $self->_crc ^ 0xFFFFFFFF)
      :                     $self->_sha->digest;
   return encode_base64($raw, '');
}

sub is_supported_algorithm ($co, $name) { exists(SIZE_FOR->{$name}) }

sub supported_algorithms { sort { $a cmp $b } keys(SIZE_FOR->%*) }

1;

lib/AWS/Signature/V4/Chunker.pm  view on Meta::CPAN

has amzdate       => (is => 'ro');
has scope         => (is => 'ro');

# The signing key, for signed chunks only, can sign any request for the same
# service, region and day: it is kept in a closure, so that no accessor gives
# it back and dumping the object does not show it. The closure can still sign
# with it, so the chunker is no safer to share than the signer.
has _mac => (
   is       => 'ro',
   init_arg => 'key',
   coerce   => sub ($key) {
      ref $key eq 'CODE' ? $key : sub ($data) { hmac_sha256_hex($data, $key) };
   },
);

# signature of the previous chunk: the chain must not be changed from outside
has _previous => (is => 'rw', init_arg => 'previous');
has expected      => (is => 'ro', required => 1);    # declared size of the data
has checksum      => (is => 'ro');    # name of the built-in checksum, if any
has trailer_names => (is => 'ro', default => sub { [] });

has _seen => (is => 'rw', init_arg => undef, default => 0);
has _done => (is => 'rw', init_arg => undef, default => 0);
has _sum  => (is => 'lazy', init_arg => undef);

sub BUILD ($self, $args) {
   fail 500, 'signed chunks need a "key"' if $self->signed && !$self->_mac;
   return;
}

sub _build__sum ($self) {
   my $algo = $self->checksum;
   return defined $algo ? AWS::Signature::V4::Checksum->new($algo) : undef;
}

sub _sign ($self, $data_ref) {
   my $string_to_sign = join "\n", 'AWS4-HMAC-SHA256-PAYLOAD',
      $self->amzdate, $self->scope, $self->_previous,
      sha256_hex(''), sha256_hex($$data_ref);
   return $self->_previous($self->_mac->($string_to_sign));
}

# encoded chunk for the data (a byte string or a reference to one)
sub chunk ($self, $data) {
   fail 400, 'chunker already finished' if $self->_done;
   fail 400, 'chunk must be a byte string or a reference to one'
      if ref $data && ref $data ne 'SCALAR';
   my $ref = ref $data ? $data : \$data;
   my $len = length($$ref) // 0;
   fail 400, 'empty chunk: call finish() to terminate the stream' unless $len;
   _is_bytes($ref) or fail 400, 'chunk must be a byte string: encode characters first';
   my $seen = $self->_seen + $len;
   fail 400, "more data than the declared @{[ $self->expected ]} bytes"
      if $seen > $self->expected;
   $self->_seen($seen);
   $self->_sum->add($ref) if $self->_sum;
   my $head = $self->signed
      ? sprintf('%x;chunk-signature=%s', $len, $self->_sign($ref))
      : sprintf('%x', $len);
   return "$head\r\n" . $$ref . "\r\n";
}

# the final, empty chunk, followed by the trailers if any; the values of the
# trailers that were declared with "trailers" are passed by name, in any case
sub finish ($self, %given) {
   fail 400, 'chunker already finished' if $self->_done;
   fail 400, "got @{[ $self->_seen ]} bytes instead of the declared @{[ $self->expected ]}"
      if $self->_seen != $self->expected;
   my %values;
   for my $name (sort keys %given) {
      fail 400, "trailer '" . shown(lc $name) . "' given twice" if exists $values{lc $name};
      $values{lc $name} = $given{$name};
   }

   # all checks come before the checksum is taken, which is not repeatable,

lib/AWS/Signature/V4/Chunker.pm  view on Meta::CPAN

         sha256_hex(join '', map { "$_\n" } @lines);
      my $tsig = $self->_mac->($string_to_sign);
      $body = "0;chunk-signature=$sig\r\n${trailers}x-amz-trailer-signature:$tsig\r\n\r\n";
   }
   $self->_done(1);
   return $body;
}

# true if the string holds only bytes, even if it is stored as UTF-8; it is
# passed by reference, so that big chunks are copied only when they are UTF-8
sub _is_bytes ($ref) {
   return !utf8::is_utf8($$ref) || utf8::downgrade(my $copy = $$ref, 1);
}

1;

lib/AWS/Signature/V4/Credentials.pm  view on Meta::CPAN

use Moo;
use AWS::Signature::V4::Error qw< fail shown >;
use Digest::SHA qw< hmac_sha256 hmac_sha256_hex >;
use experimental qw< signatures >;
use namespace::clean;

# The credentials-based variant (AWS4-HMAC-SHA256). The options are the ones
# of the "credentials" option of AWS::Signature::V4.
has [qw< access_key_id secret_access_key session_token >] => (is => 'ro');

sub BUILD ($self, $args) {
   if (my ($name) = sort(grep { !m{\A(?:access_key_id|secret_access_key|session_token)\z} } keys $args->%*)) {
      fail 400, 'unknown option "' . shown($name) . '" in credentials';
   }
   for my $name (qw< access_key_id secret_access_key >) {
      my $value = $self->$name;    # empty is like missing, AWS would refuse it
      defined $value && length $value or fail 400, "missing credentials/$name";
   }
   return;
}

# ---- what AWS::Signature::V4 wants from a variant --------------------------

sub algorithm ($self) { 'AWS4-HMAC-SHA256' }

# identifies who signs, in the Credential part of the authorization
sub credential_id ($self) { $self->access_key_id }

# the key derived from the secret, for a scope like "20150830/us-east-1/iam/aws4_request"
sub signing_key ($self, $scope) {
   my ($date, $region, $service, $terminator) = split m{/}, $scope, 4;
   my $key = 'AWS4' . $self->secret_access_key;
   $key = hmac_sha256($_, $key) for $date, $region, $service, $terminator;
   return $key;
}

# hex signature of the string to sign
sub signature ($self, $scope, $string_to_sign) {
   return hmac_sha256_hex($string_to_sign, $self->signing_key($scope));
}

# what goes with the request besides the signature, as (name => value) pairs
sub extra_fields ($self) {
   my $token = $self->session_token;    # empty, e.g. from an empty variable: none
   return defined $token && length $token ? ('X-Amz-Security-Token' => $token) : ();
}

# signed chunks need the derived key
sub can_sign_chunks ($self) { 1 }

1;

lib/AWS/Signature/V4/Error.pm  view on Meta::CPAN

# this distribution are skipped when Ouch looks for the culprit.
$Carp::Internal{$_}++ for qw<
   AWS::Signature::V4 AWS::Signature::V4::Checksum
   AWS::Signature::V4::Chunker AWS::Signature::V4::Credentials
   AWS::Signature::V4::Error AWS::Signature::V4::X509
>;

# 400 for what the caller provided, 500 for problems inside the module;
# everything is passed down to ouch(), the optional third argument included.
# No "goto": it would drop the "local" before ouch() gets to build the trace.
sub fail {
   local $Carp::MaxArgNums = -1;    # the trace must not hold secrets
   Ouch::ouch(@_);
}

# caller input, made safe to put in a message: anything that is not printable
# ASCII is escaped, so that it cannot forge lines in a log
sub shown {
   my ($value) = @_;
   return 'undef' unless defined $value;
   return $value =~ s{([^\x20-\x7E])}{sprintf '\\x{%X}', ord $1}ger;
}

1;

lib/AWS/Signature/V4/X509.pm  view on Meta::CPAN

package AWS::Signature::V4::X509;
use v5.24;
use Moo;
use experimental qw< signatures >;
use MIME::Base64 qw< encode_base64 decode_base64 >;
use Math::BigInt;

use AWS::Signature::V4::Error qw< fail shown >;

# a plain string or an arrayref of plain strings => arrayref
sub _items ($value, $name) {
   $value = [$value] unless ref $value;
   ref $value eq 'ARRAY'
      or fail 400, "x509/$name must be a string or an array reference";
   for my $item ($value->@*) {
      fail 400, "x509/$name must hold strings" if !defined $item || ref $item;
   }
   return $value;
}

sub _b64 ($der) { encode_base64($der, '') }

# ---- X.509 helpers (no external dependencies) ------------------------------

sub _slurp ($file) {
   open my $fh, '<:raw', $file or fail 400, 'open(' . shown($file) . "): $!";
   local $/;
   my $data = <$fh>;
   close $fh;
   return $data;
}

sub _to_ders ($cert) {    # PEM bundles hold many certificates
   return _check_der($cert) unless $cert =~ m{-----BEGIN};
   my @ders = map { decode_base64($_) }
      $cert =~ m{-----BEGIN CERTIFICATE-----(.*?)-----END CERTIFICATE-----}sg;
   @ders or fail 400, 'no CERTIFICATE block in PEM';
   return map { _check_der($_) } @ders;
}

sub _to_der ($cert) {
   return _check_der($cert) unless $cert =~ m{-----BEGIN};
   $cert =~ m{-----BEGIN CERTIFICATE-----(.*?)-----END CERTIFICATE-----}s
      or fail 400, 'no CERTIFICATE block in PEM';
   return _check_der(decode_base64($1));
}

# a certificate is a DER SEQUENCE that fits exactly in the data
sub _check_der ($der) {
   my ($tag, undef, $end) = _tlv($der, 0);
   fail 400, 'not a DER-encoded certificate'
      unless $tag == 0x30 && $end == length $der;
   return $der;
}

# read one DER TLV at $off => (tag, content_start, content_end)
sub _tlv ($der, $off) {
   my $max = length $der;
   $off + 2 <= $max or fail 400, 'truncated certificate';
   my $tag = ord substr $der, $off++, 1;
   my $len = ord substr $der, $off++, 1;
   if ($len & 0x80) {    # long form, DER wants it minimal and definite
      my $n = $len & 0x7F;
      fail 400, 'not a DER-encoded certificate' if $n == 0 || $n > 4;
      $off + $n <= $max or fail 400, 'truncated certificate';
      $len = 0;
      $len = ($len << 8) | ord substr($der, $off++, 1) for 1 .. $n;
      fail 400, 'not a DER-encoded certificate'
         if $len < 0x80 || $len < 1 << 8 * ($n - 1);
   }
   $off + $len <= $max or fail 400, 'truncated certificate';
   return ($tag, $off, $off + $len);
}

# Certificate ::= SEQ { tbs SEQ { [0] version?, INTEGER serial, ... }, ... }
sub _certificate_serial ($der) {
   my (undef, $cs) = _tlv($der, 0);
   my (undef, $ts) = _tlv($der, $cs);
   my ($tag, $s, $e) = _tlv($der, $ts);
   ($tag, $s, $e) = _tlv($der, $e) if $tag == 0xA0;    # skip explicit version
   fail 400, 'cannot find certificate serial number' unless $tag == 0x02;
   return Math::BigInt->from_hex(unpack 'H*', substr $der, $s, $e - $s)
      ->bstr;   # DER integers here are positive; leading 0x00 is harmless
}

# The error of CryptX, without the location and the backtrace that Carp adds
# when verbose (the arguments in it may hold the password), escaped as caller
# input because it can hold the file name.
sub _clean_error ($e) {
   $e =~ s{\n\t.*}{}s;    # the backtrace lines start with a tab
   $e =~ s{\s+at \S+ line \d+\.?\s*\z}{};
   return shown($e =~ s{\A\s+|\s+\z}{}gr);
}

# $key is a file name or a scalar reference to the PEM text
sub _cryptx_signer ($algo, $key, $password = undef) {
   my $class = $algo eq 'RSA' ? 'Crypt::PK::RSA' : 'Crypt::PK::ECC';
   eval "require $class; 1" or fail 500, "cannot load $class";
   my @args = ($key, defined $password ? ($password) : ());
   my $pk = eval {
      # no backtrace, e.g. from -MCarp=verbose or Carp::Always, with the password
      local $Carp::Verbose = 0;
      local $Carp::MaxArgNums = -1;
      local $SIG{__DIE__};
      $class->new(@args);
   } // fail 400, "cannot load the private key: " . _clean_error($@);
   fail 400, 'the key is not a private key' unless $pk->is_private;
   return $algo eq 'RSA'
      ? sub ($bytes) { $pk->sign_message($bytes, 'SHA256', 'v1.5') }
      : sub ($bytes) { $pk->sign_message($bytes, 'SHA256') };
}

use namespace::clean;

# The certificate-based variant, as used by IAM Roles Anywhere. The options
# are the ones of the "x509" option of AWS::Signature::V4:
#   certificate / certificate_file: PEM or DER text, or path of a file with it;
#                only the first certificate of a PEM bundle is used
#   chain / chain_files: optional arrayref of PEM/DER intermediate certificates,
#                or of paths of files with them; a PEM item can be a bundle.
#                chain can also be a plain string: a PEM-encoded bundle, and
#                chain_files a plain string: the path of one file
#   key_type:    'RSA' or 'ECDSA'
#   serial:      the serial number of the certificate, if it cannot be found
#   signer:      sub ($bytes_to_sign) -> raw signature bytes (DER for ECDSA,
#                PKCS#1 v1.5 for RSA), computed with SHA-256; or, alternatively,
#   private_key_file / private_key: PEM or DER key (path or content, the
#                content wins), signed with CryptX; private_key_password if it
#                is encrypted
has [qw<
   key_type certificate certificate_file chain chain_files serial signer
   private_key_file
>] => (is => 'ro');

# the key text and its password are secrets, only needed to load the key:

lib/AWS/Signature/V4/X509.pm  view on Meta::CPAN


# Derived from the options above. Lazy, so that each builder can use the
# others without depending on the order in which the constructor sets things
# up; BUILD forces them all, so that a bad certificate, chain or key is
# reported by new() and not by the first signature.
#
# **NOTE**: to add one, add its name here and write its builder.
my @DERIVED = qw< algorithm credential_id _chain _der _signer _type >;
has $_ => (is => 'lazy', init_arg => undef) for @DERIVED;

sub BUILD ($self, $args) {
   my %known = map { $_ => 1 } qw<
      key_type certificate certificate_file chain chain_files serial signer
      private_key_file private_key private_key_password
   >;
   if (my ($name) = sort(grep { !$known{$_} } keys $args->%*)) {
      fail 400, 'unknown option "' . shown($name) . '" in x509';
   }
   for my $name (@DERIVED) {    # not "for (...)": builders may use $_
      $self->$name;
   }

   # we don't need private key material past this point, so we get rid
   # of it immediately. Of course it may still linger in memory depending
   # on garbage collection.
   $self->_clear_private_key;
   $self->_clear_private_key_password;
   return;
}

sub _build__type ($self) {
   my $type = uc($self->key_type // fail 400, 'missing x509/key_type');
   fail 400, 'x509/key_type must be RSA or ECDSA, got ' . shown($type)
      unless $type eq 'RSA' || $type eq 'ECDSA';
   return $type;
}

sub _build_algorithm ($self) { 'AWS4-X509-' . $self->_type . '-SHA256' }

sub _build__der ($self) {
   my $cert = $self->certificate;
   if (!defined $cert && defined $self->certificate_file) {
      $cert = _slurp($self->certificate_file);
   }
   defined $cert or fail 400, 'x509 needs "certificate" or "certificate_file"';
   return _to_der($cert);
}

sub _build__chain ($self) {
   my $chain = $self->chain;
   if (!defined $chain && defined $self->chain_files) {
      my $files = _items($self->chain_files, 'chain_files');    # a single path or an arrayref
      $chain = [map { _slurp($_) } $files->@*];
   }
   if (defined $chain && !ref $chain) {    # a plain string is a PEM bundle
      $chain =~ m{-----BEGIN CERTIFICATE-----}
         or fail 400, 'x509/chain as a string must be PEM-encoded';
   }
   return [map { _to_ders($_) } _items($chain // [], 'chain')->@*];
}

sub _build_credential_id ($self) {
   return $self->serial // _certificate_serial($self->_der);
}

sub _build__signer ($self) {
   my $type = $self->_type;
   my $signer = $self->signer;
   fail 400, '"signer" must be a code reference'
      if defined $signer && ref $signer ne 'CODE';
   if (!$signer && defined $self->_private_key) {    # the content wins, as for certificate
      my $key = $self->_private_key;    # CryptX wants a reference for a PEM/DER text
      $signer = _cryptx_signer($type, \$key, $self->_private_key_password);
   }
   elsif (!$signer && defined $self->private_key_file) {
      $signer = _cryptx_signer($type, $self->private_key_file, $self->_private_key_password);
   }
   return $signer
      // fail 400, 'x509 needs one of "signer", "private_key_file", "private_key"';
}

# ---- what AWS::Signature::V4 wants from a variant --------------------------

# hex signature of the string to sign; the scope is not used here
sub signature ($self, $scope, $string_to_sign) {
   my $sig = $self->_signer->($string_to_sign);
   fail 400, 'the x509 signer returned no signature'
      unless defined $sig && !ref $sig && length $sig;
   utf8::downgrade($sig, 1)
      or fail 400, 'the x509 signer returned a string with wide characters';
   return unpack 'H*', $sig;
}

# what goes with the request besides the signature, as (name => value) pairs
sub extra_fields ($self) {
   my $chain = $self->_chain;
   return (
      'X-Amz-X509' => _b64($self->_der),
      ($chain->@* ? ('X-Amz-X509-Chain' => join ',', map { _b64($_) } $chain->@*) : ()),
   );
}

# No derived key, so no signed chunks. This is stated twice, on purpose:
# AWS::Signature::V4 asks can_sign_chunks() up front, to refuse the request
# before doing anything else, and signing_key() is what fails if somebody
# asks for the key anyway. If this ever changes, change BOTH, and the
# corresponding tests in t/variants.t.
sub can_sign_chunks ($self) { 0 }
sub signing_key ($self, $scope) {
   fail 400, 'signed streaming needs the credentials variant, not x509';
}

1;

script/aws-iam-ra  view on Meta::CPAN

   say {*STDERR} $response->{content};    # this says what went wrong
   die "the request failed\n";
}
else {
   my $data = decode_json($response->{content});
   $data = $data->{credentialSet}[0]{credentials}
      unless $config->{full};
   say {*STDOUT} JSON::PP->new->ascii->canonical->pretty->encode($data);
}

sub get_options ($specs, @args) {
   my (%cmdline, %environment, %default);
   my @cmdline_options = qw< help! man! usage! version! >;
   my @required;
   for my $spec ($specs->@*) {
      my ($optnames, $default, $env_var, $required) =
        ref $spec
        ? $spec->@{qw< getopt default environment required >}
        : ($spec, undef, undef, undef);
      push @cmdline_options, $optnames;
      my $name = $optnames =~ s{[^-\w].*}{}rmxs;

script/aws-iam-ra  view on Meta::CPAN

   pod2usage(-verbose => 2) if $cmdline{man};

   my %overall = (%default, %environment, %cmdline);
   if (my @missing = grep { ! exists($overall{$_}) } @required) {
      my $list = join ', ', @missing;
      pod2usage(message => "missing: $list", -verbose => 99,
         -sections => ' ');
   }

   return bless {%overall, _args => \@args}, __PACKAGE__;
} ## end sub get_options

__END__

=pod

=encoding utf-8

=head1 NAME

aws-iam-ra - get credentials from AWS IAM Roles Anywhere

t/basic.t  view on Meta::CPAN

   skip 'openssl not available', 20 if system("openssl version >/dev/null 2>&1");
   for my $alg (qw< RSA ECDSA >) {
      my $genkey = $alg eq 'RSA'
         ? "openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048"
         : "openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256";
      system("$genkey -out $dir/$alg.key 2>/dev/null") == 0 or die "genkey";
      system("openssl req -new -x509 -key $dir/$alg.key -subj /CN=test "
         . "-days 2 -out $dir/$alg.pem 2>/dev/null") == 0 or die "req";
      system("openssl x509 -in $dir/$alg.pem -pubkey -noout > $dir/$alg.pub") == 0
         or die "pubkey";
      my $verifies = sub ($string_to_sign, $signature) {
         open my $o, '>:raw', "$dir/sts" or die; print {$o} $string_to_sign; close $o;
         open my $g, '>:raw', "$dir/sig" or die; print {$g} pack 'H*', $signature; close $g;
         system("openssl dgst -sha256 -verify $dir/$alg.pub -signature $dir/sig $dir/sts >/dev/null") == 0;
      };
      open my $fh, '<', "$dir/$alg.pem" or die; my $pem = do { local $/; <$fh> };
      my $x = AWS::Signature::V4->new(
         service => 'rolesanywhere', region => 'eu-west-1',
         x509 => {key_type  => $alg, certificate => $pem,
                  private_key_file => "$dir/$alg.key"},
      );

t/canonical.t  view on Meta::CPAN

use Test2::V0;
use FindBin '$Bin';
use lib "$Bin/../lib";
use AWS::Signature::V4;
use Digest::SHA qw< sha256_hex >;

my %cred = (access_key_id => 'AKID', secret_access_key => 'SECRET');
my $std = AWS::Signature::V4->new(service => 'service', region => 'us-east-1', credentials => {%cred});
my $s3  = AWS::Signature::V4->new(service => 's3',      region => 'us-east-1', credentials => {%cred});

sub canon ($signer, $url, %rest) {
   my $r = $signer->sign(method => 'GET', url => $url, time => 1440938160, %rest);
   my @lines = split /\n/, $r->{canonical_request}, -1;
   return ($lines[1], $lines[2], $r);    # path, query, whole result
}
sub path_of  ($signer, $url) { (canon($signer, $url))[0] }
sub query_of ($signer, $url) { (canon($signer, $url))[1] }
sub req (@args) { (canon(@args))[2] }

# errors caused by the caller: Ouch exceptions with code 400
sub bad ($re = qr/./) {
   object { prop blessed => 'Ouch'; call code => 400; call message => match $re };
}

subtest 'path, non-S3 (normalized, double-encoded)' => sub {
   my %case = (    # from the AWS SigV4 test suite
      'https://h'                      => '/',
      'https://h/'                     => '/',
      'https://h/example/..'           => '/',
      'https://h/./'                   => '/',
      'https://h/./example'            => '/example',
      'https://h//example//'           => '/example/',
      'https://h/example/./a/../b'     => '/example/b',
      'https://h/../a'                 => '/a',
      'https://h/example/'             => '/example/',
      'https://h/example space/'       => '/example%2520space/',
      'https://h/example%20space/'     => '/example%2520space/',
      'https://h/%E1%88%B4'            => '/%25E1%2588%25B4',
      'https://h/a-._~b'               => '/a-._~b',
      'https://h/a$b'                  => '/a%2524b',
   );
   is path_of($std, $_), $case{$_}, $_ for sort keys %case;
};

subtest 'path, S3 (verbatim, single-encoded)' => sub {
   my %case = (
      'https://h/'                 => '/',
      'https://h/example space/'   => '/example%20space/',
      'https://h/example%20space/' => '/example%20space/',
      'https://h/a/../b'           => '/a/../b',
      'https://h//a//b'            => '//a//b',
      'https://h/%E1%88%B4'        => '/%E1%88%B4',
      'https://h/a$b'              => '/a%24b',
   );
   is path_of($s3, $_), $case{$_}, $_ for sort keys %case;
};

subtest 'query' => sub {
   my %case = (
      'https://h/'                                 => '',
      'https://h/?'                                => '',
      'https://h/?Param1=value1'                   => 'Param1=value1',
      'https://h/?Param2=v2&Param1=v1'             => 'Param1=v1&Param2=v2',
      'https://h/?a=2&a=1&a=3'                     => 'a=1&a=2&a=3',
      'https://h/?B=1&a=1&b=1&A=1'                 => 'A=1&B=1&a=1&b=1',
      'https://h/?a&b='                            => 'a=&b=',
      'https://h/?a=&a=x'                          => 'a=&a=x',
      'https://h/?k=a b'                           => 'k=a%20b',

t/canonical.t  view on Meta::CPAN

      'https://h/?-._~=-._~'                       => '-._~=-._~',
      'https://h/?%E1%88%B4=%E1%88%B4'             => '%E1%88%B4=%E1%88%B4',
      'https://h/?a=1&&b=2'                        => 'a=1&b=2',
      'https://h/?a=x=y'                           => 'a=x%3Dy',
      'https://h/?a=1#frag'                        => 'a=1',
   );
   is query_of($std, $_), $case{$_}, $_ for sort keys %case;
   is query_of($s3, 'https://h/?b=2&a=1'), 'a=1&b=2', 'S3 sorts too';
};

subtest 'url must be ASCII' => sub {
   is dies { canon($std, 'https://h/ሴ') }, bad(qr/ASCII/), 'non-ASCII path rejected';
   is dies { canon($std, 'https://h/?ሴ=1') }, bad(qr/ASCII/), 'non-ASCII query rejected';
   is dies { canon($std, "https://h/\x{e9}") }, bad(qr/ASCII/), 'latin-1 character rejected';
};

subtest 'host' => sub {
   my %case = (
      'https://example.com/'          => 'example.com',
      'https://example.com:443/'      => 'example.com',
      'http://example.com:80/'        => 'example.com',
      'https://example.com:8443/'     => 'example.com:8443',
      'http://example.com:443/'       => 'example.com:443',
      'https://example.com'           => 'example.com',
      'https://STS.Amazonaws.com/'    => 'sts.amazonaws.com',
      'https://h:0443/'               => 'h',
      'https://h:/'                   => 'h',

t/canonical.t  view on Meta::CPAN

   is req($std, 'https://a/', headers => {Host => 'b'})->{headers}{host}, 'b',
      'explicit Host wins';
   is dies { canon($std, 'https://user:pw@example.com/') }, bad(qr/user/),
      'user information is refused';
   for my $url ('https://evil.example\\.b.s3.amazonaws.com/x', 'https://b s3/',
         'https://h:abc/', 'https://h:443:443/', 'https://h:123456/') {
      is dies { canon($std, $url) }, bad(qr/invalid/), "invalid url: $url";
   }
};

subtest 'headers' => sub {
   my $r = req($std, 'https://h/', headers => {
      'X-Amz-Meta-B' => '  a   b  ',
      'x-amz-meta-a' => "tab\there",
      'X-Multi'      => ['1', '2'],
      'User-Agent'   => 'ignored',
      'Authorization' => 'ignored',
   });
   like $r->{canonical_request},
      qr{\nhost:h\nx-amz-date:20150830T123600Z\nx-amz-meta-a:tab here\nx-amz-meta-b:a b\nx-multi:1,2\n\nhost;x-amz-date;x-amz-meta-a;x-amz-meta-b;x-multi\n},
      'lowercased, sorted, trimmed, collapsed, multi-valued joined';

t/canonical.t  view on Meta::CPAN

   }, 0, 'undefined header values: no warnings';
   is $r->{headers}{host}, 'h', 'undefined Host: taken from the url';
   ok !exists $r->{headers}{'x-a'}, 'undefined value: no header';
   is $r->{headers}{'x-b'}, '1', 'undefined items of a list are skipped';

   # names that differ only in case are joined in a repeatable order
   is req($std, 'https://h/', headers => {'X-Foo' => 'a', 'x-foo' => 'b', 'X-FOO' => 'c'})
      ->{headers}{'x-foo'}, 'c,a,b', 'sorted by name as given';
};

subtest 'x-amz-* headers are always signed' => sub {
   my $t = AWS::Signature::V4->new(service => 's3', region => 'r',
      credentials => {%cred, session_token => 'TOK'});
   my $r = $t->sign(method => 'PUT', url => 'https://b.s3.amazonaws.com/k', time => 0,
      headers => {'Content-Type' => 'text/plain', 'X-Amz-Acl' => 'private'},
      signed_headers => ['content-type'], body => 'abc');
   is $r->{signed_headers},
      'content-type;host;x-amz-acl;x-amz-content-sha256;x-amz-date;x-amz-security-token',
      'those given and those added by sign';
   is req($std, 'https://h/', signed_headers => [])->{signed_headers}, 'host;x-amz-date',
      'even with an empty list';
};

subtest 'payload' => sub {
   my $empty = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
   my $r = req($std, 'https://h/');
   like $r->{canonical_request}, qr/\n$empty\z/, 'empty body';
   ok !exists $r->{headers}{'x-amz-content-sha256'}, 'no payload header outside S3';

   $r = req($s3, 'https://h/');
   is $r->{headers}{'x-amz-content-sha256'}, $empty, 'S3 payload header';
   like $r->{signed_headers}, qr/x-amz-content-sha256/, 'and it is signed';

   $r = req($std, 'https://h/', unsigned_payload => 1);

t/canonical.t  view on Meta::CPAN

   like $r->{canonical_request}, qr/\n\Q@{[ sha256_hex('abc') ]}\E\z/,
      'undefined payload_hash: the body is hashed';
   $r = req($std, 'https://h/', payload_hash => 'BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD');
   like $r->{canonical_request}, qr/\nba7816bf[0-9a-f]{56}\z/, 'hex payload_hash is lowercased';
   for my $hash ("x\r\nX-Injected: 1", 'HASH', 'a' x 63, {}) {
      is dies { canon($s3, 'https://h/', payload_hash => $hash) }, bad(qr/payload_hash/),
         'invalid payload_hash ' . (ref $hash || $hash =~ s/[\r\n]/?/gr);
   }
};

subtest 'payload header' => sub {
   my $lambda = AWS::Signature::V4->new(service => 'lambda', region => 'r', credentials => {%cred});
   my $r = req($lambda, 'https://h/', body => '{}', unsigned_payload => 1);
   is $r->{headers}{'x-amz-content-sha256'}, 'UNSIGNED-PAYLOAD', 'unsigned payload: header added';
   like $r->{signed_headers}, qr/x-amz-content-sha256/, 'and signed';
   $r = req($lambda, 'https://h/', payload_hash => 'STREAMING-X');
   is $r->{headers}{'x-amz-content-sha256'}, 'STREAMING-X', 'same for any marker';

   my $abc = sha256_hex('abc');
   $r = req($s3, 'https://h/', headers => {'X-Amz-Content-Sha256' => $abc});
   is $r->{headers}{'x-amz-content-sha256'}, $abc, 'S3: the header given is kept';

t/canonical.t  view on Meta::CPAN

   is $r->{headers}{'x-amz-content-sha256'}, 'UNSIGNED-PAYLOAD', 'and it is sent';
   $r = req($s3, 'https://h/', headers => {'X-Amz-Content-Sha256' => $abc}, body => 'abc');
   like $r->{canonical_request}, qr/\n$abc\z/, 'it can agree with the body';
   is dies { canon($lambda, 'https://h/', body => 'abc',
         headers => {'X-Amz-Content-Sha256' => 'UNSIGNED-PAYLOAD'}) },
      bad(qr/does not match/), 'a header that disagrees with the body is refused';
   is dies { canon($s3, 'https://h/', headers => {'X-Amz-Content-Sha256' => 'nope'}) },
      bad(qr/x-amz-content-sha256/), 'an invalid header is refused';
};

subtest 'S3 under other names' => sub {
   for my $name (qw< s3-object-lambda s3-outposts s3express >) {
      my $t = AWS::Signature::V4->new(service => $name, region => 'r', credentials => {%cred});
      my ($path, undef, $r) = canon($t, 'https://h/a%20b//c/../d');
      is $path, '/a%20b//c/../d', "$name: path verbatim";
      is $r->{headers}{'x-amz-content-sha256'}, sha256_hex(''), "$name: payload header";
      like $t->presign(url => 'https://h/', time => 0)->{canonical_request},
         qr/\nUNSIGNED-PAYLOAD\z/, "$name: presign with UNSIGNED-PAYLOAD";
   }
   my $t = AWS::Signature::V4->new(service => 's3x', region => 'r', credentials => {%cred});
   is path_of($t, 'https://h/a/../b'), '/b', 'but not any name starting with s3';
};

subtest 'body as scalar reference' => sub {
   my $body = 'some payload';
   my $plain = req($std, 'https://h/', body => $body);
   my $byref = req($std, 'https://h/', body => \$body);
   is $byref->{signature}, $plain->{signature}, 'same signature by reference';
   is $body, 'some payload', 'referenced body untouched';

   my $big = 'x' x 10_000_000;
   my $b1 = req($std, 'https://h/', body => \$big);
   like $b1->{canonical_request}, qr/\n[0-9a-f]{64}\z/, 'large body by reference';

t/canonical.t  view on Meta::CPAN

   my $l = req($std, 'https://h/', body => \$latin);
   my $l2 = req($std, 'https://h/', body => "\xe9");
   is $l->{signature}, $l2->{signature}, 'upgraded latin-1 string hashes as bytes';
   ok utf8::is_utf8($latin), 'and the input string was not downgraded';

   my $undef;
   my $e1 = req($std, 'https://h/', body => \$undef);
   my $e2 = req($std, 'https://h/');
   is $e1->{signature}, $e2->{signature}, 'reference to undef is an empty body';
   is dies { canon($std, 'https://h/', body => []) }, bad(qr/body/), 'array reference rejected';
   is dies { canon($std, 'https://h/', body => sub {}) }, bad(qr/body/), 'code reference rejected';
};

subtest 'method, scope, token' => sub {
   my $r = $std->sign(method => 'post', url => 'https://h/', time => 1440938160);
   like $r->{canonical_request}, qr/\APOST\n/, 'method uppercased';
   is $r->{scope}, '20150830/us-east-1/service/aws4_request', 'scope';
   like $r->{authorization},
      qr{^AWS4-HMAC-SHA256 Credential=AKID/20150830/us-east-1/service/aws4_request, SignedHeaders=host;x-amz-date, Signature=[0-9a-f]{64}$},
      'authorization header';

   my $t = AWS::Signature::V4->new(service => 'service', region => 'r',
      credentials => {%cred, session_token => 'TOK'});
   $r = $t->sign(method => 'GET', url => 'https://h/', time => 0);
   is $r->{headers}{'x-amz-security-token'}, 'TOK', 'session token header';
   like $r->{signed_headers}, qr/x-amz-security-token/, 'is signed';
   like $r->{headers}{'x-amz-date'}, qr/^19700101T000000Z$/, 'epoch 0';
};

subtest 'constructor errors' => sub {
   is dies { AWS::Signature::V4->new(region => 'r', credentials => {%cred}) },
      bad(qr/service/), 'no service';
   is dies { AWS::Signature::V4->new(service => 's', credentials => {%cred}) },
      bad(qr/region/), 'no region';
   is dies { AWS::Signature::V4->new(service => 's', region => 'r') },
      bad(qr/credentials/), 'no credentials';
   is dies { AWS::Signature::V4->new(service => 's', region => 'r', credentials => {access_key_id => 'x'}) },
      bad(qr/secret_access_key/), 'missing secret';
   is dies { AWS::Signature::V4->new(service => 's', region => 'r', credentials => {%cred, token => 'T'}) },
      bad(qr/unknown option "token" in credentials/), 'unknown credentials option';
   is dies { AWS::Signature::V4->new(service => 's', region => "us-east-1\r\nX-Evil: 1",
         credentials => {%cred}) }, bad(qr/region/), 'invalid region';
   is dies { AWS::Signature::V4->new(service => 'a/b', region => 'r', credentials => {%cred}) },
      bad(qr/service/), 'invalid service';
};

subtest 'arguments' => sub {
   is $std->sign({method => 'GET', url => 'https://h/', time => 0})->{signature},
      $std->sign(method => 'GET', url => 'https://h/', time => 0)->{signature},
      'a hash reference is the same as a list of pairs';
   is dies { $std->sign(method => 'GET', url => 'https://h/', 'time') },
      bad(qr/pairs/), 'odd list';
   is dies { canon($std, 'https://h/', content => 'x') }, bad(qr/unsupported for sign: "content"/),
      'unknown parameter';
   is dies { canon($std, 'https://h/', expires => 60) }, bad(qr/unsupported for sign: "expires"/),
      'presign-only parameter';
   for my $name (qw< body payload_hash unsigned_payload >) {

t/canonical.t  view on Meta::CPAN

      'negative time'             => [time => -1],
      'url a reference'           => [url => []],
   );
   for my $name (sort keys %bad) {
      is dies { $std->sign(method => 'GET', url => 'https://h/', $bad{$name}->@*) }, bad(), $name;
   }
   is req($std, 'https://h/', time => 1440938160.75)->{headers}{'x-amz-date'},
      '20150830T123600Z', 'fractional time is fine';
};

subtest 'url path and query' => sub {
   for my $url ('foo/bar', 'folder/file.txt', 'x') {
      is dies { canon($std, $url, headers => {Host => 'h'}) }, bad(qr{start with "/"}),
         "relative path $url refused";
   }
   is path_of($std, 'https://h?a=1'), '/', 'empty path is fine';
   is req($std, '/a/b', headers => {Host => 'h'})->{headers}{host}, 'h', 'absolute path with Host';
   is dies { canon($std, 'https://h/?prefix=a+b') }, bad(qr/\+/), 'plus sign in the query refused';
   is query_of($std, 'https://h/?prefix=a%2Bb%20c'), 'prefix=a%2Bb%20c', 'encoded is fine';
   is path_of($std, 'https://h/a+b'), '/a%252Bb', 'plus sign in the path is a plus sign';
   for my $url ('https://h/public/%2e%2e/admin', 'https://h/a/%2E/b', 'https://h/a/.%2e/b') {
      is dies { canon($std, $url) }, bad(qr/dot segment/), "encoded dot segment: $url";
   }
   is path_of($s3, 'https://h/public/%2e%2e/admin'), '/public/../admin',
      'S3 does not normalize: fine there';
};

subtest 'values that the module puts in headers or in the query' => sub {
   my $signer = sub (%creds) {
      AWS::Signature::V4->new(service => 'service', region => 'r',
         credentials => {%cred, %creds});
   };
   my $t = $signer->(session_token => "TOKEN\n");
   is dies { $t->sign(method => 'GET', url => 'https://h/') },
      bad(qr/x-amz-security-token/), 'session token with a newline';
   my $k = $signer->(access_key_id => "AKID\r\nX-Evil: 1");
   is dies { $k->sign(method => 'GET', url => 'https://h/') },
      bad(qr/authorization/), 'access key id with CR/LF';

t/chain.t  view on Meta::CPAN

use Test2::V0;
use FindBin '$Bin';
use lib "$Bin/../lib";
use AWS::Signature::V4;
use MIME::Base64 qw< encode_base64 >;
use File::Temp qw< tempdir >;

# chain items only need to be well-formed DER SEQUENCEs, tiny ones will do
my @der = map { "\x30\x03\x02\x01" . chr($_) } 1 .. 3;
my @b64 = map { encode_base64($_, '') } @der;
sub pem ($der) {
   "-----BEGIN CERTIFICATE-----\n" . encode_base64($der) . "-----END CERTIFICATE-----\n"
}
my @pem = map { pem($_) } @der;

my $dir = tempdir(CLEANUP => 1);
sub file ($name, $content) {
   open my $fh, '>:raw', "$dir/$name" or die;
   print {$fh} $content;
   close $fh;
   return "$dir/$name";
}

sub chain_header (%x) {
   my $s = AWS::Signature::V4->new(service => 'rolesanywhere', region => 'r', x509 => {
      key_type  => 'ECDSA', certificate => $pem[0], serial => 1,
      signer => sub { 'sig' }, %x});
   my $r = $s->sign(method => 'GET', url => 'https://h/', time => 0);
   return $r->{headers}{'x-amz-x509-chain'};
}

my $both = join ',', @b64[1, 2];
is chain_header(), undef, 'no chain, no header';
is chain_header(chain => [$pem[1], $pem[2]]), $both, 'chain, PEM contents';
is chain_header(chain => [$der[1], $der[2]]), $both, 'chain, DER contents';
is chain_header(chain => [$pem[1], $der[2]]), $both, 'chain, mixed';
is chain_header(chain => [$pem[1] . $pem[2]]), $both, 'chain, PEM bundle';

t/chain.t  view on Meta::CPAN

is chain_header(chain_files => [file(bundle => $pem[1] . $pem[2])]), $both,
   'chain_files, PEM bundle';
is chain_header(chain => [$pem[2]], chain_files => \@f), $b64[2],
   'chain wins over chain_files';
ok dies { chain_header(chain_files => ["$dir/missing"]) }, 'missing file croaks';
ok dies { chain_header(chain => ["-----BEGIN X-----\nAA==\n-----END X-----\n"]) },
   'PEM without certificates croaks';

my $r = AWS::Signature::V4->new(service => 's', region => 'r', x509 => {
      key_type  => 'RSA', certificate => $pem[0], serial => 1,
      chain => [$pem[1]], signer => sub { 'sig' }})
   ->sign(method => 'GET', url => 'https://h/', time => 0);
like $r->{signed_headers}, qr/x-amz-x509-chain/, 'chain header is signed';

done_testing;

t/error.t  view on Meta::CPAN

use v5.24;
use Test2::V0;
use FindBin '$Bin';
use experimental 'signatures';
use lib "$Bin/../lib";
use AWS::Signature::V4::Error qw< fail >;

my $secret = 'S3CR3T-value';

sub thrown (@args) { my $e = dies { fail(@args) }; $e }

subtest 'code and message' => sub {
   my $e = thrown(400, 'bad input');
   isa_ok $e, ['Ouch'], 'an Ouch exception';
   is $e->code, 400, 'code';
   is $e->message, 'bad input', 'message';
   is $e->data, undef, 'no data by default';
   is thrown(500, 'internal')->code, 500, 'other code';
};

subtest 'the third argument is passed down' => sub {
   my $e = thrown(400, 'bad option', {option => 'foo', got => $secret});
   is $e->code, 400, 'code';
   is $e->message, 'bad option', 'message';
   is $e->data, {option => 'foo', got => $secret}, 'data is available';
   is $e->hashref->{data}, {option => 'foo', got => $secret}, 'and it is in hashref too';
   unlike "$e", qr{\Q$secret\E|foo}, 'data is not in the stringified error';
   unlike $e->message, qr{\Q$secret\E}, 'nor in the message';

   my $d = [1, 2, 3];
   is thrown(400, 'array', $d)->data, [1, 2, 3], 'not only hashes';
   is thrown(400, 'scalar', 'plain')->data, 'plain', 'nor references';
};

subtest 'data and arguments stay out of the trace' => sub {
   my $e = do {
      package Some::Caller;
      sub run ($password) { main::thrown(400, 'oops', {got => $secret}) }
      run('Hunter2');
   };
   is $e->data, {got => $secret}, 'data kept';
   unlike $e->trace, qr{\Q$secret\E|Hunter2|HASH\(}, 'no arguments in the trace';
};

subtest 'reported where the caller is' => sub {
   my $line = __LINE__ + 1;
   my $e = dies { fail 400, 'here', {some => 'data'} };
   like "$e", qr{ at \S*error\.t line $line\b}, 'file and line of the caller';
};

done_testing;

t/errors.t  view on Meta::CPAN

use experimental 'signatures';
use Digest::SHA qw< sha256 >;
use MIME::Base64 qw< encode_base64 >;
use AWS::Signature::V4;
use AWS::Signature::V4::Chunker;

my %cred = (credentials => {access_key_id => 'a', secret_access_key => 'b'});
my $s = AWS::Signature::V4->new(service => 's3', region => 'r', %cred);
my $secret = 'Hunter2-TopSecret';

sub ouch_like ($code, $status, $name) {
   is dies { $code->() },
      object { prop blessed => 'Ouch'; call code => $status },
      $name;
}

sub streaming ($signer, %opts) {
   $signer->sign(method => 'PUT', url => 'http://h/', streaming => 1, %opts);
}

# errors caused by the caller are Ouch exceptions with code 400
my %caller = (
   'no service'      => sub { AWS::Signature::V4->new(region => 'r', %cred) },
   'no region'       => sub { AWS::Signature::V4->new(service => 's', %cred) },
   'no credentials'  => sub { AWS::Signature::V4->new(service => 's', region => 'r') },
   'both variants'   => sub { AWS::Signature::V4->new(service => 's', region => 'r', %cred, x509 => {}) },
   'bad key type'   => sub { AWS::Signature::V4->new(service => 's', region => 'r', x509 => {key_type => 'DSA'}) },
   'x509 key type under its old name' =>
      sub { AWS::Signature::V4->new(service => 's', region => 'r', x509 => {algorithm => 'RSA'}) },
   'credentials not a hash' =>
      sub { AWS::Signature::V4->new(service => 's', region => 'r', credentials => 'AKID:SECRET') },
   'no method'       => sub { $s->sign(url => 'http://h/') },
   'non-ASCII url'   => sub { $s->sign(method => 'GET', url => "http://h/\x{e9}") },
   'control chars in url' => sub { $s->sign(method => 'GET', url => "http://h/a\nb") },
   'empty url'       => sub { $s->sign(method => 'GET', url => '') },
   'no host'         => sub { $s->presign(url => '/path') },
   'wide body'       => sub { $s->sign(method => 'PUT', url => 'http://h/', body => "\x{263a}") },
   'body_fh not a handle' => sub { $s->sign(method => 'PUT', url => 'http://h/', body_fh => 'file.txt') },
   'bad expires'     => sub { $s->presign(url => 'http://h/', expires => 0) },
   'unknown checksum' => sub { streaming($s, decoded_content_length => 1, checksum => 'md5') },
   'finish twice'    => sub {
      my $ck = streaming($s, decoded_content_length => 0)->{chunker};
      $ck->finish;
      $ck->finish;
   },
);
ouch_like $caller{$_}, 400, $_ for sort keys %caller;

# ... including what goes wrong when loading certificates and keys
my %x509 = (service => 's', region => 'r');
my $der = "\x30\x03\x02\x01\x05";    # a tiny, valid, DER structure
my %x509_errors = (
   'garbage certificate' => {key_type => 'RSA', certificate => 'garbage', serial => 1, signer => sub { 'x' }},
   'truncated certificate' => {key_type => 'RSA', certificate => "\x30\x82\x01", signer => sub { 'x' }},
   'signer not code' => {key_type => 'RSA', certificate => $der, serial => 1, signer => 'nope'},
   'missing key file' => {key_type => 'RSA', certificate => $der, serial => 1, private_key_file => '/no/such/key'},
   'garbage key' => {key_type => 'ECDSA', certificate => $der, serial => 1, private_key => 'garbage'},
);
for my $name (sort keys %x509_errors) {
   ouch_like sub { AWS::Signature::V4->new(%x509, x509 => $x509_errors{$name}) }, 400, $name;
}

# internal problems are 500
ouch_like sub { AWS::Signature::V4::Chunker->new(signed => 1, expected => 0) }, 500,
   'chunker without key';

# the error is reported where the caller is, and holds no secrets
my $e = dies {
   AWS::Signature::V4->new(%x509, x509 => {
      key_type => 'RSA', certificate => $der, serial => 1,
      private_key => 'garbage', private_key_password => $secret,
   });
};
like "$e", qr{ at \S*errors\.t line \d+}, 'error reported at the line of the caller';
unlike $e->trace, qr{\Q$secret\E}, 'the trace does not include the password';
unlike "$e", qr{\Q$secret\E}, 'the message does not include the password';
for my $how ('verbose', 'die handler') {
   my $e = dies {
      local $Carp::Verbose = $how eq 'verbose';
      local $SIG{__DIE__} = sub { die Carp::longmess($_[0]) } if $how eq 'die handler';
      AWS::Signature::V4->new(%x509, x509 => {
         key_type => 'RSA', certificate => $der, serial => 1,
         private_key => 'garbage', private_key_password => $secret,
      });
   };
   like $e->message, qr{\Acannot load the private key: [^\n]+\z},
      "$how: the message is one line";
   unlike "$e", qr{\Q$secret\E}, "$how: the message does not include the password";
}
like dies { $s->sign(url => 'http://h/') }, qr{ at \S*errors\.t line \d+},

t/errors.t  view on Meta::CPAN

my $v = AWS::Signature::V4->new(service => 's', region => 'r', credentials => \%mine);
$mine{access_key_id} = 'EVIL';
is $v->credentials->{access_key_id}, 'a', 'credentials are copied';

# a subclass can assign $_ in its builders
{
   package Sub::Signer;
   use Moo;
   extends 'AWS::Signature::V4';
   has '+region' => (lazy => 1, builder => 1);
   sub _build_region { $_ = 'eu-west-1'; return $_ }
}
is(Sub::Signer->new(service => 's', %cred)->region, 'eu-west-1', 'builders can use $_');

# no warnings for what used to be accepted silently
is warns { $s->sign(method => 'GET', url => 'http://h/', headers => {'X-Opt' => undef}) },
   0, 'undefined header value: no warnings';

# the chunker is not confused by its own errors
my $ck = streaming($s, decoded_content_length => 9, checksum => 'sha256',
   trailers => ['x-foo'], signed_headers => ['host'])->{chunker};
$ck->chunk('123456789');
ouch_like sub { $ck->finish }, 400, 'missing trailer value';
like $ck->finish('x-foo' => 1),
   qr{x-amz-checksum-sha256:\Q@{[ encode_base64(sha256('123456789'), '') ]}\E\r\n},
   'the checksum survives a failed finish';

$ck = streaming($s, decoded_content_length => 4)->{chunker};
$ck->chunk('abc');
ouch_like sub { $ck->chunk('xy') }, 400, 'too much data';
ok lives { $ck->chunk('x') }, 'a chunk that fits is still accepted';
ok lives { $ck->finish }, 'and the stream can be completed';

done_testing;

t/presign.t  view on Meta::CPAN

use v5.24;
use experimental 'signatures';
use Test2::V0;
use FindBin '$Bin';
use lib "$Bin/../lib";
use AWS::Signature::V4;
use Digest::SHA qw< sha256_hex >;
use MIME::Base64 qw< encode_base64 >;

sub bad ($re = qr/./) {
   object { prop blessed => 'Ouch'; call code => 400; call message => match $re };
}

# Example from the AWS docs: presigned GET on S3
my $s3 = AWS::Signature::V4->new(
   service => 's3', region => 'us-east-1',
   credentials => {
      access_key_id     => 'AKIAIOSFODNN7EXAMPLE',
      secret_access_key => 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
   },

t/presign.t  view on Meta::CPAN

   'invalid method';
is $iam->presign({url => 'https://h/', time => 0})->{signature},
   $iam->presign(url => 'https://h/', time => 0)->{signature}, 'hash reference of arguments';

# X.509 variant, with a stub signer
my $cert = "-----BEGIN CERTIFICATE-----\n" . encode_base64("\x30\x03\x02\x01\x07")
   . "-----END CERTIFICATE-----\n";
my $seen = '';
my $x = AWS::Signature::V4->new(service => 'rolesanywhere', region => 'r', x509 => {
      key_type  => 'RSA', certificate => $cert, serial => 42,
      chain => [$cert], signer => sub { $seen = shift; 'SIG' }});
$r = $x->presign(url => 'https://h/x', time => 0);
is $seen, $r->{string_to_sign}, 'signer got the string to sign';
is $r->{signature}, unpack('H*', 'SIG'), 'signature is the hex of the signer output';
like $r->{url}, qr/X-Amz-Algorithm=AWS4-X509-RSA-SHA256/, 'x509 algorithm';
like $r->{url}, qr{X-Amz-Credential=42%2F19700101%2Fr%2Frolesanywhere%2Faws4_request}, 'serial in credential';
my $enc = 'MAMCAQc%3D';    # base64 of the certificate, percent-encoded
like $r->{url}, qr/&X-Amz-X509=\Q$enc\E&/, 'certificate in the query';
like $r->{url}, qr/&X-Amz-X509-Chain=\Q$enc\E&/, 'chain in the query';
unlike $r->{canonical_request}, qr/^x-amz-x509/m, 'not headers';
like $r->{canonical_request}, qr/X-Amz-X509=/, 'signed as query parameters';

t/security.t  view on Meta::CPAN

use lib "$Bin/../lib";
use experimental 'signatures';
use Data::Dumper ();
use File::Temp ();
use AWS::Signature::V4;

my %cred = (access_key_id => 'AKID', secret_access_key => 'SECRET');
my $s3  = AWS::Signature::V4->new(service => 's3', region => 'r', credentials => {%cred});
my $url = 'https://b.s3.amazonaws.com/k';

sub bad_request ($re) {
   object { prop blessed => 'Ouch'; call code => 400; call message => match $re };
}

sub dump_of ($x) {
   local $Data::Dumper::Deparse = 0;
   Data::Dumper->new([$x])->Useqq(1)->Dump;
}

subtest 'header names and values are validated' => sub {
   for my $value ("a\r\nX-Injected: 1", "a\nb", "a\rb", "a\0b") {
      my $shown = $value =~ s/([^ -~])/sprintf '\\x%02X', ord $1/ger;
      is dies { $s3->sign(method => 'GET', url => $url, headers => {'X-V' => $value}) },
         bad_request(qr/header/), "value $shown rejected";
   }
   for my $name ("x-n:1\nfoo", 'x n', 'x:n', '', "x\x{e9}") {
      my $shown = $name =~ s/([^ -~])/sprintf '\\x%02X', ord $1/ger;
      is dies { $s3->sign(method => 'GET', url => $url, headers => {$name => 'v'}) },
         bad_request(qr/header/), "name '$shown' rejected";
   }
   ok lives { $s3->sign(method => 'GET', url => $url,
      headers => {"X-Ok_1.a!#\$%&'*+^`|~" => "tab\there, spaces  ok"}) },
      'valid token names and values with tabs and spaces are fine';
   is dies { $s3->presign(url => $url, headers => {'X-V' => "a\nb"}) },
      bad_request(qr/header/), 'presign too';
};

subtest 'the derived signing key is not exposed' => sub {
   my $r = $s3->sign(method => 'PUT', url => $url, time => 0,
      streaming => 1, decoded_content_length => 1);
   my $ck = $r->{chunker};
   ok !$ck->can('key'), 'no key accessor';
   ok !$ck->can('previous'), 'no previous accessor';
   my $key = unpack 'H*', AWS::Signature::V4::Credentials->new(%cred)
      ->signing_key($r->{scope});
   unlike dump_of($r), qr/\Q$key\E/, 'the hex key is not in a dump of the result';
   my $raw = pack 'H*', $key;
   unlike dump_of($r), qr/\Q@{[ quotemeta $raw ]}\E/, 'nor the raw key';
   like $ck->chunk('x'), qr/\A1;chunk-signature=[0-9a-f]{64}\r\nx\r\n\z/, 'chunks are still signed';
};

subtest 'presign refuses authentication parameters in the url' => sub {
   for my $param (qw<
      X-Amz-Algorithm X-Amz-Credential X-Amz-Date X-Amz-Expires
      X-Amz-SignedHeaders X-Amz-Signature X-Amz-Security-Token
      X-Amz-X509 X-Amz-X509-Chain x-amz-signature X-AMZ-EXPIRES
   >) {
      is dies { $s3->presign(url => "$url?$param=1") },
         bad_request(qr/\Q$param\E/i), "$param rejected";
   }
   is dies { $s3->presign(url => "$url?X%2DAmz%2DCredential=1") },
      bad_request(qr/credential/i), 'also when percent-encoded';
   ok lives { $s3->presign(url => "$url?X-Amz-Meta-Foo=1&versionId=3") },
      'other parameters are fine';
};

subtest 'host is always signed' => sub {
   my $r = $s3->sign(method => 'GET', url => $url, time => 0,
      signed_headers => ['x-amz-date']);
   is $r->{signed_headers}, 'host;x-amz-content-sha256;x-amz-date',
      'sign adds host, and the x-amz-* headers';
   $r = $s3->presign(url => $url, time => 0, signed_headers => ['x-amz-date'],
      headers => {'x-amz-date' => 'x'});
   is $r->{signed_headers}, 'host;x-amz-date', 'presign adds host';
};

subtest 'secrets of the x509 key are not kept around' => sub {
   my $dir = File::Temp::tempdir(CLEANUP => 1);
   system(qq{openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 }
      . qq{-aes256 -pass pass:TopSecretPass -out $dir/k.pem 2>/dev/null}) == 0
      or skip_all 'openssl needed';
   system(qq{openssl req -new -x509 -key $dir/k.pem -passin pass:TopSecretPass }
      . qq{-subj /CN=t -days 1 -out $dir/c.pem 2>/dev/null}) == 0
      or skip_all 'openssl needed';
   my $pem = do { local (@ARGV, $/) = "$dir/k.pem"; <> };
   my $s = AWS::Signature::V4->new(service => 'rolesanywhere', region => 'r',
      x509 => {key_type => 'ECDSA', certificate_file => "$dir/c.pem",
               private_key => $pem, private_key_password => 'TopSecretPass'});
   ok !exists $s->x509->{private_key}, 'no key text in ->x509';
   ok !exists $s->x509->{private_key_password}, 'no password in ->x509';
   my $dump = dump_of($s);
   unlike $dump, qr/TopSecretPass/, 'no password in a dump';
   unlike $dump, qr/ENCRYPTED PRIVATE KEY/, 'no key text in a dump';
   like $s->sign(method => 'GET', url => 'https://h/', time => 0)->{signature},
      qr/\A[0-9a-f]+\z/, 'signing still works';
};

subtest 'userinfo in the url is refused' => sub {
   for my $u ('http://a@evil.example@good.example/', 'http://user@good.example/') {
      is dies { $s3->sign(method => 'GET', url => $u) }, bad_request(qr/user/), $u;
   }
};

subtest 'caller input is escaped in error messages' => sub {
   for my $case (
      [sub { AWS::Signature::V4->new(service => 's', region => 'r',
         x509 => {key_type => "DSA\nFAKE LOG LINE"}) }, 'key_type'],
      [sub { $s3->sign(method => 'PUT', url => $url, streaming => 1,
         decoded_content_length => 1, checksum => "md5\nFAKE") }, 'checksum'],
      [sub { $s3->sign(method => 'PUT', url => $url, streaming => 1,
         decoded_content_length => 1, trailers => ["x\nFAKE"]) }, 'trailer name'],
      [sub { $s3->sign(method => 'GET', url => $url, signed_headers => ["x\nFAKE"]) },
         'signed header name'],
      [sub { AWS::Signature::V4->new(service => 's', region => 'r',
         x509 => {key_type => 'RSA', certificate => "\x30\x03\x02\x01\x05", serial => 1,
            private_key_file => "/no/such\nFAKE LOG LINE"}) }, 'private key file'],
      [sub { AWS::Signature::V4->new(service => 's', region => 'r',
         x509 => {key_type => 'RSA', certificate_file => "/no/such\nFAKE LOG LINE",
            serial => 1, signer => sub { 'x' }}) }, 'certificate file'],
   ) {
      my ($code, $name) = @$case;
      my $e = dies { $code->() };
      isa_ok $e, ['Ouch'], $name;
      unlike $e->message, qr/[\r\n]/, "$name: no line breaks in the message";
   }
};

done_testing;

t/streaming.t  view on Meta::CPAN

is $r->{signed_headers}, 'content-encoding;host;x-amz-content-sha256;x-amz-date;x-amz-decoded-content-length',
   'even with an explicit list, the headers of streaming are signed';
ok dies { $s3->sign(method => 'PUT', url => 'https://h/k', streaming => 1) },
   'decoded_content_length is required';
ok dies { $s3->sign(method => 'PUT', url => 'https://h/k', streaming => 1,
   decoded_content_length => 'x') }, 'and must be a number';
ok dies { $s3->presign(url => 'https://h/k', streaming => 1, decoded_content_length => 1) },
   'no streaming with presign';

my $x = AWS::Signature::V4->new(service => 's3', region => 'r', x509 => {
      key_type  => 'RSA', serial => 1, signer => sub { 'x' },
      certificate => "-----BEGIN CERTIFICATE-----\nMAMCAQc=\n-----END CERTIFICATE-----\n"});
ok dies { $x->sign(method => 'PUT', url => 'https://h/k', streaming => 1,
   decoded_content_length => 0) }, 'no streaming with x509';

my $short = $s3->sign(method => 'PUT', url => 'https://h/k', streaming => 1,
   decoded_content_length => 4, time => 0)->{chunker};
$short->chunk('ab');
ok dies { $short->finish }, 'finish() checks the total length';
ok dies { $short->chunk('abc') }, 'chunk() checks the total length';
ok dies { $short->chunk('') }, 'empty chunks are refused';

t/streaming.t  view on Meta::CPAN

my $viafh  = $std->sign(method => 'PUT', url => 'https://h/', body_fh => $in, time => 0);
my $viabody = $std->sign(method => 'PUT', url => 'https://h/', body => substr($data, 5), time => 0);
is $viafh->{signature}, $viabody->{signature}, 'body_fh hashes from the current position to the end';
is tell($in), 5, 'and the file position is restored';
ok dies { $std->sign(method => 'PUT', url => 'https://h/', body_fh => $in, body => 'x') },
   'body and body_fh together are refused';
my $pfh = $std->presign(url => 'https://h/', body_fh => $in, time => 0);
my $pbody = $std->presign(url => 'https://h/', body => substr($data, 5), time => 0);
is $pfh->{signature}, $pbody->{signature}, 'body_fh works with presign too';

sub bad ($re) {
   object { prop blessed => 'Ouch'; call code => 400; call message => match $re };
}

# body_fh must be put back where it was, so it must be seekable and binary
open my $pipe, '-|', $^X, '-e', 'print "hello"' or die "pipe: $!";
is dies { $std->sign(method => 'PUT', url => 'https://h/', body_fh => $pipe) },
   bad(qr/seekable/), 'a pipe is refused';
is do { local $/; <$pipe> }, 'hello', 'and it is not consumed';
close $pipe;
open my $text, '<:encoding(UTF-8)', $file or die;

t/trailer.t  view on Meta::CPAN

use FindBin '$Bin';
use lib "$Bin/../lib";
use AWS::Signature::V4;
use Digest::SHA qw< sha1 sha256 sha256_hex hmac_sha256 hmac_sha256_hex >;
use MIME::Base64 qw< encode_base64 >;

my $s3 = AWS::Signature::V4->new(service => 's3', region => 'us-east-1', credentials => {
      access_key_id => 'AKIAIOSFODNN7EXAMPLE',
      secret_access_key => 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'});
my $x = AWS::Signature::V4->new(service => 's3', region => 'r', x509 => {
      key_type  => 'RSA', serial => 1, signer => sub { 'x' },
      certificate => "-----BEGIN CERTIFICATE-----\nMAMCAQc=\n-----END CERTIFICATE-----\n"});

sub bad ($re) {
   object { prop blessed => 'Ouch'; call code => 400; call message => match $re };
}

# the reference for the signed chunks and trailers
my $key = 'AWS4' . 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY';
$key = hmac_sha256($_, $key) for '20130524', 'us-east-1', 's3', 'aws4_request';
my $scope = '20130524/us-east-1/s3/aws4_request';
my $sts = sub ($kind, @parts) { join "\n", "AWS4-HMAC-SHA256-$kind", '20130524T000000Z', $scope, @parts };

sub start ($signer = $s3, %opts) {
   $signer->sign(method => 'PUT', url => 'https://h/k', time => 1369353600,
      decoded_content_length => 9, %opts);
}

# --- checksums, fed in two pieces
my %expect = (    # of "123456789"
   crc32  => encode_base64(pack('N', 0xCBF43926), ''),
   crc32c => encode_base64(pack('N', 0xE3069283), ''),
   sha1   => encode_base64(sha1('123456789'), ''),
   sha256 => encode_base64(sha256('123456789'), ''),
);
for my $algo (sort keys %expect) {
   my $ck = start($x, streaming => 'unsigned', checksum => $algo)->{chunker};
   my $body = $ck->chunk('1234') . $ck->chunk('56789') . $ck->finish;
   is $body, "4\r\n1234\r\n5\r\n56789\r\n0\r\nx-amz-checksum-$algo:$expect{$algo}\r\n\r\n",
      "unsigned, $algo, byte for byte";
}

# --- crc32c against a bitwise reference, on longer data and in many chunks
sub crc32c_ref ($data) {
   my $crc = 0xFFFFFFFF;
   for my $byte (unpack 'C*', $data) {
      $crc ^= $byte;
      $crc = ($crc & 1) ? (($crc >> 1) ^ 0x82F63B78) : ($crc >> 1) for 1 .. 8;
   }
   return encode_base64(pack('N', $crc ^ 0xFFFFFFFF), '');
}
my $long = join '', map { chr(($_ * 7) % 256) } 1 .. 5000;
my $ck = start($x, streaming => 'unsigned', checksum => 'crc32c',
   decoded_content_length => length $long)->{chunker};

t/trailer.t  view on Meta::CPAN

   $ck->chunk('123456789');
   my $sig1 = hmac_sha256_hex($sts->('PAYLOAD', $r->{signature}, sha256_hex(''), sha256_hex('123456789')), $key);
   my $sig2 = hmac_sha256_hex($sts->('PAYLOAD', $sig1, sha256_hex(''), sha256_hex('')), $key);
   my @lines = ("x-amz-checksum-sha1:$expect{sha1}", 'x-foo:1', 'x-bar:2');
   my $tsig = hmac_sha256_hex($sts->('TRAILER', $sig2, sha256_hex(join '', map { "$_\n" } @lines)), $key);
   is $ck->finish('x-foo' => '1', 'x-bar' => '2'),
      "0;chunk-signature=$sig2\r\n" . join('', map { "$_\r\n" } @lines)
      . "x-amz-trailer-signature:$tsig\r\n\r\n",
      'all trailers, in order, signed';

   my $mk = sub ($signer = $x) {
      my $c = start($signer, streaming => $signer == $x ? 'unsigned' : 1, checksum => 'crc32',
         trailers => ['X-Foo'])->{chunker};
      $c->chunk('123456789');
      $c;
   };
   is dies { $mk->()->finish }, bad(qr/missing value for trailer 'x-foo'/), 'missing value';
   is dies { $mk->()->finish('x-foo' => 1, 'x-nope' => 2) }, bad(qr/undeclared trailers: x-nope/),
      'undeclared value';
   is dies { $mk->()->finish('x-foo' => 1, 'x-amz-checksum-crc32' => 'x') },
      bad(qr/'x-amz-checksum-crc32' is computed/), 'computed value given';

t/variants.t  view on Meta::CPAN

use v5.24;
use Test2::V0;
use FindBin '$Bin';
use lib "$Bin/../lib";
use experimental 'signatures';
use MIME::Base64 qw< encode_base64 >;
use AWS::Signature::V4;
use AWS::Signature::V4::Credentials;
use AWS::Signature::V4::X509;

sub bad_request ($name) {
   object { prop blessed => 'Ouch'; call code => 400; call message => match qr/\Q$name\E/ };
}

subtest 'credentials' => sub {
   my $c = AWS::Signature::V4::Credentials->new(
      access_key_id => 'AKIDEXAMPLE',
      secret_access_key => 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY',
   );
   is $c->algorithm, 'AWS4-HMAC-SHA256', 'algorithm';
   is $c->credential_id, 'AKIDEXAMPLE', 'credential id is the access key';
   ok $c->can_sign_chunks, 'it can sign chunks';
   is [$c->extra_fields], [], 'no token, no extra fields';

   my $scope = '20150830/us-east-1/iam/aws4_request';

t/variants.t  view on Meta::CPAN

   is dies { AWS::Signature::V4::Credentials->new(secret_access_key => 'b') },
      bad_request('credentials/access_key_id'), 'access key is needed';
   is dies { AWS::Signature::V4::Credentials->new(access_key_id => 'a') },
      bad_request('credentials/secret_access_key'), 'secret is needed';
   is dies { AWS::Signature::V4::Credentials->new(access_key_id => '', secret_access_key => 'b') },
      bad_request('credentials/access_key_id'), 'access key cannot be empty';
   is dies { AWS::Signature::V4::Credentials->new(access_key_id => 'a', secret_access_key => '') },
      bad_request('credentials/secret_access_key'), 'secret cannot be empty';
};

subtest 'x509' => sub {
   my $der   = "\x30\x03\x02\x01\x05";     # tiny but well-formed DER
   my $chain = "\x30\x03\x02\x01\x06";
   my %x = (certificate => $der, serial => 7, signer => sub { "\x01\x02" });

   my $x = AWS::Signature::V4::X509->new(key_type  => 'ecdsa', %x);
   is $x->algorithm, 'AWS4-X509-ECDSA-SHA256', 'algorithm, from the key type';
   is $x->credential_id, 7, 'credential id is the serial';
   ok !$x->can_sign_chunks, 'it cannot sign chunks';
   is dies { $x->signing_key('20150830/us-east-1/iam/aws4_request') },
      bad_request('credentials variant'), 'no derived key';
   is $x->signature('any/scope', 'anything'), '0102', 'the signature is the hex of the signer output';
   is [$x->extra_fields], ['X-Amz-X509' => encode_base64($der, '')], 'the certificate';

t/variants.t  view on Meta::CPAN

         bad_request('not a DER-encoded certificate'), "certificate, $name";
      is dies { AWS::Signature::V4::X509->new(key_type => 'RSA', %x, chain => [$bad]) },
         bad_request('not a DER-encoded certificate'), "chain, $name";
   }
   my $long = "\x30\x81\x80" . ("\x05\x00" x 64);    # long form, when needed
   is [AWS::Signature::V4::X509->new(key_type => 'RSA', %x, certificate => $long)->extra_fields],
      ['X-Amz-X509' => encode_base64($long, '')], 'minimal long form accepted';

   for my $case ([undef, 'undef'], ['', 'empty'], [[1], 'a reference'], ["\x{263a}", 'wide']) {
      my ($out, $name) = @$case;
      my $y = AWS::Signature::V4::X509->new(key_type => 'RSA', %x, signer => sub { $out });
      is dies { $y->signature('any/scope', 'anything') },
         bad_request('x509 signer returned'), "signer returns $name";
   }
   is dies { AWS::Signature::V4->new(service => 'iam', region => 'r',
      x509 => {key_type => 'RSA', %x, signer => sub { undef }})
      ->sign(method => 'GET', url => 'https://h/') },
      bad_request('x509 signer returned no signature'), 'sign reports the signer failure';
   my $z = AWS::Signature::V4::X509->new(key_type => 'RSA', %x, signer => sub { "\x{e9}" });
   is $z->signature('any/scope', 'anything'), 'e9', 'characters under 256 are bytes';

   is dies { AWS::Signature::V4::X509->new(%x) },
      bad_request('x509/key_type'), 'key type is needed';
   is dies { AWS::Signature::V4::X509->new(%x, key_type  => 'DSA') },
      bad_request('RSA or ECDSA'), 'key type is checked';
   is dies { AWS::Signature::V4::X509->new(key_type  => 'RSA', signer => sub { 1 }) },
      bad_request('certificate'), 'certificate is needed';
   is dies { AWS::Signature::V4::X509->new(key_type  => 'RSA', certificate => $der, serial => 1) },
      bad_request('signer'), 'a way to sign is needed';
};

subtest 'the main class gives the same results as the variants' => sub {
   my %cred = (access_key_id => 'AKID', secret_access_key => 'secret');
   my $s = AWS::Signature::V4->new(service => 'iam', region => 'us-east-1', credentials => {%cred});
   my $r = $s->sign(method => 'GET', url => 'https://iam.amazonaws.com/', time => 1440938160);
   my $c = AWS::Signature::V4::Credentials->new(%cred);
   is $r->{signature}, $c->signature($r->{scope}, $r->{string_to_sign}), 'credentials signature';
   is $s->algorithm, $c->algorithm, 'credentials algorithm';

   my $x = AWS::Signature::V4->new(
      service => 'iam', region => 'us-east-1',
      x509 => {key_type  => 'RSA', certificate => "\x30\x03\x02\x01\x05", serial => 9,
               signer => sub { 'sig' }});
   $r = $x->sign(method => 'GET', url => 'https://iam.amazonaws.com/', time => 1440938160);
   is $r->{signature}, unpack('H*', 'sig'), 'x509 signature';
   like $r->{authorization}, qr{Credential=9/20150830/us-east-1/iam/aws4_request}, 'x509 credential';
   ok exists $r->{headers}{'x-amz-x509'}, 'the certificate header';
   is $x->algorithm, 'AWS4-X509-RSA-SHA256', 'x509 algorithm';
};

done_testing;



( run in 2.371 seconds using v1.01-cache-2.11-cpan-0e0213f3164 )