AWS-Signature-V4

 view release on metacpan or  search on metacpan

MANIFEST  view on Meta::CPAN

dist.ini
eg/01-sts-get-caller-identity.pl
eg/02-s3-get-object.pl
eg/03-s3-put-object-from-file.pl
eg/04-s3-presigned-urls.pl
eg/05-s3-chunked-upload.pl
eg/06-dynamodb-json-api.pl
eg/07-rolesanywhere-x509.pl
eg/08-x509-custom-signer.pl
eg/09-inspect-a-signature.pl
eg/10-s3-content-encoding-probe.pl
eg/README.md
lib/AWS/Signature/V4.pm
lib/AWS/Signature/V4.pod
lib/AWS/Signature/V4/Checksum.pm
lib/AWS/Signature/V4/Checksum.pod
lib/AWS/Signature/V4/Chunker.pm
lib/AWS/Signature/V4/Chunker.pod
lib/AWS/Signature/V4/Credentials.pm
lib/AWS/Signature/V4/Credentials.pod
lib/AWS/Signature/V4/Error.pm

README  view on Meta::CPAN

      signature is made with the private key that goes with the
      certificate, using CryptX (Crypt::PK::RSA and Crypt::PK::ECC) or a
      signing function of your own.

    Both header-based signing ("sign") and presigned URLs ("presign") are
    available, as well as chunked and streaming uploads to S3 (see "sign"
    and "encoded_length") and hashing of large payloads without loading
    them in memory.

    Some conventions apply to the inputs, because what is signed has to be
    exactly what goes on the wire and the module cannot guess an encoding:

      * the url must be ASCII, with anything else already percent-encoded;

      * the body is a byte string, or a reference to one: encode text as
      the user agent will, wide characters are an error;

      * headers are a hash reference or an array reference of pairs, with
      names that are case insensitive.

    Defaults that depend on the service (e.g. S3 handles path encoding
    differently from all other services) are set from the service name, and
    can be overridden (see "new").

