AWS-S3

 view release on metacpan or  search on metacpan

t/aws/s3/request/xml_escape.t  view on Meta::CPAN

#!perl

use strict;
use warnings;

# Request bodies built from caller supplied values (object keys, bucket
# location) must be XML escaped, otherwise a crafted value can inject
# additional elements into the request, e.g. extra <Object> entries in a
# multi-object delete.

package Capturing::UA;

use parent 'LWP::UserAgent';

our @REQUESTS;

sub request {
    my ( $self, $req ) = @_;
    push @REQUESTS, $req;
    return HTTP::Response->new( 200, 'OK' );
}

package main;

use Test::More;
use XML::LibXML;

use_ok( 'AWS::S3' );

my $s3 = AWS::S3->new(
    access_key_id     => 'foo',
    secret_access_key => 'bar',
    endpoint          => 's3.baz.com',
    ua                => Capturing::UA->new,
);

sub _parse_body {
    my ( $req ) = @_;
    return XML::LibXML->new->parse_string( $req->content );
}

note( "_xml_escape" );
{
    my $req = $s3->request( 'DeleteMulti', bucket => 'maibucket', keys => [] );

    # check by parsing the result back rather than asserting on the exact
    # entities used, the contract is that the value round trips as text
    my %values = (
        'special characters'     => q{a&b<c>d"e'f},
        'carriage return'        => "line1\rline2",
        'CRLF'                   => "line1\r\nline2",
        'already looks escaped'  => '&amp; already looks escaped',
        'plain text'             => 'plain/key.txt',
    );

    foreach my $name ( sort keys %values ) {
        my $value = $values{$name};
        my $doc   = XML::LibXML->new->parse_string( '<a>' . $req->_xml_escape( $value ) . '</a>' );
        is( $doc->documentElement->textContent, $value, "round trips: $name" );
    }

    unlike( $req->_xml_escape( '<x>' ), qr/[<>]/, 'angle brackets are not left raw' );
    is( $req->_xml_escape( undef ), '', 'undef becomes empty string' );
}

note( "DeleteMulti" );
{
    @Capturing::UA::REQUESTS = ();

    my $evil = 'x</Key></Object><Object><Key>victim/important.txt';
    my @keys = ( 'normal.txt', $evil, 'a&b<c>.txt', "carriage\rreturn.txt" );

    $s3->request( 'DeleteMulti', bucket => 'maibucket', keys => \@keys )->request;

    is( scalar @Capturing::UA::REQUESTS, 1, 'one request sent' );

    my $doc;
    eval { $doc = _parse_body( $Capturing::UA::REQUESTS[0] ); 1 }
        or fail( "request body is well formed XML: $@" );

    my @sent = map { $_->textContent } $doc->findnodes( '/Delete/Object/Key' );

    is( scalar @sent, scalar @keys, 'one <Object> per supplied key, none injected' );
    is_deeply( \@sent, \@keys, 'keys round trip exactly as supplied' );
    unlike(
        $Capturing::UA::REQUESTS[0]->content,
        qr{<Key>victim/important\.txt</Key>},
        'injected key is not a standalone element',
    );
}

note( "CreateBucket" );
{



( run in 1.650 second using v1.01-cache-2.11-cpan-eb134014566 )