TCMS.pm 11 KB

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