TCMS.pm 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. package TCMS;
  2. use 5.040;
  3. use re '/aa';
  4. use Carp qw{confess};
  5. use Clone qw{clone};
  6. use Date::Format qw{strftime};
  7. use Sys::Hostname();
  8. use HTTP::Body ();
  9. use URL::Encode ();
  10. use Text::Xslate ();
  11. use DateTime::Format::HTTP();
  12. use CGI::Cookie ();
  13. use File::Basename();
  14. use Time::HiRes qw{gettimeofday tv_interval};
  15. use List::Util;
  16. use URI();
  17. use Ref::Util qw{is_coderef is_hashref is_arrayref};
  18. #Grab our custom routes
  19. use FindBin;
  20. use lib "$FindBin::Bin/../lib";
  21. use FindBin::libs;
  22. use Trog::Routes::HTML;
  23. use Trog::Routes::JSON;
  24. use Trog::Log qw{:all};
  25. use Trog::Log::DBI;
  26. use Trog::Auth;
  27. use Trog::Config;
  28. # Loaded here rather than where it is used, so that the vault key comes out of
  29. # the environment once, in the parent, before there is a worker to fork -- see
  30. # Trog::Vault.
  31. use Trog::Vault;
  32. use Trog::Data;
  33. use Trog::Themes;
  34. # Troglodyne philosophy - simple as possible
  35. my $cur_query = {};
  36. # Build routes
  37. sub build_routes {
  38. my $conf = Trog::Config::get();
  39. my $data = Trog::Data->new($conf);
  40. my %routes = %{ _routes($data) };
  41. my $default_route = $routes{default}{callback};
  42. # Transform 'method' / 'callback' to new scheme
  43. my %routes_adj;
  44. foreach my $k ( keys(%routes) ) {
  45. my $v = $routes{$k};
  46. # Some routes are just pointers to other routes.
  47. # In this case they might have already been transformed and need to be skipped.
  48. if ( exists $v->{callbacks} ) {
  49. $routes_adj{$k} = $v;
  50. next;
  51. }
  52. my %cb;
  53. my $method = $v->{method};
  54. my $callback = delete $v->{callback};
  55. #XXX For now we will discard the tPSGI object. We might want it later.
  56. my $cb_wrap = sub {
  57. my ( $tpsgi, $query ) = @_;
  58. confess "Cannot determine directory for logs!" unless $tpsgi->{log_dir};
  59. # Make sure the tCMS logs live in the same dir as the tpsgi logs.
  60. log_init( "$tpsgi->{log_dir}/tpsgi.log", $tpsgi->{verbose} ? 'debug' : 'info', $tpsgi->{loggers} );
  61. # Let's open up our default route if needed before we bother thinking any harder
  62. return $default_route->($query) unless -f "config/setup"; ## no critic (ProhibitFiletest_f) -- a flag file, only ever touched
  63. # Set the urchin parameters if necessary.
  64. %$Trog::Log::DBI::urchin = map { $_ => delete $query->{$_} } qw{utm_source utm_medium utm_campaign utm_term utm_content};
  65. # Set the IP of the request so we can fail2ban
  66. $Trog::Log::ip = $query->{ip};
  67. # Set the referer & ua to go into DB logs, but not logs in general.
  68. # The referer/ua largely has no importance beyond being a proto bug report for log messages.
  69. $Trog::Log::DBI::referer = $query->{referer};
  70. $Trog::Log::DBI::ua = $query->{ua};
  71. # Figure out if we have a logged in user, so we can serve them user-specific files
  72. my $cookies = {};
  73. $cookies = CGI::Cookie->parse( $query->{cookies} ) if $query->{cookies};
  74. my $active_user = '';
  75. $Trog::Log::user = 'nobody';
  76. if ( exists $cookies->{tcmslogin} ) {
  77. $active_user = Trog::Auth::session2user( $cookies->{tcmslogin}->value );
  78. $Trog::Log::user = $active_user if $active_user;
  79. }
  80. # Make sure TPSGI can log the user
  81. $tpsgi->{user} = $active_user;
  82. # Enrich the query with tcms specific foo
  83. $query->{user_acls} = [];
  84. $query->{user_acls} = Trog::Auth::acls4user($active_user) // [] if $active_user;
  85. # Grab the list of ACLs we want to add to a post, if any.
  86. $query->{acls} = [ $query->{acls} ] if ( $query->{acls} && ref $query->{acls} ne 'ARRAY' );
  87. # Filter out passed ACLs which are naughty
  88. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  89. @{ $query->{acls} } = grep { $_ ne 'admin' } @{ $query->{acls} } unless $is_admin;
  90. $query->{user} = $active_user;
  91. $query->{body} = '';
  92. $query->{social_meta} = 1;
  93. $query->{primary_post} = {};
  94. $query->{nocache} = $v->{nocache};
  95. # Some routes may just need to do serve()
  96. $query->{tpsgi} = $tpsgi;
  97. # Redirecting somewhere naughty not allow
  98. $query->{to} = URI->new( $query->{to} // '' )->path() || $query->{to} if $query->{to};
  99. # Now that we have firmed up the actual routing, let's validate.
  100. return $tpsgi->forbidden($query) if exists $query->{dispatcher}{auth} && !$active_user;
  101. if ( needs_enrolment( $active_user, $query->{dispatcher} ) ) {
  102. INFO("$active_user has no TOTP enrolment; sending them to /totp");
  103. return $tpsgi->see_also('/totp');
  104. }
  105. no strict 'refs';
  106. $callback->($query);
  107. use strict;
  108. };
  109. #XXX todo support different callbacks per requested content-type
  110. $cb{'*'} = $cb_wrap if $callback;
  111. $v->{callbacks} = \%cb;
  112. $routes_adj{$k} = $v;
  113. }
  114. return [%routes_adj];
  115. }
  116. =head2 needs_enrolment($user, $dispatcher) = BOOL
  117. Whether this request should be turned around and sent to /totp.
  118. Two factors or nothing. A login is what gets you to the enrolment page -- the QR
  119. is the shared secret, so it cannot be handed to whoever asks for it -- which
  120. leaves a window where somebody is logged in and has no second factor yet. This
  121. is what makes that window one page wide: every route a login can reach, and no
  122. route a logged out visitor can, is refused until they have enrolled.
  123. The enrolment page and the QR on it say so themselves, with totp_exempt, because
  124. the exemption belongs next to the route rather than in a list over here that the
  125. routing table knows nothing about.
  126. =cut
  127. sub needs_enrolment ( $user, $dispatcher ) {
  128. return 0 unless $user;
  129. return 0 unless $dispatcher && $dispatcher->{auth} && !$dispatcher->{totp_exempt};
  130. return Trog::Auth::has_totp($user) ? 0 : 1;
  131. }
  132. # Override the generic error handler to look spiffy
  133. sub generic_route ( $rname, $code, $title, $query ) {
  134. $query->{code} = $code;
  135. $query->{route} //= $rname;
  136. $query->{title} = $title;
  137. $query->{template} = "$rname.tx";
  138. return Trog::Routes::HTML::index($query);
  139. }
  140. our @routes = @{ build_routes() };
  141. our %aliases = aliases();
  142. #XXX Return a clone of the routing table ref, because code modifies it later
  143. sub _routes ( $data = {} ) {
  144. state %routes;
  145. return clone( \%routes ) if %routes;
  146. my $conf = Trog::Config::get();
  147. $data = Trog::Data->new($conf) unless $data;
  148. # Routes in general are going to override earlier, more default ones.
  149. # XXX this is probably bad in the case of the specific content-typed routes, they should be mutex
  150. my %roots = $data->routes();
  151. # Setup the /secure/... versions for logged in users, except for already secured routes.
  152. foreach my $route ( keys(%roots) ) {
  153. next if index( $route, '/secure/' ) == 0;
  154. $roots{"/secure$route"} = $roots{$route};
  155. }
  156. # It is the responsibility of theme authors to setup /secure routes (other than index)
  157. my %themed = Trog::Themes::routes();
  158. %routes = %Trog::Routes::HTML::routes;
  159. @routes{ keys(%Trog::Routes::JSON::routes) } = values(%Trog::Routes::JSON::routes);
  160. @routes{ keys(%roots) } = values(%roots);
  161. @routes{ keys(%themed) } = values(%themed) if %themed;
  162. # Add in global routes, here because they *must* know about all other routes
  163. # Also, nobody should ever override these.
  164. $routes{'/robots.txt'} = {
  165. method => 'GET',
  166. callback => \&robots,
  167. };
  168. # Special 'am I authenticated' route for nginx
  169. $routes{'/authenticated'} = {
  170. method => 'GET',
  171. nocache => 1,
  172. noindex => 1,
  173. callback => sub {
  174. my ($query) = @_;
  175. return $query->{tpsgi}->ok($query) if $query->{user};
  176. return $query->{tpsgi}->forbidden($query);
  177. },
  178. };
  179. # Heartbeat route
  180. $routes{'/status'} = {
  181. method => 'GET',
  182. nocache => 1,
  183. noindex => 1,
  184. callback => sub {
  185. my ($query) = @_;
  186. return $query->{tpsgi}->ok($query);
  187. },
  188. };
  189. # The Various aliases for directory indices
  190. foreach my $index (qw{ / /index.html /index.htm}) {
  191. $routes{$index} = $routes{'/index'} unless exists $routes{$index};
  192. $routes{"/secure$index"} = $routes{'/index'} unless exists $routes{"/secure$index"};
  193. }
  194. return clone( \%routes );
  195. }
  196. sub aliases {
  197. my $conf = Trog::Config::get();
  198. my $data = Trog::Data->new($conf);
  199. return $data->aliases();
  200. }
  201. =head2 robots
  202. Return an appropriate robots.txt
  203. This is a "special" route as it needs to know about all the routes in order to disallow noindex=1 routes.
  204. =cut
  205. # TODO anytime that the routing table changes, we need to invalidate the cache.
  206. sub robots ($query) {
  207. state $etag = "robots-" . time();
  208. my $routes = _routes();
  209. # If there's a 'capture' route, we need to format it correctly.
  210. state @banned = map { exists $routes->{$_}{robot_name} ? $routes->{$_}{robot_name} : $_ } grep { $routes->{$_}{noindex} } sort keys(%$routes);
  211. return Trog::Renderer->render(
  212. contenttype => 'text/plain',
  213. template => 'robots.tx',
  214. data => {
  215. etag => $etag,
  216. banned => \@banned,
  217. %$query,
  218. },
  219. code => 200,
  220. );
  221. }
  222. 1;