INTERFACE

 new

       my $s = AWS::Signature::V4->new(%args);

    Create a signer. service and region are mandatory (for the X.509

README  view on Meta::CPAN


      An X-Amz-Content-Sha256 header is taken as the payload hash; if the
      payload hash also comes from the arguments below, the two must agree;

    body, body_fh

      the payload, as a byte string, a reference to one (which avoids
      copying large data around) or an open filehandle. The filehandle is
      hashed from its current position to its end, without loading it in
      memory, and put back where it was: so it must be seekable (a file,
      not a pipe or a socket) and binary, without layers like :encoding or
      :crlf that change the bytes read. Only one of them can be used;

    payload_hash, unsigned_payload

      skip the calculation and use the provided SHA-256 in hex, or
      UNSIGNED-PAYLOAD. They take precedence over body and body_fh.
      payload_hash can also be a STREAMING-* marker, anything else is an
      error. When the payload hash is not a SHA-256, the
      x-amz-content-sha256 header carries it, whatever the service;

README  view on Meta::CPAN

    canonical_request, string_to_sign

      the intermediate values of the algorithm, handy for debugging;

    chunker

      only when streaming: see below.

  Chunked and streaming uploads

    streaming enables the aws-chunked encoding used for uploads to S3,
    where the body is sent in chunks that are signed as they go. It can be
    1 or signed (each chunk is signed, credentials variant only) or
    unsigned (no chunk signatures, only the request headers are signed,
    also OK with X.509). The decoded_content_length, i.e. the size of the
    data, is mandatory. sign sets the payload hash to
    STREAMING-AWS4-HMAC-SHA256-PAYLOAD (or its variants below), adds
    x-amz-decoded-content-length and aws-chunked to Content-Encoding (after
    any other encoding, e.g. gzip,aws-chunked, as it is the one applied
    last: S3 takes that token off the end and stores what is left, here
    gzip), all signed; the Content-Length to provide is the size of the
    encoded body, see "encoded_length". S3 wants all chunks but the last
    one to be at least 8 KiB. body, body_fh, payload_hash and
    unsigned_payload do not apply.

       my $length = AWS::Signature::V4->encoded_length($decoded_length, $chunk_size);
       my $r = $s->sign(
          method => 'PUT', url => $url,
          headers => { 'Content-Length' => $length },

TODO.md  view on Meta::CPAN

- have the findings saved to `tmp/review-<n>-<name>.md` (`tmp/` is
  git-ignored), so that nothing is lost between sessions;
- fix after each chunk, or collect all the findings first and fix them
  together.

Chunks 1 to 3 cover all the code: stopping after them already gives a
baseline for everything that runs.

- [x] **1. Signing core** (level `max`, ~890 lines):
      `lib/AWS/Signature/V4.pm` with `t/canonical.t`, `t/basic.t`,
      `t/presign.t`. Canonical request, encoding, presign,
      `encoded_length`.
- [x] **2. Streaming** (level `high`, ~440 lines):
      `lib/AWS/Signature/V4/Chunker.pm`, `Checksum.pm` with
      `t/streaming.t`, `t/trailer.t`.
- [x] **3. Variants and errors** (level `high`, ~760 lines):
      `lib/AWS/Signature/V4/X509.pm`, `Credentials.pm`, `Error.pm` with
      `t/chain.t`, `t/variants.t`, `t/error.t`, `t/errors.t`,
      `t/security.t`. DER parsing, key loading.
- [x] **4. Documentation** (level `medium`, ~1140 lines): all the `.pod`
      files, checked against the code: do they promise anything that the

TODO.md  view on Meta::CPAN

      sent `aws-chunked` alone, came back stored as no `Content-Encoding`
      at all; the real case, which sent `gzip,aws-chunked`, came back
      stored as `gzip`. So S3 strips the `aws-chunked` token from the end
      of the list and keeps what is left, which is what RFC 9110 and
      botocore describe. Both objects round-tripped byte-identical.

      What follows is the question as it stood, kept because it explains
      why the module emits this order and how to ask again if AWS ever
      answers differently.

      With `streaming` and an encoding already set by the caller, `sign`
      emits `gzip,aws-chunked` (`lib/AWS/Signature/V4.pm`, in the
      `$streaming` branch; asserted in `t/streaming.t` and documented in
      `V4.pod` under `sign`). This was the only behaviour in the module
      chosen from indirect evidence rather than from AWS itself, because
      the authorities contradict each other:

      - RFC 9110 §8.4 wants the encodings in the order they were applied,
        and `aws-chunked` is the outermost one, applied to the already
        compressed data: `gzip,aws-chunked`;
      - botocore (`httpchecksum.py`) agrees, appending: `headers
        ["Content-Encoding"] += ",aws-chunked"`;
      - the first review cited the S3 documentation for the opposite
        order, and a boto3 issue reports seeing `aws-chunked,gzip` in
        stored metadata.

      The guess was that S3 strips the `aws-chunked` token from either
      position, so that both orders would be accepted and the point would
      be moot; the run above confirms the stripping, at least from the
      end. It does not say what the other order would do, and there is no
      reason to find out while the module sends this one.

      `eg/10-s3-content-encoding-probe.pl` settled it. It uploads a
      gzipped object with `streaming`, plus a control without any
      `Content-Encoding` so that a rejection can be told apart from a
      wrong bucket, region or set of credentials; it reads both back,
      checks the bytes round-trip, and deletes them again. Run it against
      a bucket that can be written to:

      ```shell
      AWS_REGION=eu-west-1 \
         AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... \
         ./eg/10-s3-content-encoding-probe.pl my-bucket
      ```

      It exits zero and prints `verdict: S3 accepted gzip,aws-chunked`
      when the order the module sends works, which is what it did. If a
      later run somewhere else has the control accepted and the gzip case
      refused, the order is wrong there: swap the last line of the
      `$streaming` branch in `lib/AWS/Signature/V4.pm` to

      ```perl
      join ',', 'aws-chunked', @encodings;
      ```

      update the sentence under `sign` in `V4.pod` and the two
      `content-encoding` assertions in `t/streaming.t` to match, and run
      the probe again to confirm. The report it prints holds no
      credentials, no `Authorization` header and neither bucket nor key,
      so it is safe to paste into a chat or a bug report.

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

#!/usr/bin/env perl
# Does S3 accept the Content-Encoding order that this module sends?
#
#    ./10-s3-content-encoding-probe.pl BUCKET [KEY_PREFIX]
#
# With streaming, sign() has to add "aws-chunked" to whatever
# Content-Encoding the caller already set. RFC 9110 and botocore put it
# last ("gzip,aws-chunked"), because aws-chunked is applied to the
# already compressed data; the S3 documentation was read the other way
# round in an earlier review of this distribution. See TODO.md: nothing
# but a real bucket can settle it, and this is the program that asks.
#
# Two objects are uploaded: a control with no Content-Encoding of its
# own, and the real case with gzip. The control tells a wrong order apart

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

         $c->{extra}->%*,
         'Content-Type' => 'text/plain',
         # length of the *encoded* body: data plus the chunk framing
         'Content-Length' => AWS::Signature::V4->encoded_length($size, $chunk_size),
      },
      streaming              => 1,
      decoded_content_length => $size,
   );
   # what the module decided to send, rather than what we assume it sends:
   # this is the whole question, and it must be reported as it is
   $c->{sent}     = $r->{headers}{'content-encoding'};
   $c->{announced} = $r->{headers}{'content-length'};
   # the encoded body is built once, whole, and sent as a string. A
   # callback would be the thing to do for a real upload (example 05 does
   # that), but HTTP::Tiny retries an idempotent request once when the
   # socket breaks under it, and this body cannot be produced a second
   # time: the chunk signatures chain, and finish() has already been
   # called, so the retry would send nothing and fail on the length --
   # reported as a 599, which reads like a refusal and is not one. A few
   # hundred bytes in memory buy a run that means what it says
   my $chunker = $r->{chunker};

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

      $c->{put_error} = s3_error($put);
      $c->{s3_code}   = s3_code($put);
      next;
   }
   $c->{ok} = 1;

   my $g = $signer->sign(method => 'GET', url => $url);
   my $get = $http->get($url, {headers => without_host($g)});
   $c->{get} = status_of($get);
   if ($get->{success}) {
      $c->{stored} = header_of($get, 'content-encoding');
      my $got = $get->{content} // '';
      $c->{body} =
           $got eq $gz    ? 'identical'
         : $got eq $plain ? 'DECOMPRESSED on the way (S3 or the client unzipped it)'
         : sprintf('DIFFERENT (%d bytes back, %d sent)', length $got, $size);
   }
   else { $c->{get_error} = s3_error($get) }

   next if $ENV{KEEP};
   my $d = $signer->sign(method => 'DELETE', url => $url);

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

   push @out, '          stored is not what this probe expects: read the stored';
   push @out, '          Content-Encoding and the body line above, because the';
   push @out, '          upload being accepted is then not the whole story.';
   $status = 1;
}
elsif ($refused) {
   push @out, "verdict:  S3 REJECTED $gzip_case->{sent} with $gzip_case->{s3_code},";
   push @out, "          while accepting $control->{sent} alone, so the order is";
   push @out, '          the problem. Swap the last line of the $streaming';
   push @out, '          branch in lib/AWS/Signature/V4.pm to';
   push @out, q{             join ',', 'aws-chunked', @encodings;};
   push @out, '          update V4.pod and t/streaming.t to match, and run';
   push @out, '          this program again to confirm the other order.';
   $status = 1;
}
else {
   push @out, 'verdict:  INCONCLUSIVE. The gzip upload failed, but not with a';
   push @out, '          refusal from S3, so it says nothing about the order:';
   push @out, '          see the error line above, then run it again.';
   $status = 1;
}

