TCMS.pm 14 KB

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