TCMS.pm 15 KB

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