TCMS.pm 11 KB

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