eg/README.md  view on Meta::CPAN

dot, and the answer is not to turn TLS verification off: use the
path-style URL `https://s3.REGION.amazonaws.com/BUCKET/KEY` for those
buckets.

Because the bucket and `AWS_REGION` end up in the host name, they are
checked before use, as in 10: a `/` in either would move the host
somewhere else altogether (a bucket of `evil.example.com/x` gives
`https://evil.example.com/x.s3...`) and the request would be signed and
sent there, session token and all. The key needs no such check, since it
lands in the path: `sign` already refuses control characters in the URL,
and the rest is the encoding caveat above.


## 03-s3-put-object-from-file.pl

Upload a file to S3 without loading it in memory: the payload hash is
computed from a filehandle (`body_fh`, which is left where it was), and
`HTTP::Tiny` then reads the same file a piece at a time when sending.

```shell
./eg/03-s3-put-object-from-file.pl backup.tar.gz my-bucket backups/backup.tar.gz

eg/README.md  view on Meta::CPAN

authorization header), which is what helps when AWS answers
`SignatureDoesNotMatch`. The time is fixed, so the output is always the
same, and the program tells whether the signature matches the one in the
documentation.

```shell
./eg/09-inspect-a-signature.pl
```


## 10-s3-content-encoding-probe.pl

Not a usage example but a diagnostic probe, kept here because it is built
out of the same pieces as 05. With `streaming`, `sign` adds `aws-chunked`
to whatever `Content-Encoding` the caller already set, and the authorities
disagree on the order: this uploads a gzipped object and reports whether
S3 takes the one the module sends (see the note in `TODO.md`).

It writes two objects to the bucket it is given, a control without any
`Content-Encoding` and the real case with gzip, so that a rejection can
be told apart from a wrong bucket, region or set of credentials. It reads

eg/README.md  view on Meta::CPAN

nothing and refuses to run otherwise, treating anything but a clear "not
there" as occupied. That check needs `s3:ListBucket` on the bucket:
without it S3 answers a HEAD on a key that does not exist with 403
rather than 404, a free key cannot be told from a forbidden one, and the
program stops and says so. The bucket, the region and the key prefix are also
checked before use: they are pasted into the URL, and a `/` in the bucket
or the region would move the host elsewhere and send the signed request,
session token included, to whatever is there.

```shell
./eg/10-s3-content-encoding-probe.pl my-bucket
AWS_REGION=eu-west-1 ./eg/10-s3-content-encoding-probe.pl my-bucket scratch/probe-
KEEP=1 ./eg/10-s3-content-encoding-probe.pl my-bucket
DRY_RUN=1 ./eg/10-s3-content-encoding-probe.pl my-bucket
```

A verdict is only reached when the run earns it. "Accepted" needs more
than a 200: S3 must also have stored the object as `Content-Encoding:
gzip`, having taken the `aws-chunked` token off, and have given the bytes
back unchanged. "Rejected", which tells you to change the order in the
signing code, needs S3 itself to have turned the upload down — a 4xx
carrying an S3 error code, and not one of the 401 and 403 that talk
about the credentials rather than the header. Everything else, a 503, a
dropped connection, a key that expired halfway through, is reported as

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

      fail 400, 'decoded_content_length must be a non-negative integer'
         unless $len =~ m{\A[0-9]+\z};
      $payload_hash =
           $unsigned_chunks ? 'STREAMING-UNSIGNED-PAYLOAD-TRAILER'
         : @trailer_names   ? 'STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER'
         :                    'STREAMING-AWS4-HMAC-SHA256-PAYLOAD';
      $h->{'x-amz-decoded-content-length'} = $len;
      $h->{'x-amz-trailer'} = join ',', @trailer_names if @trailer_names;

      # whatever the caller has, e.g. gzip, then aws-chunked: RFC 9110 wants
      # the encodings in the order they were applied, and this one is the
      # outermost, applied to the already-gzipped data (as botocore does)
      my @encodings = grep { length && lc($_) ne 'aws-chunked' }
         map { _trim($_) } split m{,}, $h->{'content-encoding'} // '';
      $h->{'content-encoding'} = join ',', @encodings, 'aws-chunked';
   }
   else {
      $payload_hash = _payload_hash(\%args);
   }
   $payload_hash = _agree($payload_hash, $given, sha256_hex(''));
   $h->{'x-amz-content-sha256'} = $payload_hash
      if $self->payload_header || $streaming || defined $given || !_is_sha256($payload_hash);

   my %extra = $self->_auth->extra_fields;
   $h->{lc $_} = $extra{$_} for keys %extra;
   _check_header_values($h);    # before they end up in the canonical request

   my @signed = _signed_headers($h, $args{signed_headers}
      // [grep { ! UNSIGNED->{$_} } keys $h->%*], $streaming ? 'content-encoding' : ());
   my $r = $self->_signed($method, $path, _canonical_query($query), $h,
      \@signed, $payload_hash, $amzdate, $scope);

   my $credential = $self->_auth->credential_id . "/$scope";
   $r->{authorization} = $self->algorithm . " Credential=$credential, "
      . "SignedHeaders=$r->{signed_headers}, Signature=$r->{signature}";
   _check_header_value(authorization => $r->{authorization});
   $r->{headers} = {$h->%*, authorization => $r->{authorization}};

   $r->{chunker} = AWS::Signature::V4::Chunker->new(

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

=pod

=for vim
   vim: tw=72 ts=3 sts=3 sw=3 et ai :

=encoding utf8

=head1 NAME

AWS::Signature::V4 - User-Agent agnostic AWS Signatures V4 for credentials and X509


=head1 VERSION

This document describes AWS::Signature::V4 version 0.004.

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

function of your own.

=back

Both header-based signing (L</sign>) and presigned URLs (L</presign>)
are available, as well as chunked and streaming uploads to S3 (see
L</sign> and L</encoded_length>) and hashing of large payloads without
loading them in memory.

Some conventions apply to the inputs, because what is signed has to be
exactly what goes on the wire and the module cannot guess an encoding:

=over

=item *

the C<url> must be ASCII, with anything else already percent-encoded;

=item *

the body is a I<byte string>, or a reference to one: encode text as the
user agent will, wide characters are an error;

=item *

headers are a hash reference or an array reference of pairs, with names
that are case insensitive.

=back

Defaults that depend on the service (e.g. S3 handles path encoding
differently from all other services) are set from the C<service> name,
and can be overridden (see L</new>).


=head1 INTERFACE

=head2 new

   my $s = AWS::Signature::V4->new(%args);

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


An C<X-Amz-Content-Sha256> header is taken as the payload hash; if the
payload hash also comes from the arguments below, the two must agree;

=item C<body>, C<body_fh>

the payload, as a byte string, a reference to one (which avoids copying
large data around) or an open filehandle. The filehandle is hashed
from its current position to its end, without loading it in memory, and
put back where it was: so it must be seekable (a file, not a pipe or a
socket) and binary, without layers like C<:encoding> or C<:crlf> that
change the bytes read. Only one of them can be used;

=item C<payload_hash>, C<unsigned_payload>

skip the calculation and use the provided SHA-256 in hex, or
C<UNSIGNED-PAYLOAD>. They take precedence over C<body> and C<body_fh>.
C<payload_hash> can also be a C<STREAMING-*> marker, anything else is an
error. When the payload hash is not a SHA-256, the
C<x-amz-content-sha256> header carries it, whatever the service;

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

the intermediate values of the algorithm, handy for debugging;

=item C<chunker>

only when streaming: see below.

=back

=head3 Chunked and streaming uploads

C<streaming> enables the C<aws-chunked> encoding used for uploads to S3,
where the body is sent in chunks that are signed as they go. It can be
C<1> or C<signed> (each chunk is signed, credentials variant only) or
C<unsigned> (no chunk signatures, only the request headers are signed,
also OK with X.509). The C<decoded_content_length>, i.e. the size of
the data, is mandatory. C<sign> sets the payload hash to
C<STREAMING-AWS4-HMAC-SHA256-PAYLOAD> (or its variants below), adds
C<x-amz-decoded-content-length> and C<aws-chunked> to C<Content-Encoding>
(after any other encoding, e.g. C<gzip,aws-chunked>, as it is the one
applied last: S3 takes that token off the end and stores what is left,
here C<gzip>), all signed; the C<Content-Length> to provide is the size
of the encoded body, see L</encoded_length>. S3 wants all chunks but the last
one to be at least 8 KiB. C<body>, C<body_fh>, C<payload_hash> and
C<unsigned_payload> do not apply.

   my $length = AWS::Signature::V4->encoded_length($decoded_length, $chunk_size);
   my $r = $s->sign(
      method => 'PUT', url => $url,
      headers => { 'Content-Length' => $length },

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

=pod

=for vim
   vim: tw=72 ts=3 sts=3 sw=3 et ai :

=encoding utf8

=head1 NAME

AWS::Signature::V4::Checksum - Incremental checksums for S3 trailers


=head1 VERSION

This module is part of the L<AWS::Signature::V4> distribution and shares
its version.

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

=pod

=for vim
   vim: tw=72 ts=3 sts=3 sw=3 et ai :

=encoding utf8

=head1 NAME

AWS::Signature::V4::Chunker - Encode the body of an aws-chunked upload


=head1 VERSION

This module is part of the L<AWS::Signature::V4> distribution and shares
its version.

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

   );

   my $chunker = $r->{chunker};
   print {$socket} $chunker->chunk($_) for @pieces;
   print {$socket} $chunker->finish;


=head1 DESCRIPTION

This module wraps the data of an S3 upload into the C<aws-chunked>
encoding: each piece is prefixed by its size and, for the signed
variants, by a signature that depends on the previous one.

B<You are not supposed to use this module directly.> Objects are created
by L<AWS::Signature::V4/sign> when called with C<streaming>, and returned
in the C<chunker> key of its result. Only then do they hold what they need
to sign: the derived signing key, the scope, the date and the signature of
the request itself (the "seed" of the chain). The constructor is
therefore an internal detail and its arguments are not a stable
interface; the options that matter (C<streaming>, C<checksum>,
C<trailers>, C<decoded_content_length>) are all described in

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

=pod

=for vim
   vim: tw=72 ts=3 sts=3 sw=3 et ai :

=encoding utf8

=head1 NAME

AWS::Signature::V4::Credentials - The credentials-based variant of AWS Signature V4


=head1 VERSION

This module is part of the L<AWS::Signature::V4> distribution and shares
its version.

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

=pod

=for vim
   vim: tw=72 ts=3 sts=3 sw=3 et ai :

=encoding utf8

=head1 NAME

AWS::Signature::V4::Error - Throw the errors of AWS::Signature::V4


=head1 VERSION

This module is part of the L<AWS::Signature::V4> distribution and shares
its version.

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

=pod

=for vim
   vim: tw=72 ts=3 sts=3 sw=3 et ai :

=encoding utf8

=head1 NAME

AWS::Signature::V4::X509 - The certificate-based variant of AWS Signature V4


=head1 VERSION

This module is part of the L<AWS::Signature::V4> distribution and shares
its version.

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

         -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

=head1 USAGE

   aws-iam-ra [--help] [--man] [--usage] [--version]

   aws-iam-ra --certificate|-c <path>

t/streaming.t  view on Meta::CPAN

      'Content-Encoding'    => 'aws-chunked',
      'Content-Length'      => 66824,
   },
   streaming              => 1,
   decoded_content_length => 66560,
   time                   => 1369353600,
);
like $r->{authorization}, qr/Signature=4f232c4386841ef735655705268965c44a0e4690baa4adea153f7db9fa80a0a9$/,
   'seed signature matches AWS docs';
is $r->{signed_headers},
   'content-encoding;content-length;host;x-amz-content-sha256;x-amz-date;x-amz-decoded-content-length;x-amz-storage-class',
   'signed headers';
is $r->{headers}{'x-amz-content-sha256'}, 'STREAMING-AWS4-HMAC-SHA256-PAYLOAD', 'payload marker';
is $r->{headers}{'x-amz-decoded-content-length'}, 66560, 'decoded length header';

my $ck = $r->{chunker};
my $first = 'a' x 65536;
my $c1 = $ck->chunk(\$first);
like $c1, qr/\A10000;chunk-signature=ad80c730a21e5b8d04586a2213dd63b9a0e99e0e2307b0ade35a65485a288648\r\n/,
   'first chunk signature matches';
my $c2 = $ck->chunk('a' x 1024);

t/streaming.t  view on Meta::CPAN

is $c3, "0;chunk-signature=b6c6ea8a5354eaf15b3cb7646744f4275b71ea724fed81ceb9323e279d449df9\r\n\r\n",
   'final chunk matches';
is length($c1 . $c2 . $c3), 66824, 'body is as long as announced';
is substr($c1, -2), "\r\n", 'chunk ends with CRLF';
ok dies { $ck->finish }, 'cannot finish twice';
ok dies { $ck->chunk('x') }, 'nor add chunks afterwards';

# defaults and validation
$r = $s3->sign(method => 'PUT', url => 'https://h/k', streaming => 1,
   decoded_content_length => 0, time => 0);
is $r->{headers}{'content-encoding'}, 'aws-chunked', 'Content-Encoding added';
$r = $s3->sign(method => 'PUT', url => 'https://h/k', streaming => 1,
   decoded_content_length => 0, headers => {'Content-Encoding' => 'gzip'}, time => 0);
is $r->{headers}{'content-encoding'}, 'gzip,aws-chunked', 'aws-chunked goes after an existing Content-Encoding';
$r = $s3->sign(method => 'PUT', url => 'https://h/k', streaming => 1,
   decoded_content_length => 0, headers => {'Content-Encoding' => 'AWS-Chunked, gzip'}, time => 0);
is $r->{headers}{'content-encoding'}, 'gzip,aws-chunked', 'and it is not repeated';
like $r->{signed_headers}, qr/\bcontent-encoding\b/, 'Content-Encoding is signed';
$r = $s3->sign(method => 'PUT', url => 'https://h/k', streaming => 1,
   decoded_content_length => 0, signed_headers => [], time => 0);
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' },

t/streaming.t  view on Meta::CPAN

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;
is dies { $std->sign(method => 'PUT', url => 'https://h/', body_fh => $text) },
   bad(qr/binary/), 'a handle with an encoding layer is refused';
open my $wo, '>>', $file or die;
is dies { $std->sign(method => 'PUT', url => 'https://h/', body_fh => $wo) },
   bad(qr/cannot be read/), 'a write-only handle is refused';
close $wo;

# encoded_length checks what it gets
my %bad_length = (
   'signed as a word'   => [[10, 4, checksum => 'crc32', signed => 'yes'], qr/signed/],
   'negative size'      => [[-5, 10], qr/decoded size/],
   'fractional size'    => [[10.5, 4], qr/decoded size/],

t/trailer.t  view on Meta::CPAN

   is $ck->chunk(\'123456789'), "9\r\n123456789\r\n", 'and a scalar reference is fine';
   like $ck->finish, qr/x-amz-checksum-crc32c:\Q$expect{crc32c}\E\r\n/, 'the refused pieces were not counted';
}

# --- request side
my $r = start($x, streaming => 'unsigned', checksum => 'crc32c');
is $r->{headers}{'x-amz-content-sha256'}, 'STREAMING-UNSIGNED-PAYLOAD-TRAILER', 'unsigned marker';
is $r->{headers}{'x-amz-trailer'}, 'x-amz-checksum-crc32c', 'x-amz-trailer';
like $r->{signed_headers}, qr/x-amz-trailer/, 'and it is signed';
is $r->{headers}{'x-amz-decoded-content-length'}, 9, 'decoded length';
is $r->{headers}{'content-encoding'}, 'aws-chunked', 'content encoding';
ok !defined $r->{chunker}->_mac, 'unsigned chunker has no key';

$r = start($s3, streaming => 'signed', checksum => 'sha256');
ok !(grep { defined && !ref && ($_ eq $key || $_ eq unpack 'H*', $key) } values $r->{chunker}->%*),
   'signed chunker: the key is not in the object';
is $r->{headers}{'x-amz-content-sha256'}, 'STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER', 'signed trailer marker';
$r = start($s3, streaming => 1);
is $r->{headers}{'x-amz-content-sha256'}, 'STREAMING-AWS4-HMAC-SHA256-PAYLOAD', 'no trailer: plain marker';
ok !exists $r->{headers}{'x-amz-trailer'}, 'and no x-amz-trailer';



( run in 2.684 seconds using v1.01-cache-2.11-cpan-39bc3f1cbff )