blib/lib/App/Netdisco/Web.pm untested

filter: Statementstmt 0.0% 0 / 480 Branchbran 0.0% 0 / 132 Conditioncond 0.0% 0 / 117 MC/DCmcdc 0.0% 0 / 68 Subroutinesub 0.0% 0 / 50 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 850 CC 16 SCAR 38.5
CC
16
Cov
0%
BEGIN
210.0
_load_web_plugins
6.0
_tenant_is_configured
6.0
CRAP 47.0
1 package App::Netdisco::Web;
2  
3 use Dancer ':syntax';
4 use Dancer::Plugin::Ajax;
5  
6 use Dancer::Plugin::DBIC;
7 use Dancer::Plugin::Auth::Extensible;
8 use Dancer::Plugin::Swagger;
9  
10 use Dancer::Error;
11 use Dancer::Continuation::Route::ErrorSent;
12  
13 use URI ();
14 use HTTP::Status ();
15 use Socket6 (); # to ensure dependency is met
16 use HTML::Entities (); # to ensure dependency is met
17 use URI::QueryParam (); # part of URI, to add helper methods
18 use URI::Escape 'uri_escape_utf8';
19 use MIME::Base64 'encode_base64';
20 use Path::Class 'dir';
21 use Module::Load ();
22 use Data::Visitor::Tiny;
23 use Scalar::Util 'blessed';
24 use Storable 'dclone';
25 use URI::Based;
26  
27 use App::Netdisco::Util::Web qw/
28 escape_results_token
29 interval_to_daterange
30 page_title
31 pane_chrome
32 pane_history_header
33 request_is_api
34 request_is_api_report
35 request_is_api_search
36 tacacs_startup_warning
37 /;
38 use App::Netdisco::Util::Permission 'permitted_by_acl';
39 use App::Netdisco::Util::Port 'device_acl_by_role_check';
40 use App::Netdisco::Util::PostgresFloor 'warn_postgres_floor_all_tenants';
41 use App::Netdisco::Util::SiteLocal qw/scan_shadowed_files site_local_paths/;
42 use App::Netdisco::Util::SNMPText 'scan_config_encoding';
43  
44 BEGIN {
45 no warnings 'redefine';
46  
47 # https://github.com/PerlDancer/Dancer/issues/967
48 *Dancer::_redirect = sub {
49 my ($destination, $status) = @_;
50 my $response = Dancer::SharedData->response;
51 $response->status($status || 302);
52 $response->headers('Location' => $destination);
53 };
54  
55 # neater than using Dancer::Plugin::Res to handle JSON differently
56 *Dancer::send_error = sub {
57 my ($body, $status) = @_;
58 if (request_is_api) {
59 status $status || 400;
60 $body = '' unless defined $body;
61 Dancer::Continuation::Route::ErrorSent->new(
62 return_value => to_json { error => $body, return_url => param('return_url') }
63 )->throw;
64 }
65 Dancer::Continuation::Route::ErrorSent->new(
66 return_value => Dancer::Error->new(
67 message => $body,
68 code => $status || 500)->render()
69 )->throw;
70 };
71  
72 # behind_proxy is documented as a setting nobody needs, since
73 # Plack::Middleware::ReverseProxy is always in the stack, but a site that
74 # sets it makes Dancer answer with the X-Forwarded-For header verbatim, and
75 # more than one proxy makes that a chain rather than an address. Take the
76 # last element, as ReverseProxy does: anything left of it is client supplied.
77 *Dancer::Request::address = sub {
78 my $self = shift;
79 return $self->env->{REMOTE_ADDR} unless setting('behind_proxy');
80 my $forwarded = $self->forwarded_for_address;
81 my ($client) = (defined $forwarded ? ($forwarded =~ m/([^,\s]+)\s*$/) : ());
82 return ($client || $self->env->{REMOTE_ADDR});
83 };
84  
85 # to insert /t/$tenant if set
86 # which is fine for building links, but not fine for
87 # comparison to request->path, because when is_forward() the
88 # request->path is changed...
89 *Dancer::Request::uri_for = sub {
90 my ($self, $part, $params, $dont_escape) = @_;
91 my $uri = $self->base;
92  
93 if (vars->{'tenant'}) {
94 $part = '/t/'. vars->{'tenant'} . $part;
95 }
96  
97 # Make sure there's exactly one slash between the base and the new part
98 my $base = $uri->path;
99 $base =~ s|/$||;
100 $part =~ s|^/||;
101 $uri->path("$base/$part");
102  
103 $uri->query_form($params) if $params;
104  
105 return $dont_escape ? uri_unescape($uri->canonical) : $uri->canonical;
106 };
107  
108 # ...so here we are monkeypatching request->path as well
109 *Dancer::Request::path = sub {
110 die "path is accessor not mutator" if scalar @_ > 1;
111 my $self = shift;
112 $self->_build_path() unless $self->{path};
113  
114 if (vars->{'tenant'} and $self->{path} !~ m{/t/}) {
115 my $path = $self->{path};
116 my $base = setting('path');
117 my $tenant = '/t/' . vars->{'tenant'};
118  
119 $tenant = ($base . $tenant) if $base ne '/';
120 $tenant .= '/' if $base eq '/';
121 $path =~ s/^$base/$tenant/;
122  
123 return $path;
124 }
125 return $self->{path};
126 };
127  
128 # implement same_site
129 # from https://github.com/PerlDancer/Dancer-Session-Cookie/issues/20
130 *Dancer::Session::Cookie::_cookie_params = sub {
131 my $self = shift;
132 my $name = $self->session_name;
133 my $duration = $self->_session_expires_as_duration;
134 my %cookie = (
135 name => $name,
136 value => $self->_cookie_value,
137 path => setting('session_cookie_path') || '/',
138 domain => setting('session_domain'),
139 secure => setting('session_secure'),
140 http_only => setting("session_is_http_only") // 1,
141 same_site => setting("session_same_site"),
142 );
143 if ( defined $duration ) {
144 $cookie{expires} = time + $duration;
145 }
146 return %cookie;
147 };
148 }
149  
150 # before AuthN, because hooks run in the order their modules load and a token
151 # ACL's rules can contain group:<name>, which resolves through host_groups
152 use App::Netdisco::Web::ManagedConfig;
153 use App::Netdisco::Web::AuthN;
154 use App::Netdisco::Web::Static;
155 use App::Netdisco::Web::Theme;
156 use App::Netdisco::Web::Search;
157 use App::Netdisco::Web::Device;
158 use App::Netdisco::Web::Report;
159 use App::Netdisco::Web::API::Objects;
160 use App::Netdisco::Web::API::Queue;
161 use App::Netdisco::Web::API::Statistics;
162 use App::Netdisco::Web::API::User;
163 use App::Netdisco::Web::Health;
164 use App::Netdisco::Web::Metrics;
165 use App::Netdisco::Web::AdminTask;
166 use App::Netdisco::Web::TypeAhead;
167 use App::Netdisco::Web::PortControl;
168 use App::Netdisco::Web::Statistics;
169 use App::Netdisco::Web::Password;
170 use App::Netdisco::Web::CustomFields;
171 use App::Netdisco::Web::GenericReport;
172  
173 sub _load_web_plugins {
174 my $plugin_list = shift;
175  
176 foreach my $plugin (@$plugin_list) {
177 $plugin =~ s/^X::/+App::NetdiscoX::Web::Plugin::/;
178 $plugin = 'App::Netdisco::Web::Plugin::'. $plugin
179 if $plugin !~ m/^\+/;
180 $plugin =~ s/^\+//;
181  
182 $ENV{ND2_LOG_PLUGINS} && debug "loading web plugin $plugin";
183  
184 # support for loading a plugin twice
185 my $inc_file = join( '/', split /::/, $plugin ) . '.pm';
186 delete $INC{ $inc_file };
187  
188 Module::Load::load $plugin;
189 }
190 }
191  
192 if (setting('web_plugins') and ref [] eq ref setting('web_plugins')) {
193 _load_web_plugins( setting('web_plugins') );
194 }
195  
196 if (setting('extra_web_plugins') and ref [] eq ref setting('extra_web_plugins')) {
197 unshift @INC, dir(($ENV{NETDISCO_HOME} || $ENV{HOME}), 'site_plugins')->stringify;
198 _load_web_plugins( setting('extra_web_plugins') );
199 }
200  
201 foreach my $tag (keys %{ setting('_admin_tasks') }) {
202 my $code = sub {
203 # trick the ajax into working as if this were a tabbed page
204 params->{tab} = $tag;
205  
206 var(nav => 'admin');
207 template 'admintask', {
208 task => setting('_admin_tasks')->{ $tag },
209 }, { layout => 'main' };
210 };
211  
212 if (setting('_admin_tasks')->{ $tag }->{ 'roles' }) {
213 get "/admin/$tag" => require_any_role setting('_admin_tasks')->{ $tag }->{ 'roles' } => $code;
214 }
215 else {
216 get "/admin/$tag" => require_role admin => $code;
217 }
218 }
219  
220  
221 # after plugins are loaded, add our own template path
222 push @{ config->{engines}->{netdisco_template_toolkit}->{INCLUDE_PATH} },
223 setting('views');
224  
225 # Confirms the CSV plugin mapping in share/config.yml is still in force.
226 # Warns rather than dies: a misconfiguration should not become an outage.
227 warning 'the CSV template plugin is not App::Netdisco::Template::Plugin::CSV.'
228 . ' CSV downloads may no longer be neutralized against formula injection'
229 unless ((config->{engines}->{netdisco_template_toolkit}->{PLUGINS} || {})
230 ->{csv} || '') eq 'App::Netdisco::Template::Plugin::CSV';
231  
232 # sort the reports which have been loaded, by their label
233 foreach my $cat (@{ setting('_report_order') }) {
234 setting('_reports_menu')->{ $cat } ||= [];
235 setting('_reports_menu')->{ $cat }
236 = [ sort { setting('_reports')->{$a}->{'label'}
237 cmp
238 setting('_reports')->{$b}->{'label'} }
239 @{ setting('_reports_menu')->{ $cat } } ];
240 }
241  
242 # any template paths in deployment.yml (should override plugins)
243 if (setting('template_paths') and ref [] eq ref setting('template_paths')) {
244 if (setting('site_local_files')) {
245 push @{setting('template_paths')},
246 dir(($ENV{NETDISCO_HOME} || $ENV{HOME}), 'nd-site-local', 'share')->stringify,
247 dir(($ENV{NETDISCO_HOME} || $ENV{HOME}), 'nd-site-local', 'share', 'views')->stringify;
248 }
249 unshift @{ config->{engines}->{netdisco_template_toolkit}->{INCLUDE_PATH} },
250 @{setting('template_paths')};
251 }
252  
253 # here rather than earlier because template_paths is only resolved above
254 foreach my $finding (scan_shadowed_files(
255 { paths => [ site_local_paths() ], startup => 1 })) {
256 warning sprintf
257 '%s predates %s. Run "netdisco-do checksitelocal" for details.',
258 $finding->{path}, $finding->{release};
259 }
260  
261 warn_postgres_floor_all_tenants(sub { warning shift });
262  
263 warning 'Your configuration contains text that looks garbled. Run "netdisco-do checkencoding" for details.'
264 if scan_config_encoding(config());
265  
266 if (my $tacacs_warning = tacacs_startup_warning()) {
267 warning $tacacs_warning;
268 }
269  
270 # after template_paths, which decides where site-local themes can live
271 App::Netdisco::Web::Theme::resolve_configured_theme();
272  
273 # load cookie key from database
274 setting('session_cookie_key' => undef);
275 setting('session_cookie_key' => 'this_is_for_testing_only')
276 if $ENV{HARNESS_ACTIVE};
277 eval {
278 my $sessions = schema('netdisco')->resultset('Session');
279 my $skey = $sessions->find({id => 'dancer_session_cookie_key'});
280 setting('session_cookie_key' => $skey->get_column('a_session')) if $skey;
281 };
282 Dancer::Session::Cookie::init(session);
283  
284 # workaround for https://github.com/PerlDancer/Dancer/issues/935
285 hook after_error_render => sub { setting('layout' => 'main') };
286  
287 # A route that dies is rendered by Dancer::Error as an HTML page, whatever the
288 # client asked for, so an API client that sent Accept: application/json got
289 # markup to parse. send_error is already JSON for the API (see above); this is
290 # the path that does not go through it. The body names the status only: the
291 # exception text stays in the log, as show_errors keeps it out of the page.
292 hook after_error_render => sub {
293 my $response = shift;
294 return unless request_is_api;
295 $response->content_type('application/json');
296 $response->content(to_json {
297 error => lc HTTP::Status::status_message($response->status || 500),
298 return_url => param('return_url'),
299 });
300 };
301  
302 # build list of port detail columns
303 {
304 my @port_columns =
305 sort { $a->{idx} <=> $b->{idx} }
306 map {{ name => $_, %{ setting('sidebar_defaults')->{'device_ports'}->{$_} } }}
307 grep { $_ =~ m/^c_/ } keys %{ setting('sidebar_defaults')->{'device_ports'} };
308  
309 splice @port_columns, setting('device_port_col_idx_right') + 1, 0,
310 grep {$_->{position} eq 'right'} @{ setting('_extra_device_port_cols') };
311 splice @port_columns, setting('device_port_col_idx_mid') + 1, 0,
312 grep {$_->{position} eq 'mid'} @{ setting('_extra_device_port_cols') };
313 splice @port_columns, setting('device_port_col_idx_left') + 1, 0,
314 grep {$_->{position} eq 'left'} @{ setting('_extra_device_port_cols') };
315  
316 set('port_columns' => \@port_columns);
317  
318 # update sidebar_defaults so hooks scanning params see new plugin cols
319 setting('sidebar_defaults')->{'device_ports'}->{ $_->{name} } = $_
320 for @port_columns;
321 }
322  
323 # build lookup for tenancies
324 {
325 set('tenant_data' => {
326 map { ( $_->{tag} => { displayname => $_->{'displayname'},
327 tag => $_->{'tag'},
328 path => config->{'url_base'}->with("/t/$_->{tag}")->path } ) }
329 @{ setting('tenant_databases') },
330 { tag => 'netdisco', displayname => (setting('database')->{displayname} || 'Default') }
331 });
332 config->{'tenant_data'}->{'netdisco'}->{'path'}
333 = URI::Based->new((config->{path} eq '/') ? '' : config->{path})->path;
334 set('tenant_tags' => [ map { $_->{'tag'} }
335 sort { $a->{'displayname'} cmp $b->{'displayname'} }
336 values %{ config->{'tenant_data'} } ]);
337 }
338  
339 hook 'before' => sub {
340 my $key = request->path;
341 if (param('tab') and ($key !~ m/ajax/)) {
342 $key .= ('/' . param('tab'));
343 }
344 $key =~ s|.*/(\w+)/(\w+)$|${1}_${2}|;
345  
346 # the admin pages are served from /admin/<task> but their sidebar options
347 # are configured, and read by the sidebar templates, under admintask_<task>
348 $key =~ s/^admin_/admintask_/;
349  
350 var(sidebar_key => $key);
351  
352 # trim whitespace
353 params->{'q'} =~ s/^\s+|\s+$//g if param('q');
354  
355 # copy sidebar defaults into vars so we can mess about with it
356 foreach my $sidebar (keys %{setting('sidebar_defaults')}) {
357 vars->{'sidebar_defaults'}->{$sidebar} = { map {
358 ($_ => setting('sidebar_defaults')->{$sidebar}->{$_}->{'default'})
359 } keys %{setting('sidebar_defaults')->{$sidebar}} };
360 }
361 };
362  
363 # swagger submits "false" params whereas web UI does not - remove them
364 # so that code testing for param existence as truth still works.
365 hook 'before' => sub {
366 return unless request_is_api_report or request_is_api_search;
367 map {delete params->{$_} if params->{$_} eq 'false'} keys %{params()};
368 };
369  
370 hook 'before_template' => sub {
371 # search or report from navbar, or reset of sidebar, can ignore params
372 return if param('firstsearch')
373 or var('sidebar_key') !~ m/^\w+_\w+$/;
374  
375 # update defaults to contain the passed url params
376 # (this follows initial copy from config.yml, then cookie restore)
377 var('sidebar_defaults')->{var('sidebar_key')}->{$_} = param($_)
378 for keys %{ var('sidebar_defaults')->{var('sidebar_key')} || {} };
379 };
380  
381 hook 'before_template' => sub {
382 my $tokens = shift;
383  
384 # quick b64 encode
385 $tokens->{atob} = sub { encode_base64(shift, '') };
386  
387 # allow portable static content
388 $tokens->{uri_base} = request->base->path
389 if request->base->path ne '/';
390 $tokens->{uri_base} .= ('/t/'. uri_escape_utf8(vars->{'tenant'}))
391 if vars->{'tenant'};
392  
393 # cache-busting suffix for the stylesheets and scripts in the layout.
394 # bin/netdisco-web-fg asks browsers to hold css, javascript, images and
395 # fonts for a day without revalidating, and the filenames never carry a
396 # version, so after an upgrade a returning visitor renders the new markup
397 # with the previous release's stylesheet until that day is up.
398 $tokens->{asset_version} = ($App::Netdisco::VERSION || 'HEAD');
399  
400 # allow portable dynamic content
401 $tokens->{uri_for} = sub { uri_for(@_)->path_query };
402  
403 # current query string to all resubmit from within ajax template
404 my $queryuri = URI->new();
405 $queryuri->query_param($_ => param($_))
406 for grep {$_ ne 'return_url'} keys %{params()};
407 $tokens->{my_query} = $queryuri->query();
408  
409 # hide custom fields according to only/no settings
410 $tokens->{permitted_by_acl} = sub { permitted_by_acl(@_) };
411  
412 # access to logged in user's roles (modulo RBAC)
413 # role will be "admin" "port_control" "radius" or "ldap"
414 $tokens->{user_has_role} = sub {
415 my ($role, $device) = @_;
416 return false unless $role;
417  
418 return user_has_role($role) if $role ne 'port_control';
419 return false unless user_has_role('port_control');
420 return true if not $device;
421  
422 my $user = logged_in_user or return false;
423 return device_acl_by_role_check($device, $user);
424 };
425  
426 # create date ranges from within templates
427 $tokens->{to_daterange} = sub { interval_to_daterange(@_) };
428  
429 # data structure for DataTables records per page menu
430 $tokens->{table_showrecordsmenu} =
431 to_json( setting('table_showrecordsmenu') );
432  
433 # linked searches will use these default url path params
434 foreach my $sidebar_key (keys %{ var('sidebar_defaults') }) {
435 my ($mode, $report) = ($sidebar_key =~ m/(\w+)_(\w+)/);
436 if ($mode =~ m/^(?:search|device)$/) {
437 $tokens->{$sidebar_key} = uri_for("/$mode", {tab => $report});
438 }
439 elsif ($mode =~ m/^report$/) {
440 $tokens->{$sidebar_key} = uri_for("/$mode/$report");
441 }
442 elsif ($mode =~ m/^admintask$/) {
443 $tokens->{$sidebar_key} = uri_for("/$mode/$report");
444 }
445  
446 foreach my $col (keys %{ var('sidebar_defaults')->{$sidebar_key} }) {
447 $tokens->{$sidebar_key}->query_param($col,
448 var('sidebar_defaults')->{$sidebar_key}->{$col});
449 }
450  
451 # fix Plugin Template Variables to be only path+query
452 $tokens->{$sidebar_key} = $tokens->{$sidebar_key}->path_query;
453 }
454  
455 # helper from NetAddr::MAC for the MAC formatting
456 $tokens->{mac_format_call} = 'as_'. lc(param('mac_format'))
457 if param('mac_format');
458  
459 # allow very long lists of ports
460 $Template::Directive::WHILE_MAX = 10_000;
461  
462 # allow hash keys with leading underscores
463 $Template::Stash::PRIVATE = undef;
464 };
465  
466 # The report and search templates embed their result set as a JavaScript
467 # literal inside a <script> element, which they must opt out of AutoFilter to
468 # do. Escaping happens here rather than in each of the templates so that a
469 # site-local template or a third-party report plugin gets it too, without its
470 # author having to know.
471 hook 'before_template' => sub {
472 escape_results_token( shift );
473 };
474  
475 # prevent Template::AutoFilter taking action on CSV output
476 hook 'before_template' => sub {
477 my $template_engine = engine 'template';
478 if (not request->is_ajax
479 and header('Content-Type')
480 and header('Content-Type') eq 'text/comma-separated-values' ) {
481  
482 $template_engine->{config}->{AUTO_FILTER} = 'none';
483 $template_engine->init();
484 }
485 # debug $template_engine->{config}->{AUTO_FILTER};
486 };
487 hook 'after_template_render' => sub {
488 my $template_engine = engine 'template';
489 if (not request->is_ajax
490 and header('Content-Type')
491 and header('Content-Type') eq 'text/comma-separated-values' ) {
492  
493 $template_engine->{config}->{AUTO_FILTER} = 'html_entity';
494 $template_engine->init();
495 }
496 # debug $template_engine->{config}->{AUTO_FILTER};
497 };
498  
499 # support for report api which is basic table result in json
500 #
501 # The branch is chosen on the presence of the token, not its value. Node search
502 # is the only handler that renders without a `results` token, and the second
503 # branch exists for it. Creating the key here or in any earlier hook silently
504 # moves it onto the first branch and empties the response: #732 in 2020, #1649
505 # in 2026.
506 hook before_layout_render => sub {
507 my ($tokens, $html_ref) = @_;
508 return unless request_is_api_report or request_is_api_search;
509  
510 if (ref {} eq ref $tokens and exists $tokens->{results}) {
511 ${ $html_ref } = to_json $tokens->{results};
512 }
513 elsif (ref {} eq ref $tokens) {
514 map {delete $tokens->{$_}}
515 grep {not blessed $tokens->{$_} or not $tokens->{$_}->isa('App::Netdisco::DB::ResultSet')}
516 keys %$tokens;
517  
518 visit( $tokens, sub {
519 my ( $key, $valueref ) = @_;
520 $$valueref = [$$valueref->hri->all]
521 if blessed $$valueref and $$valueref->isa('App::Netdisco::DB::ResultSet');
522 });
523  
524 ${ $html_ref } = to_json $tokens;
525 }
526 else {
527 ${ $html_ref } = '[]';
528 }
529 };
530  
531 # workaround for Swagger plugin weird response body
532 hook 'after' => sub {
533 my $r = shift; # a Dancer::Response
534  
535 if (request->path =~ m{/swagger\.json} and
536 request->path eq uri_for('/swagger.json')->path
537 and ref {} eq ref $r->content) {
538 my $spec = dclone $r->content;
539  
540 if (vars->{'tenant'}) {
541 my $base = setting('path');
542 my $tenant = '/t/' . vars->{'tenant'};
543 $tenant = ($base . $tenant) if $base ne '/';
544 $tenant .= '/' if $base eq '/';
545  
546 foreach my $path (sort keys %{ $spec->{paths} }) {
547 (my $newpath = $path) =~ s/^$base/$tenant/;
548 $spec->{paths}->{$newpath} = delete $spec->{paths}->{$path};
549 }
550 }
551  
552 $r->content( to_json( $spec ) );
553 header('Content-Type' => 'application/json');
554 }
555  
556 # instead of setting serialiser
557 # and also to handle some plugins just returning undef if search fails
558 if (request_is_api) {
559 header('Content-Type' => 'application/json');
560 $r->content( $r->content || '[]' );
561 }
562 };
563  
564 # setup for swagger API
565 my $swagger = Dancer::Plugin::Swagger->instance;
566 my $swagger_doc = $swagger->doc;
567  
568 $swagger_doc->{consumes} = 'application/json';
569 $swagger_doc->{produces} = 'application/json';
570 $swagger_doc->{tags} = [
571 {name => 'General',
572 description => 'Log in/out and health checks'},
573 {name => 'Search',
574 description => 'Search Operations'},
575 {name => 'Objects',
576 description => 'Device, Port, and associated Node Data'},
577 {name => 'Reports',
578 description => 'Canned and Custom Reports'},
579 {name => 'Queue',
580 description => 'Operations on the Job Queue'},
581 ];
582  
583 $swagger_doc->{securityDefinitions} = {
584 APIKeyHeader =>
585 { type => 'apiKey', name => 'Authorization', in => 'header' },
586 BasicAuth =>
587 { type => 'basic' },
588 };
589 $swagger_doc->{security} = [ { APIKeyHeader => [] } ];
590  
591 if (setting('trust_x_remote_user')) {
592 foreach my $path (keys %{ $swagger_doc->{paths} }) {
593 foreach my $method (keys %{ $swagger_doc->{paths}->{$path} }) {
594 unshift @{ $swagger_doc->{paths}->{$path}->{$method}->{parameters} }, {
595 name => 'X-REMOTE_USER',
596 description => 'API client user name',
597 in => 'header',
598 required => false,
599 type => 'string',
600 };
601 }
602 }
603 }
604  
605 # manually install Swagger UI routes because plugin doesn't handle non-root
606 # hosting, so we cannot use show_ui(1)
607 my $swagger_base = config->{plugins}->{Swagger}->{ui_url};
608  
609 get $swagger_base => sub {
610 Dancer::Plugin::Swagger->instance->doc->{schemes} = [ request->scheme ];
611 redirect uri_for($swagger_base)->path . '/';
612 };
613  
614 get $swagger_base.'/' => sub {
615 Dancer::Plugin::Swagger->instance->doc->{schemes} = [ request->scheme ];
616 # The ?url= this used to require was dropped with the guard that enforced
617 # it: the 5.x page resolves its own definition. Reinstating either alone
618 # makes the two routes redirect to each other, so they move together.
619 template 'swagger-ui', {}, { layout => undef };
620 };
621  
622 # omg the plugin uses system_path and we don't want to go there
623 get $swagger_base.'/**' => sub {
624 Dancer::Plugin::Swagger->instance->doc->{schemes} = [ request->scheme ];
625 my @path = @{ (splat())[0] };
626  
627 # Netdisco serves its own entry point, so nothing under swagger-ui/ answers
628 # for index.html. Answered rather than left to 404 because deployments and
629 # bookmarks link to it.
630 return redirect uri_for($swagger_base)->path . '/'
631 if @path == 1 and $path[0] eq 'index.html';
632  
633 send_file( join '/', 'swagger-ui', @path );
634 };
635  
636 # htmx applies a <title> found at the top level of a swapped response, the
637 # HX-Push-Url and HX-Replace-Url headers to the address bar, and an element
638 # carrying hx-swap-oob to whatever in the page has that id, so the chrome
639 # around a pane comes from the response rather than from the browser reading
640 # the page the fragment replaces.
641 hook 'after' => sub {
642 my $r = shift; # a Dancer::Response
643  
644 # htmx sends this on every request it makes, and htmx is the only thing
645 # that acts on the title, so it is a closer guard than X-Requested-With.
646 # It also keeps the title away from the CSV download of a report and from
647 # the API endpoints, which forward to these same paths.
648 #
649 # Read from the PSGI environment because request->header cannot be relied
650 # on: Dancer::Request::is_ajax carries the same workaround, for headers
651 # that Plack::Builder leaves unset, and netdisco-web-fg builds its app
652 # that way.
653 return unless request->env->{'HTTP_HX_REQUEST'};
654 return unless $r->status and $r->status =~ m/^2\d\d$/;
655  
656 # the pane routes alone. Their two-segment shape is what excludes the
657 # report data and connected-node endpoints, neither of which replaces a
658 # pane and both of which would set the title wrongly.
659 my ($page, $tab) =
660 (request->path =~ m{/ajax/content/(device|search|report|admin)/(\w+)$})
661 or return;
662  
663 $r->header( pane_history_header($page, $tab) );
664  
665 # A tenant URL reaches its pane by forward, and Dancer runs this hook once
666 # for the inner request and again for the response it rebuilds from it.
667 # Without this the pane carries two titles, htmx lifts only the first, and
668 # the second is swapped into the pane as an element, which also makes an
669 # empty result set stop looking empty; the chrome would swap twice over
670 # itself. The header above needs no guard: setting it twice leaves one
671 # header, where prepending twice leaves two of everything.
672 return if var('nd_fragment_chrome');
673 var('nd_fragment_chrome' => 1);
674  
675 my $title = page_title($page, $tab) || '';
676 my $chrome = pane_chrome($page, $tab);
677 return unless length $title or length $chrome;
678  
679 # htmx only lifts a title that is a direct child of the fragment, so this
680 # goes first and nothing may wrap it. The chrome follows for the same
681 # reason: an out-of-band element is swapped from the top level of the
682 # fragment, which is also where htmx 4 will want its <hx-partial>.
683 $r->content(
684 (length $title
685 ? ('<title>'. HTML::Entities::encode_entities($title) .'</title>') : '')
686 . $chrome . ($r->content || ''));
687 };
688  
689 # remove empty lines from CSV response
690 # this makes writing templates much more straightforward!
691 hook 'after' => sub {
692 my $r = shift; # a Dancer::Response
693  
694 if ($r->content_type and $r->content_type eq 'text/comma-separated-values') {
695 my @newlines = ();
696 my @lines = split m/\n/, $r->content;
697  
698 foreach my $line (@lines) {
699 push @newlines, $line if $line !~ m/^\s*$/;
700 }
701  
702 $r->content(join "\n", @newlines);
703 }
704 };
705  
706 # support for tenancies
707  
708 # the segment is echoed back into the page as uri_base, which the layout and
709 # the SNMP panes emit unfiltered, so only a configured tag may set it.
710 sub _tenant_is_configured {
711 my $tenant = shift;
712 return 0 unless defined $tenant;
713 return scalar grep { defined $_ and $_ eq $tenant }
714 @{ setting('tenant_tags') || [] };
715 }
716  
717 any qr{^/t/(?<tenant>[^/]+)/?$} => sub {
718 my $capture = captures;
719 pass unless _tenant_is_configured($capture->{'tenant'});
720 var tenant => $capture->{'tenant'};
721 forward '/';
722 };
723 any '/t/*/**' => sub {
724 my ($tenant, $path) = splat;
725 pass unless _tenant_is_configured($tenant);
726 var tenant => $tenant;
727 forward (join '/', '', @$path, (request->path =~ m{/$} ? '' : ()));
728 };
729  
730 # /ajax/ is excluded so a non-XHR request to one falls through to no route at
731 # all. Dancer caches the route it matched, keyed on the path alone, so letting
732 # this one answer would make that path 404 for every later XHR.
733 any qr{^(?!/ajax/).*} => sub {
734 # an unknown /api path, or a known one with the wrong method, would get
735 # the HTML not-found page, even with Accept: application/json
736 send_error('not found', 404) if request_is_api;
737  
738 var('notfound' => true);
739 status 'not_found';
740 template 'index', {}, { layout => 'main' };
741 };
742  
743 true;