| 1 |
use strict; |
| 2 |
use warnings; |
| 3 |
use Test::More; |
| 4 |
use Test::Fatal; |
| 5 |
use Encode qw(encode); |
| 6 |
|
| 7 |
use Dancer2::Core::Request; |
| 8 |
use Dancer2::Serializer::JSON; |
| 9 |
|
| 10 |
subtest 'request path decoding (lenient)' => sub { |
| 11 |
my $bytes = encode( 'UTF-8', "/\x{00F8}" ); |
| 12 |
my $req = Dancer2::Core::Request->new( |
| 13 |
env => { |
| 14 |
REQUEST_METHOD => 'GET', |
| 15 |
PATH_INFO => $bytes, |
| 16 |
}, |
| 17 |
); |
| 18 |
|
| 19 |
my $path = $req->path; |
| 20 |
is( ord( substr( $path, 1, 1 ) ), 0xF8, 'decoded UTF-8 path' ); |
| 21 |
ok( utf8::is_utf8($path), 'decoded path is characters' ); |
| 22 |
}; |
| 23 |
|
| 24 |
subtest 'request path decoding (invalid utf8, lenient)' => sub { |
| 25 |
my $bad = '/' . pack( 'C', 0xFF ); |
| 26 |
my $req = Dancer2::Core::Request->new( |
| 27 |
env => { |
| 28 |
REQUEST_METHOD => 'GET', |
| 29 |
PATH_INFO => $bad, |
| 30 |
}, |
| 31 |
); |
| 32 |
|
| 33 |
my @warnings; |
| 34 |
local $SIG{__WARN__} = sub { push @warnings, @_ }; |
| 35 |
my $path = $req->path; |
| 36 |
|
| 37 |
is( $path, $bad, 'invalid UTF-8 left as bytes' ); |
| 38 |
like( $warnings[0], qr/Invalid UTF-8/, 'warned on invalid UTF-8' ); |
| 39 |
}; |
| 40 |
|
| 41 |
subtest 'request path decoding (invalid utf8, strict)' => sub { |
| 42 |
my $req = Dancer2::Core::Request->new( |
| 43 |
env => { |
| 44 |
REQUEST_METHOD => 'GET', |
| 45 |
PATH_INFO => '/' . pack( 'C', 0xFF ), |
| 46 |
}, |
| 47 |
strict_utf8 => 1, |
| 48 |
); |
| 49 |
|
| 50 |
my $error = exception { $req->path }; |
| 51 |
like( $error, qr/Invalid UTF-8/, 'strict mode rejects invalid UTF-8' ); |
| 52 |
}; |
| 53 |
|
| 54 |
subtest 'json serialization (lenient + strict)' => sub { |
| 55 |
my $bad = pack( 'C', 0xFF ); |
| 56 |
|
| 57 |
my @warnings; |
| 58 |
my $serializer = Dancer2::Serializer::JSON->new( |
| 59 |
config => { strict_utf8 => 0 }, |
| 60 |
log_cb => sub { push @warnings, $_[1] }, |
| 61 |
); |
| 62 |
my $json = $serializer->serialize( { bad => $bad } ); |
| 63 |
ok( $json, 'serialize succeeded in lenient mode' ); |
| 64 |
like( $warnings[0], qr/Invalid UTF-8/, 'warned on invalid UTF-8' ); |
| 65 |
|
| 66 |
my $strict_bad = pack( 'C', 0xFF ); |
| 67 |
my $strict = Dancer2::Serializer::JSON->new( |
| 68 |
config => { strict_utf8 => 1 }, |
| 69 |
log_cb => sub {1}, |
| 70 |
); |
| 71 |
my $error = exception { $strict->serialize( { bad => $strict_bad } ) }; |
| 72 |
like( $error, qr/Invalid UTF-8/, 'strict mode rejects invalid UTF-8' ); |
| 73 |
}; |
| 74 |
|
| 75 |
done_testing(); |