Trog-DataSource-Virt.t 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. use strict;
  2. use warnings;
  3. use Test::More;
  4. use Test::MockModule qw{strict};
  5. use Test::Fatal qw{exception};
  6. use Path::Tiny();
  7. use JSON::MaybeXS();
  8. use FindBin;
  9. use lib "$FindBin::Bin/../lib";
  10. # Nothing in this file may ever reach a real hypervisor. Every libvirt object
  11. # here is a fake that records what was asked of it, which is the only safe way
  12. # to test the destructive half: the machine this suite runs on is itself a
  13. # guest of the hypervisor the feature talks to.
  14. require_ok('Trog::DataSource::Virt') or BAIL_OUT("Can't find SUT");
  15. my $logmock = Test::MockModule->new('Trog::DataSource::Virt');
  16. $logmock->redefine( WARN => sub { note(shift) } );
  17. $logmock->redefine( INFO => sub { note(shift) } );
  18. our @CALLS;
  19. {
  20. package FakeDomain;
  21. sub new { my ( $c, %a ) = @_; return bless {%a}, $c }
  22. sub get_name { $_[0]{name} }
  23. sub get_uuid_string { $_[0]{uuid} }
  24. sub is_active { $_[0]{active} }
  25. sub get_info { { state => $_[0]{state}, memory => 1024, nrVirtCpu => 2 } }
  26. # The operations we must never actually perform: record and return.
  27. sub create { push @main::CALLS, [ 'create', $_[0]{name} ]; 1 }
  28. sub shutdown { push @main::CALLS, [ 'shutdown', $_[0]{name} ]; 1 }
  29. sub destroy { push @main::CALLS, [ 'destroy', $_[0]{name} ]; 1 }
  30. sub create_snapshot { push @main::CALLS, [ 'create_snapshot', $_[0]{name} ]; 1 }
  31. # Reading a console is not a mutation, so this one really runs.
  32. sub screenshot { return 'image/png' }
  33. }
  34. {
  35. package FakeStream;
  36. sub new { bless {}, shift }
  37. sub recv_all { my ( $self, $cb ) = @_; $cb->( $self, 'fake-png-bytes' ); return 1 }
  38. sub finish { 1 }
  39. }
  40. {
  41. package FakeConn;
  42. sub new { bless {}, shift }
  43. sub new_stream { FakeStream->new() }
  44. sub list_all_domains {
  45. return (
  46. FakeDomain->new( name => 'alpha', uuid => 'uuid-alpha', active => 1, state => 1 ),
  47. FakeDomain->new( name => 'beta', uuid => 'uuid-beta', active => 0, state => 5 ),
  48. );
  49. }
  50. }
  51. my $connect_fails = 0;
  52. my $virtmock = Test::MockModule->new('Sys::Virt');
  53. $virtmock->redefine(
  54. new => sub {
  55. die "libvirt error: nope\n" if $connect_fails;
  56. return FakeConn->new();
  57. }
  58. );
  59. my $series = {
  60. child_form => 'guests.tx',
  61. tags => ['guests'],
  62. visibility => 'private',
  63. user => 'specadmin',
  64. hypervisors => [ { id => 'hv-1', title => 'spec-hv', conn_uri => 'test:///default' } ],
  65. };
  66. subtest 'guests become posts' => sub {
  67. @CALLS = ();
  68. my @posts = Trog::DataSource::Virt::posts( $series, { user_acls => ['admin'] } );
  69. is( scalar @posts, 2, 'one post per guest' );
  70. is( $posts[0]{title}, 'alpha', 'named after the guest' );
  71. is( $posts[0]{id}, 'uuid-alpha', "and identified by the guest's uuid, not ours" );
  72. is( $posts[0]{form}, 'guests.tx', "wearing the series' child type" );
  73. is( $posts[0]{state}, 'running', 'with a legible state' );
  74. is( $posts[1]{state}, 'shut off', '...for each of libvirt\'s numeric ones' );
  75. is( $posts[0]{is_active}, 1, 'active guests are marked so' );
  76. is( $posts[1]{is_active}, 0, 'and inactive ones are not' );
  77. # The listing must not take screenshots: that is a per-guest round trip,
  78. # and it is the browser's job via the preview route.
  79. is( $posts[0]{preview}, '/guest/screenshot/hv-1/alpha', 'the preview is a route, not an inline capture' );
  80. is_deeply( \@CALLS, [], 'and nothing was done to any guest merely by listing' );
  81. is_deeply( $posts[0]{tags}, ['guests'], "children inherit the series' tags" );
  82. is( $posts[0]{visibility}, 'private', 'and its visibility' );
  83. };
  84. subtest 'an unreachable hypervisor says so rather than vanishing' => sub {
  85. $connect_fails = 1;
  86. my @posts = Trog::DataSource::Virt::posts( $series, { user_acls => ['admin'] } );
  87. $connect_fails = 0;
  88. is( scalar @posts, 1, 'we get a post back' );
  89. ok( $posts[0]{unreachable}, 'flagged as unreachable' );
  90. like( $posts[0]{state}, qr/unreachable/, 'saying as much' );
  91. is( $posts[0]{title}, 'spec-hv', 'named for the hypervisor we could not reach' );
  92. };
  93. subtest 'act() drives the right libvirt call, and only on request' => sub {
  94. my %expected = (
  95. poweron => 'create',
  96. poweroff => 'shutdown',
  97. snapshot => 'create_snapshot',
  98. destroy => 'destroy',
  99. );
  100. foreach my $action ( sort keys %expected ) {
  101. @CALLS = ();
  102. my ( $ok, $message ) = Trog::DataSource::Virt::act( $action, 'test:///default', 'alpha', 'specadmin' );
  103. ok( $ok, "$action succeeded" ) or diag($message);
  104. is_deeply( \@CALLS, [ [ $expected{$action}, 'alpha' ] ], "$action called $expected{$action} on the named guest, once" );
  105. }
  106. };
  107. subtest 'act() refuses what it should' => sub {
  108. @CALLS = ();
  109. my ( $ok, $message ) = Trog::DataSource::Virt::act( 'rm-rf', 'test:///default', 'alpha', 'specadmin' );
  110. ok( !$ok, 'an action we do not define is refused' );
  111. like( $message, qr/not something we do/, 'and says so' );
  112. ( $ok, $message ) = Trog::DataSource::Virt::act( 'destroy', 'test:///default', '../../etc/passwd', 'specadmin' );
  113. ok( !$ok, 'a guest name that is a path is refused' );
  114. like( $message, qr/bad guest name/, 'before any connection is made' );
  115. ( $ok, $message ) = Trog::DataSource::Virt::act( 'destroy', 'test:///default', 'nosuchguest', 'specadmin' );
  116. ok( !$ok, 'a guest that is not there is refused' );
  117. like( $message, qr/no guest called/, 'rather than acting on some other one' );
  118. is_deeply( \@CALLS, [], 'and none of those touched a guest' );
  119. $connect_fails = 1;
  120. ( $ok, $message ) = Trog::DataSource::Virt::act( 'poweroff', 'test:///default', 'alpha', 'specadmin' );
  121. $connect_fails = 0;
  122. ok( !$ok, 'an unreachable hypervisor is refused' );
  123. like( $message, qr/could not reach/, 'and reported' );
  124. is_deeply( \@CALLS, [], 'having done nothing' );
  125. };
  126. subtest 'screenshot() validates its inputs before anything else' => sub {
  127. my $hv = { id => 'hv-1', conn_uri => 'test:///default' };
  128. my ( $path, $why ) = Trog::DataSource::Virt::screenshot( $hv, '../../../etc/passwd' );
  129. is( $path, undef, 'a path-shaped guest name gets no screenshot' );
  130. like( $why, qr/bad guest name/, 'and is named as the reason' );
  131. ( $path, $why ) = Trog::DataSource::Virt::screenshot( $hv, 'alpha/../../beta' );
  132. is( $path, undef, 'nor does one with traversal in the middle' );
  133. # The cache path is built from the hypervisor id too, so it has to be
  134. # checked as well -- otherwise it is a directory traversal of its own.
  135. ( $path, $why ) = Trog::DataSource::Virt::screenshot( { id => '../../..', conn_uri => 'test:///default' }, 'alpha' );
  136. is( $path, undef, 'nor does a path-shaped hypervisor id' );
  137. like( $why, qr/bad hypervisor id/, 'which is reported separately' );
  138. };
  139. subtest 'the guest cache is scoped per hypervisor' => sub {
  140. # Two hypervisors, each with a guest called 'alpha' -- which is the normal
  141. # state of affairs, not a corner case.
  142. my $root = Path::Tiny->tempdir();
  143. local $Trog::DataSource::Virt::screenshot_dir = "$root";
  144. my @paths;
  145. foreach my $id (qw{hv-1 hv-2}) {
  146. my ( $path, $why ) = Trog::DataSource::Virt::screenshot( { id => $id, conn_uri => 'test:///default' }, 'alpha' );
  147. ok( $path, "screenshot taken for $id" ) or diag($why);
  148. push( @paths, $path );
  149. }
  150. isnt( $paths[0], $paths[1], "two hypervisors' guests do not share a cache entry" );
  151. like( $paths[0], qr{/hv-1/alpha\.png$}, 'the path names the hypervisor and the guest' );
  152. };
  153. subtest 'the datasource hook only loads what it should' => sub {
  154. require Trog::Routes::HTML;
  155. my $htmlmock = Test::MockModule->new('Trog::Routes::HTML');
  156. $htmlmock->redefine( WARN => sub { note(shift) } );
  157. my $declared;
  158. my $dmmock = Test::MockModule->new('Trog::DataModule');
  159. $dmmock->redefine( type_meta_for => sub { return { 'x-tcms-datasource' => $declared } } );
  160. my @stored = ( { title => 'a stored post' } );
  161. my $query = { primary_post => { child_form => 'guests.tx' }, user_acls => ['admin'] };
  162. # A type that declares nothing keeps its own posts -- this hook must be
  163. # invisible to the overwhelming majority of pages.
  164. $declared = undef;
  165. is_deeply( [ Trog::Routes::HTML::_datasource_posts( $query, \@stored ) ], \@stored, 'no datasource declared, posts untouched' );
  166. # The namespace restriction is the point: a sidecar is a file on disk, and
  167. # it must not be able to make us require an arbitrary module.
  168. foreach my $bad ( 'Trog::Routes::HTML', 'File::Path', '../../etc/passwd', 'Trog::DataSource::Virt::act' ) {
  169. $declared = $bad;
  170. is_deeply( [ Trog::Routes::HTML::_datasource_posts( $query, \@stored ) ], \@stored, "'$bad' is refused as a datasource" );
  171. }
  172. # One that does not exist is a warning, not a dead page.
  173. $declared = 'Trog::DataSource::Nonexistent';
  174. is_deeply( [ Trog::Routes::HTML::_datasource_posts( $query, \@stored ) ], \@stored, 'a datasource that will not load falls back' );
  175. # And a real one is actually used.
  176. $declared = 'Trog::DataSource::Virt';
  177. $query->{primary_post}{hypervisors} = [ { id => 'hv-1', title => 'spec-hv', conn_uri => 'test:///default' } ];
  178. my @got = Trog::Routes::HTML::_datasource_posts( $query, \@stored );
  179. is( scalar @got, 2, 'a declared datasource replaces the stored posts' );
  180. is( $got[0]{title}, 'alpha', 'with what it built' );
  181. };
  182. subtest 'the guest routes avoid the router\'s own query keys' => sub {
  183. require Trog::Routes::HTML;
  184. # TPSGI applies a route's captures in extract_query, and *then* overwrites
  185. # $query->{domain} with the request's own host. A capture or form field by
  186. # that name therefore never reaches the callback -- which silently aimed
  187. # the screenshot and action routes at a guest named after the web host.
  188. my @reserved = qw{domain route method scheme port user acls to};
  189. my $captures = $Trog::Routes::HTML::routes{'/guest/screenshot/(.*)/(.*)'}{captures};
  190. foreach my $capture (@$captures) {
  191. ok( !( grep { $_ eq $capture } @reserved ), "the screenshot route's '$capture' capture is not a router key" );
  192. }
  193. # The action form posts the same field names the handler reads, so check
  194. # the template rather than trusting that they still agree.
  195. my $form = Path::Tiny->new("$FindBin::Bin/../www/templates/html/components/forms/guests.tx")->slurp_utf8;
  196. foreach my $reserved (@reserved) {
  197. unlike( $form, qr/name="\Q$reserved\E"/, "the guest action form does not post a field called '$reserved'" )
  198. unless $reserved eq 'to'; # 'to' is the redirect target, and is meant to be the router's
  199. }
  200. like( $form, qr/name="guest"/, 'it posts the guest under a name that survives routing' );
  201. };
  202. subtest 'guests show nothing an unprivileged viewer cannot use' => sub {
  203. require Text::Xslate;
  204. # Rendered rather than grepped: what matters is what a given viewer ends up
  205. # looking at, and the template has enough branches that reading it is not
  206. # the same as knowing.
  207. my $tx = Text::Xslate->new(
  208. path => ["$FindBin::Bin/../www/templates/html/components"],
  209. function => { render_it => sub { $_[0] } },
  210. );
  211. my %post = (
  212. form => 'guests.tx',
  213. id => 'uuid-alpha', title => 'alpha', state => 'running', is_active => 1,
  214. preview => '/guest/screenshot/hv-1/alpha', domain => 'alpha',
  215. hypervisor => 'hv-1', hypervisor_title => 'spec-hv', vcpus => 2,
  216. addpost => 0, unreachable => 0,
  217. );
  218. my %views = (
  219. 'tiled, logged out' => { tiled => 1, can_edit => 0 },
  220. 'untiled, logged out' => { tiled => 0, can_edit => 0 },
  221. 'untiled, admin' => { tiled => 0, can_edit => 1 },
  222. );
  223. require Trog::Routes::HTML;
  224. foreach my $view ( sort keys %views ) {
  225. my $admin = $views{$view}{can_edit};
  226. # Redact the way posts() does before rendering, so this covers the
  227. # thing that actually protects the capture -- the template only decides
  228. # whether to draw an img for a value it was given.
  229. my %shown = %post;
  230. Trog::Routes::HTML::_redact_private( \%shown ) unless $admin;
  231. my $out = $tx->render( 'forms/guests.tx', { post => \%shown, style => '', route => '/vm', %{ $views{$view} } } );
  232. # The guest is always named -- that is the point of the page.
  233. like( $out, qr/alpha/, "$view: the guest is listed" );
  234. # The screenshot route requires the admin acl, so showing the img to
  235. # anyone else is a broken image and nothing else.
  236. is( scalar( () = $out =~ m/<img /g ), $admin ? 1 : 0, "$view: console capture shown only to an admin" );
  237. is( scalar( () = $out =~ m{href="/guest/screenshot}g ), $admin ? 1 : 0, "$view: and so is the link to it" );
  238. # Powering off, snapshotting and destroying likewise.
  239. is( scalar( () = $out =~ m{action="/guest/act"}g ), $admin ? 1 : 0, "$view: controls shown only to an admin" );
  240. foreach my $action (qw{poweroff snapshot destroy}) {
  241. is( scalar( () = $out =~ m/value="\Q$action\E"/g ), $admin ? 1 : 0, "$view: no $action button" ) unless $admin;
  242. }
  243. }
  244. };
  245. subtest 'a datasource says whether its posts can be edited' => sub {
  246. require Trog::Routes::HTML;
  247. my $sources = Trog::Routes::HTML::_get_datasources();
  248. ok( ( grep { $_ eq 'Trog::DataSource::Virt' } @$sources ), 'the wizard can find this datasource' );
  249. ok( !( grep { !m/^Trog::DataSource::\w+$/ } @$sources ), 'and finds nothing that is not one' );
  250. is( Trog::DataSource::Virt->EDITABLE, 0, 'a guest cannot be edited' );
  251. is( Trog::Routes::HTML::_datasource_editable('Trog::DataSource::Virt'), 0, 'so no editor is appropriate' );
  252. # The datastore is the default, and posts in it are written by people.
  253. is( Trog::Routes::HTML::_datasource_editable(''), 1, 'the datastore is editable' );
  254. # A datasource that says nothing is assumed editable, since that is what a
  255. # post type is unless it has a reason not to be.
  256. {
  257. no warnings qw{once};
  258. $INC{'Trog/DataSource/SpecMute.pm'} = 1;
  259. @Trog::DataSource::SpecMute::ISA = ();
  260. }
  261. is( Trog::Routes::HTML::_datasource_editable('Trog::DataSource::SpecMute'), 1, 'one that declares nothing is assumed editable' );
  262. };
  263. subtest 'the guests type is built by the wizard, from a datasource' => sub {
  264. my $sidecar = JSON::MaybeXS::decode_json(
  265. Path::Tiny->new("$FindBin::Bin/../www/templates/html/components/forms/guests.json")->slurp_utf8 );
  266. is( $sidecar->{'x-tcms-datasource'}, 'Trog::DataSource::Virt', 'it names its datasource' );
  267. ok( $sidecar->{'x-tcms-post-type'}{generated}, 'and is wizard generated rather than hand written' );
  268. # The relation is what tells the datasource which hypervisors to ask.
  269. is_deeply( $sidecar->{'x-tcms-relations'}, { hypervisors => { form => 'hypervisor.tx' } },
  270. 'and keeps the relation the datasource reads' );
  271. # No editor: a guest is built on every view and has nothing to save.
  272. my $form = Path::Tiny->new("$FindBin::Bin/../www/templates/html/components/forms/guests.tx")->slurp_utf8;
  273. unlike( $form, qr{action="/post/save"}, 'the template offers no editor' );
  274. };
  275. subtest 'the guests type declares its console capture private' => sub {
  276. require Trog::DataModule;
  277. is_deeply( Trog::DataModule::private_fields_for('guests.tx'), ['preview'],
  278. 'so the url to it is withheld rather than guarded in the template' );
  279. };
  280. subtest 'private fields are dropped before a non-editor sees them' => sub {
  281. require Trog::Routes::HTML;
  282. require Trog::DataModule;
  283. my $dmmock = Test::MockModule->new('Trog::DataModule');
  284. $dmmock->redefine( private_fields_for => sub { return $_[0] eq 'secretive.tx' ? ['hidden'] : [] } );
  285. my $post = {
  286. form => 'secretive.tx',
  287. title => 'a post',
  288. hidden => 'the secret',
  289. shown => 'not a secret',
  290. # A relation is a post in its own right, with its own private fields.
  291. related => { form => 'secretive.tx', title => 'related', hidden => 'another secret' },
  292. many => [ { form => 'secretive.tx', hidden => 'a third secret' } ],
  293. other => { form => 'ordinary.tx', hidden => 'not declared private here' },
  294. };
  295. Trog::Routes::HTML::_redact_private($post);
  296. ok( !exists $post->{hidden}, 'the private field is gone' );
  297. is( $post->{shown}, 'not a secret', 'and the public ones are not' );
  298. is( $post->{title}, 'a post', '...including the ones every post has' );
  299. ok( !exists $post->{related}{hidden}, 'a related post is redacted too' );
  300. ok( !exists $post->{many}[0]{hidden}, 'and so is one reached through a list' );
  301. is( $post->{other}{hidden}, 'not declared private here', 'a type that declares nothing keeps everything' );
  302. };
  303. subtest 'a post that refers to itself does not hang the redactor' => sub {
  304. require Trog::Routes::HTML;
  305. require Trog::DataModule;
  306. my $dmmock = Test::MockModule->new('Trog::DataModule');
  307. $dmmock->redefine( private_fields_for => sub { return ['hidden'] } );
  308. my $post = { form => 'loop.tx', hidden => 'secret' };
  309. $post->{itself} = $post;
  310. # A relation can point back at whatever pulled it in.
  311. is( exception { Trog::Routes::HTML::_redact_private($post) }, undef, 'it terminates' );
  312. ok( !exists $post->{hidden}, 'having done the job' );
  313. };
  314. subtest 'a hypervisor does not show its connection uri to everyone' => sub {
  315. require Trog::DataModule;
  316. # The uri carries a host and a username, and these pages are public. It is
  317. # declared private rather than guarded in the template, so the value is
  318. # dropped before rendering and the template needs no guard of its own.
  319. my $private = Trog::DataModule::private_fields_for('hypervisor.tx');
  320. is_deeply( $private, ['conn_uri'], 'the connection uri is declared private' );
  321. my $sidecar = JSON::MaybeXS::decode_json(
  322. Path::Tiny->new("$FindBin::Bin/../www/templates/html/components/forms/hypervisor.json")->slurp_utf8 );
  323. ok( $sidecar->{properties}{conn_uri}{'x-tcms-private'}, 'and says so in its sidecar' );
  324. };
  325. done_testing();