AWS-S3

 view release on metacpan or  search on metacpan

lib/AWS/S3/Roles/Request.pm  view on Meta::CPAN

package AWS::S3::Roles::Request;
use Moose::Role;
use HTTP::Request;
use HTTP::Date ();
use Digest::MD5 ();
use MIME::Base64 ();
use URI;
use HTML::Entities ();
use AWS::S3::ResponseParser;
use MooseX::Types::URI qw(Uri);
use URI::Escape qw/ uri_escape /;
use AWS::S3::Types;
use AWS::S3::Signer::V4;
use Log::Any qw( $LOG );

has 's3' => (
    is       => 'ro',
    isa      => 'AWS::S3',
    required => 1,
);

has 'type' => (
    is       => 'ro',
    isa      => 'Str',
    required => 1,
);

has 'protocol' => (
    is      => 'ro',
    isa     => 'Str',
    lazy    => 1,
    default => sub {
        shift->s3->secure ? 'https' : 'http';
    }
);

has 'endpoint' => (
    is      => 'ro',
    isa     => 'Str',
    lazy    => 1,
    default => sub {
        shift->s3->endpoint;
    }
);

# XXX should be required=>1; https://rt.cpan.org/Ticket/Display.html?id=77863
has "_action" => (
    isa       => 'Str',
    is        => 'ro',
    init_arg  => undef,
    #required  => 1
);

has '_expect_nothing' => ( isa => 'Bool', is => 'ro', init_arg => undef );

has '_uri' => (
    isa     => Uri,
    is      => 'ro',
    lazy    => 1,
    default => sub {
        my $self = shift;
        my $m = $self->meta;

        my $uri = URI->new(
            $self->protocol . '://'
            . ( $m->has_attribute('bucket') ? $self->bucket . '.' : '' )
            . $self->endpoint
            . '/'
        );

		# note we add some extra exceptions to uri_escape to prevent
		# encoding of things like "/", ":", "="
        if ( $m->has_attribute('key') ) {
            my $escaped_path = $self->_escape_key( $self->key );

            # if we have a leading slash in the key name we need to add *another*
            # slash in the call to ->path to ensure it is retained
            if ( $escaped_path =~ m!^/! && $self->s3->honor_leading_slashes ) {
                $uri->path( '/'.$escaped_path )
            } else {
                $uri->path( $escaped_path )
            }
        }

        $uri->query_keywords( $self->_subresource )
          if $m->has_attribute('_subresource');

        $uri;
    }
);

has 'signerv4' => (
    is       => 'ro',
    isa      => 'AWS::S3::Signer::V4',
    lazy     => 1,
    default  => sub {
        my $s = shift;
        AWS::S3::Signer::V4->new(
            -access_key => $s->s3->access_key_id,
            -secret_key => $s->s3->secret_access_key,
        );
    }
);

# uri_escape() croaks on characters above 0xFF, so encode those as UTF-8
# first, which is what URI does too. Byte strings are escaped as they were.
sub _uri_escape {
    my ( $s, $str, $unsafe ) = @_;

    return '' unless defined $str;
    utf8::encode( $str ) if $str =~ /[^\x00-\xFF]/;

    return defined $unsafe ? uri_escape( $str, $unsafe ) : uri_escape( $str );
}

# Escape an object key for use as the path of a URI; note we add some extra
# exceptions to uri_escape to prevent encoding of things like "/", ":", "="
sub _escape_key {
    my ( $s, $key ) = @_;

    return $s->_uri_escape( $key, "^A-Za-z0-9\-\._~\/:=" );
}

