TCMS.pm 9.5 KB

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