File Coverage

blib/lib/Plack/Middleware/SecureHeaders.pm
Criterion Covered Total %
statement 28 28 100.0
branch 8 8 100.0
condition n/a
subroutine 7 7 100.0
pod 2 2 100.0
total 45 45 100.0


line stmt bran cond sub pod time code
1             package Plack::Middleware::SecureHeaders;
2 5     5   7404 use strict;
  5         12  
  5         138  
3 5     5   27 use warnings;
  5         8  
  5         140  
4 5     5   386 use parent qw( Plack::Middleware );
  5         273  
  5         27  
5              
6             our $VERSION = "0.01";
7              
8 5     5   12552 use HTTP::SecureHeaders;
  5         5466  
  5         167  
9 5         48 use Plack::Util::Accessor qw(
10             secure_headers
11 5     5   33 );
  5         9  
12              
13             sub prepare_app {
14 12     12 1 31100 my $self = shift;
15 12 100       44 unless (defined $self->secure_headers) {
16 6         158 $self->secure_headers(HTTP::SecureHeaders->new)
17             }
18             }
19              
20             sub call {
21 12     12 1 92429 my($self, $env) = @_;
22              
23 12         73 my $res = $self->app->($env);
24 12         161 my $headers = Plack::Util::headers($res->[1]);
25              
26 12 100       391 unless ($headers->exists('Content-Type')) {
27 1         41 die sprintf('Required Content-Type header. %s %s', $env->{REQUEST_METHOD}, $env->{PATH_INFO});
28             }
29              
30             # NOTE: the charset attribute is necessary to prevent XSS in HTML pages
31             # https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html#content-type
32 11 100       323 if ($headers->get('Content-Type') =~ qr!^text/html!i) {
33 2 100       63 unless ($headers->get('Content-Type') =~ qr!charset=\w+!) {
34             die sprintf('Required charset for text/html. %s %s', $env->{REQUEST_METHOD}, $env->{PATH_INFO})
35 1         36 }
36             }
37              
38 10         332 $self->secure_headers->apply($headers);
39              
40 10         7082 return $res;
41             }
42              
43             1;
44             __END__