TCMS.pm 9.2 KB

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