TCMS.pm 9.3 KB

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