Base.pm 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. package Trog::Renderer::Base;
  2. use 5.040;
  3. use re '/aasx';
  4. use Encode qw{encode_utf8};
  5. use IO::Compress::Gzip;
  6. use Text::Xslate;
  7. use Trog::Component ();
  8. use Trog::Themes;
  9. use Trog::Config;
  10. use Time::HiRes qw{tv_interval};
  11. =head1 Trog::Renderer::Base
  12. Basic rendering structure, subclass me.
  13. Sets up the functions which must be present for all templates: render_it, for rendering dynamic template strings coming from a post, and component, for pulling in a Trog::Component by name.
  14. =cut
  15. our %renderers;
  16. =head2 render(%options)
  17. Render a template and build the PSGI response around it.
  18. Recognized options:
  19. template => the template's filename, relative to the template dir. Required.
  20. contenttype => what we're rendering, e.g. 'text/html'. Picks the template dir.
  21. component => render a component rather than a whole page. Returns just the
  22. body string, with no headers and no compression.
  23. data => the variables handed to the template.
  24. code => HTTP status for the response.
  25. headers => extra headers, merged over the computed ones.
  26. deflate => gzip the body and set Content-Encoding.
  27. post_processor => CODEREF run over the body before headers are computed, for
  28. things like minifiers.
  29. child_processor / child_renderer => override how post bodies are rendered by
  30. the render_it() template function. Built for you if omitted.
  31. Dies unless Xslate can resolve and render the template. Returns the body
  32. string for components, and a PSGI arrayref of [ code, headers, body ] otherwise.
  33. =cut
  34. sub render (%options) {
  35. die "Templated renders require a template to be passed" unless $options{template};
  36. # Xslate resolves includes against every dir in path, first match winning,
  37. # so handing it both lets a theme override individual templates without
  38. # having to fork the ones next to them. With no theme configured this is
  39. # just the stock dir, exactly as it was.
  40. my @template_dirs = Trog::Themes::template_dirs( $options{contenttype}, $options{component} );
  41. #TODO make this work with posts all the time
  42. $options{child_processor} //= Text::Xslate->new( path => \@template_dirs );
  43. my $child_processor = $options{child_processor};
  44. $options{child_renderer} //= sub {
  45. my ( $template_string, $options ) = @_;
  46. # If it fails to render, it must be something else
  47. my $out = eval { $child_processor->render_string( $template_string, $options ) };
  48. return $out ? $out : $template_string;
  49. };
  50. # Keyed on the whole search path, not just the winning dir: two different
  51. # paths that happen to start with the same dir are not the same renderer.
  52. my $renderer_key = join( ':', @template_dirs );
  53. $renderers{$renderer_key} //= Text::Xslate->new(
  54. path => \@template_dirs,
  55. function => {
  56. render_it => $options{child_renderer},
  57. # A plain package sub rather than a closure, so the \%renderers
  58. # memoization here cannot bake in whatever the first caller for this
  59. # path happened to pass -- which it can, and does, for render_it.
  60. component => \&Trog::Component::component,
  61. },
  62. );
  63. my $code = $options{code};
  64. # Xslate resolves the template itself, against the same @template_dirs it
  65. # will actually use. There used to be a pre-flight test here, and it was
  66. # wrong twice over: it resolved through template_dir(), which returns one
  67. # winning directory rather than the search path, so it could pass on a file
  68. # Xslate would not use and name a nonexistent stock path in its error while
  69. # a good theme template existed. And the condition itself, -f $t || -s $t,
  70. # short-circuited on -f, so an empty file passed, while a *directory* passed
  71. # on -s returning its size.
  72. #
  73. # $Trog::Component::error is how a failed component() call reaches us at all:
  74. # Xslate catches an exception thrown out of a template function, warns, and
  75. # renders on with an empty string in its place, so the render below succeeds
  76. # with a hole in it. Localised here so that a nested render (a component
  77. # rendering its own template) doesn't answer for its parent's failure.
  78. my $body = eval {
  79. local $Trog::Component::error;
  80. my $out = encode_utf8( $renderers{$renderer_key}->render( $options{template}, $options{data} ) );
  81. die $Trog::Component::error if $Trog::Component::error;
  82. $out;
  83. };
  84. die "Could not render template '$options{template}' (searched @template_dirs): $@" unless defined $body;
  85. # Users can supply a post_processor to futz with the output (such as with minifiers) if they wish.
  86. $body = $options{post_processor}->($body) if $options{post_processor} && ref $options{post_processor} eq 'CODE';
  87. # Users can supply custom headers as part of the data in options.
  88. my %headers = headers( \%options, $body );
  89. return $body if $options{component};
  90. return [ $code, [%headers], [$body] ] unless $options{deflate};
  91. $headers{"Content-Encoding"} = "gzip";
  92. my $dfh;
  93. IO::Compress::Gzip::gzip( \$body => \$dfh );
  94. print $IO::Compress::Gzip::GzipError if $IO::Compress::Gzip::GzipError;
  95. $headers{"Content-Length"} = length($dfh);
  96. return [ $code, [%headers], [$dfh] ];
  97. }
  98. =head2 headers($options, $body) = %headers
  99. The response headers for a rendered body: content type and length, caching,
  100. Server-Timing, and the security headers (CSP, X-Frame-Options, HSTS when we're
  101. on https, nosniff). Anything in $options->{headers} is merged over the top.
  102. ETags are only set for logged in users, as everyone else is served out of the
  103. static render cache.
  104. =cut
  105. sub headers ( $options, $body ) {
  106. my $query = $options->{data};
  107. my $uh = ref $options->{headers} eq 'HASH' ? $options->{headers} : {};
  108. my $ct = $options->{contenttype} eq 'text/html' ? "text/html; charset=UTF-8" : "$options->{contenttype};";
  109. my %headers = (
  110. 'Content-Type' => $ct,
  111. 'Content-Length' => length($body),
  112. 'Cache-Control' => $query->{cachecontrol} // $Trog::Vars::cache_control{revalidate},
  113. 'X-Content-Type-Options' => 'nosniff',
  114. 'Vary' => 'Accept-Encoding',
  115. 'Server-Timing' => "render;dur=" . ( tv_interval( $query->{start} ) * 1000 ),
  116. %$uh,
  117. );
  118. #Disallow framing UNLESS we are in embed mode
  119. my $ancestor = $query->{domain} || 'none';
  120. $headers{"Content-Security-Policy"} = qq{frame-ancestors $ancestor} unless $query->{embed};
  121. $headers{'X-Frame-Options'} = 'DENY' unless $query->{embed};
  122. $headers{'Referrer-Policy'} = 'no-referrer-when-downgrade';
  123. #CSP. Yet another layer of 'no mixed content' plus whitelisted execution of remote resources.
  124. # Component renders (posts.tx, the bars) get a data hash built by the route
  125. # rather than the request, and it carries no scheme.
  126. my $scheme = ( $query->{scheme} // '' ) eq 'https' ? "$query->{scheme}:" : '';
  127. my $conf = Trog::Config::get();
  128. my $sites = $conf->param('security.allow_embeds_from') // '';
  129. $headers{'Content-Security-Policy'} .= ";default-src $scheme 'self' data: 'unsafe-eval' 'unsafe-inline' $sites";
  130. $headers{'Content-Security-Policy'} .= ";object-src 'none'";
  131. # Force https if we are https
  132. $headers{'Strict-Transport-Security'} = 'max-age=63072000' if ( $query->{scheme} // '' ) eq 'https';
  133. # We only set etags when users are logged in, cause we don't use statics
  134. $headers{'ETag'} = $query->{etag} if $query->{etag} && $query->{user};
  135. return %headers;
  136. }
  137. 1;