sub _send_request {
    my ( $s, $method, $uri, $headers, $content ) = @_;
    $LOG->debug('Making AWS request', {method => $method, uri => "$uri"});

    my $req = HTTP::Request->new( $method => $uri );
    $req->content( $content ) if $content;

    delete($headers->{Authorization}); # we will use a v4 signature
    map { $req->header( $_ => $headers->{$_} ) } keys %$headers;

    $s->_sign($req);
    my $res = $s->s3->ua->request( $req );

    # After creating a bucket and setting its location constraint, we get this
    # strange 'TemporaryRedirect' response.  Deal with it.
    if ( $res->header( 'location' ) && $res->content =~ m{>TemporaryRedirect<}s ) {
        my $location = eval { URI->new_abs( $res->header( 'location' ), $req->uri )->as_string };

        # never replay a signed request (which includes the session token and
        # the body) to somewhere we have no reason to trust, the response may
        # have been tampered with, particularly if we are not using https
        unless ( defined $location && $s->_is_trusted_redirect( $location ) ) {
            ( my $safe = $res->header( 'location' ) ) =~ s/[^\x21-\x7e]/?/g;
            $LOG->error( 'Refusing to follow redirect to untrusted location', { location => $safe } );
            die "Refusing to follow redirect to untrusted location '$safe'";
        }

        # the signature covers the host so the request must be signed again,
        # and the region may differ, a bucket in another region redirects us to
        # the regional endpoint, so take it from the host where we can
        $req->uri( $location );
        $req->remove_header( qw( Authorization Host X-Amz-Date ) );
        my ( undef, $region ) = $s->signerv4->parse_host( $req->uri->host );
        $s->_sign( $req, $region );
        $res = $s->s3->ua->request( $req );
    }
    return $s->parse_response( $res );
}

# A redirect is only trusted if it stays within the configured endpoint (or
# is an S3 hostname when that is an AWS endpoint), keeps to the same port, and
# doesn't downgrade from https.
sub _is_trusted_redirect {
    my ( $s, $location ) = @_;

    my $uri = eval { URI->new( $location ) } or return 0;

    my $scheme = $uri->scheme // '';
    return 0 unless $scheme eq 'http' || $scheme eq 'https';
    return 0 if $s->s3->secure && $scheme ne 'https';
    return 0 if defined $uri->userinfo;

    my $host = lc( $uri->host // '' );
    $host =~ s/\.\z//;
    return 0 unless length $host;

    my ( $endpoint_host, $endpoint_port ) = lc( $s->endpoint ) =~ m{\A([^:/]+)(?::(\d+))?\z}
        or return 0;
    $endpoint_host =~ s/\.\z//;
    return 0 unless length $endpoint_host;

    my $port = defined $endpoint_port ? $endpoint_port : $uri->default_port;
    return 0 unless $uri->port == $port;

    # S3 redirects to regional endpoints (e.g. bucket.s3-us-west-2.amazonaws.com)
    # so for AWS only trust S3 hostnames, not anything under amazonaws.com
    # (which includes things like ec2 and api gateway hostnames)
    if ( $endpoint_host =~ m{(?:\A|\.)(amazonaws\.com(?:\.cn)?)\z} ) {
        my $aws_domain = $1;
        return $host =~ m{(?:\A|\.)s3(?:[.-][a-z0-9-]+)*\.\Q$aws_domain\E\z} ? 1 : 0;
    }

    return ( $host eq $endpoint_host || $host =~ m{\.\Q$endpoint_host\E\z} ) ? 1 : 0;
}

sub _sign {
  my ($s, $request, $region) = @_;
  $region = $s->s3->region unless defined $region;
  my $signer = $s->signerv4;
  if (defined $s->s3->session_token) {
    $request->header('X-Amz-Security-Token', $s->s3->session_token);
  }
  my $digest = Digest::SHA::sha256_hex($request->content);
  $request->header('X-Amz-Content-SHA256', $digest);
  $signer->sign($request, $region, $digest);
  $request;
}

# the value of the Date header of a request
sub _http_date {
    return HTTP::Date::time2str( time );
}

# the value of a Content-MD5 header for the content (an empty string has an
# MD5 too, so only a missing value gives no header value)
sub _content_md5 {
    my ( $s, $content ) = @_;

    return '' unless defined $content;
    return MIME::Base64::encode_base64( Digest::MD5::md5( $content ), '' );
}

# Escape a value for safe use as XML character data (or inside an attribute).
# "\r" must be a character reference or the receiving XML parser will
# normalise it to "\n", silently changing the value.
sub _xml_escape {
    my ( $s, $str ) = @_;

    return '' unless defined $str;
    return HTML::Entities::encode_entities( $str, qq{<>&"'\r} );
}

sub parse_response {
    my ( $self, $res ) = @_;

    AWS::S3::ResponseParser->new(
        response       => $res,
        expect_nothing => $self->_expect_nothing,
        type           => $self->type,
    );
}

1;



( run in 1.156 second using v1.01-cache-2.11-cpan-0e0213f3164 )