Trog-DataSource-Virt.t 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. # Every subtest below that does not say otherwise runs as a machine which is
  60. # not one of the fake guests -- otherwise the suite's answers would depend on
  61. # what the box running it happens to be called.
  62. $Trog::DataSource::Virt::hostname = 'spec-host-that-is-no-guest';
  63. my $series = {
  64. child_form => 'guests.tx',
  65. tags => ['guests'],
  66. visibility => 'private',
  67. user => 'specadmin',
  68. hypervisors => [ { id => 'hv-1', title => 'spec-hv', conn_uri => 'test:///default' } ],
  69. };
  70. subtest 'guests become posts' => sub {
  71. @CALLS = ();
  72. my @posts = Trog::DataSource::Virt::posts( $series, { user_acls => ['admin'] } );
  73. is( scalar @posts, 2, 'one post per guest' );
  74. is( $posts[0]{title}, 'alpha', 'named after the guest' );
  75. is( $posts[0]{id}, 'uuid-alpha', "and identified by the guest's uuid, not ours" );
  76. is( $posts[0]{form}, 'guests.tx', "wearing the series' child type" );
  77. is( $posts[0]{state}, 'running', 'with a legible state' );
  78. is( $posts[1]{state}, 'shut off', '...for each of libvirt\'s numeric ones' );
  79. is( $posts[0]{is_active}, 1, 'active guests are marked so' );
  80. is( $posts[1]{is_active}, 0, 'and inactive ones are not' );
  81. # The listing must not take screenshots: that is a per-guest round trip,
  82. # and it is the browser's job via the preview route.
  83. is( $posts[0]{preview}, '/guest/screenshot/hv-1/alpha', 'the preview is a route, not an inline capture' );
  84. is_deeply( \@CALLS, [], 'and nothing was done to any guest merely by listing' );
  85. is_deeply( $posts[0]{tags}, ['guests'], "children inherit the series' tags" );
  86. is( $posts[0]{visibility}, 'private', 'and its visibility' );
  87. };
  88. subtest 'the guest this server runs on is marked as such' => sub {
  89. local $Trog::DataSource::Virt::hostname = 'alpha';
  90. my @posts = Trog::DataSource::Virt::posts( $series, { user_acls => ['admin'] } );
  91. is( $posts[0]{is_self}, 1, 'the guest named after this machine is flagged' );
  92. is( $posts[1]{is_self}, 0, 'and the one that merely lives beside it is not' );
  93. };
  94. subtest 'a guest is this server when it is named like it' => sub {
  95. my @same = (
  96. [ 'foo', 'foo' => 'the same name' ],
  97. [ 'foo', 'FOO' => 'the same name in another case' ],
  98. [ 'foo.troglodyne.net', 'foo.troglodyne.net' => 'both fully qualified' ],
  99. );
  100. foreach my $case (@same) {
  101. my ( $guest, $host, $why ) = @$case;
  102. local $Trog::DataSource::Virt::hostname = $host;
  103. ok( Trog::DataSource::Virt::_is_self($guest), "$why is this server" );
  104. }
  105. my @different = (
  106. [ 'beta', 'foo' => 'a different name' ],
  107. [ 'fooling', 'foo' => 'a name this one is only a prefix of' ],
  108. [ 'foo.test.test', 'foo.troglodyne.net' => 'the same label in someone else\'s domain' ],
  109. [ '', 'foo' => 'a guest with no name at all' ],
  110. [ 'foo', '' => 'any guest, when we cannot tell what we are called' ],
  111. );
  112. foreach my $case (@different) {
  113. my ( $guest, $host, $why ) = @$case;
  114. local $Trog::DataSource::Virt::hostname = $host;
  115. ok( !Trog::DataSource::Virt::_is_self($guest), "$why is not" );
  116. }
  117. };
  118. subtest 'an unreachable hypervisor says so rather than vanishing' => sub {
  119. $connect_fails = 1;
  120. my @posts = Trog::DataSource::Virt::posts( $series, { user_acls => ['admin'] } );
  121. $connect_fails = 0;
  122. is( scalar @posts, 1, 'we get a post back' );
  123. ok( $posts[0]{unreachable}, 'flagged as unreachable' );
  124. like( $posts[0]{state}, qr/unreachable/, 'saying as much' );
  125. is( $posts[0]{title}, 'spec-hv', 'named for the hypervisor we could not reach' );
  126. };
  127. subtest 'act() drives the right libvirt call, and only on request' => sub {
  128. my %expected = (
  129. poweron => 'create',
  130. poweroff => 'shutdown',
  131. snapshot => 'create_snapshot',
  132. destroy => 'destroy',
  133. );
  134. foreach my $action ( sort keys %expected ) {
  135. @CALLS = ();
  136. my ( $ok, $message ) = Trog::DataSource::Virt::act( $action, 'test:///default', 'alpha', 'specadmin' );
  137. ok( $ok, "$action succeeded" ) or diag($message);
  138. is_deeply( \@CALLS, [ [ $expected{$action}, 'alpha' ] ], "$action called $expected{$action} on the named guest, once" );
  139. }
  140. };
  141. subtest 'act() refuses what it should' => sub {
  142. @CALLS = ();
  143. my ( $ok, $message ) = Trog::DataSource::Virt::act( 'rm-rf', 'test:///default', 'alpha', 'specadmin' );
  144. ok( !$ok, 'an action we do not define is refused' );
  145. like( $message, qr/not something we do/, 'and says so' );
  146. ( $ok, $message ) = Trog::DataSource::Virt::act( 'destroy', 'test:///default', '../../etc/passwd', 'specadmin' );
  147. ok( !$ok, 'a guest name that is a path is refused' );
  148. like( $message, qr/bad guest name/, 'before any connection is made' );
  149. ( $ok, $message ) = Trog::DataSource::Virt::act( 'destroy', 'test:///default', 'nosuchguest', 'specadmin' );
  150. ok( !$ok, 'a guest that is not there is refused' );
  151. like( $message, qr/no guest called/, 'rather than acting on some other one' );
  152. is_deeply( \@CALLS, [], 'and none of those touched a guest' );
  153. $connect_fails = 1;
  154. ( $ok, $message ) = Trog::DataSource::Virt::act( 'poweroff', 'test:///default', 'alpha', 'specadmin' );
  155. $connect_fails = 0;
  156. ok( !$ok, 'an unreachable hypervisor is refused' );
  157. like( $message, qr/could not reach/, 'and reported' );
  158. is_deeply( \@CALLS, [], 'having done nothing' );
  159. };
  160. subtest 'act() will not take the server down with it' => sub {
  161. # Hiding the buttons is not the guard: /guest/act is a POST anybody with
  162. # the admin acl can craft, and if this went through there would be nothing
  163. # left running to say what happened.
  164. local $Trog::DataSource::Virt::hostname = 'alpha';
  165. foreach my $action (qw{poweroff destroy}) {
  166. @CALLS = ();
  167. my ( $ok, $message ) = Trog::DataSource::Virt::act( $action, 'test:///default', 'alpha', 'specadmin' );
  168. ok( !$ok, "$action on the guest we are running in is refused" );
  169. like( $message, qr/is this server/, 'saying why' );
  170. is_deeply( \@CALLS, [], "and the $action never reached libvirt" );
  171. }
  172. # The rest are not destructive, and a guest that cannot be snapshotted is
  173. # less useful than one that can.
  174. foreach my $action (qw{snapshot poweron}) {
  175. @CALLS = ();
  176. my ( $ok, $message ) = Trog::DataSource::Virt::act( $action, 'test:///default', 'alpha', 'specadmin' );
  177. ok( $ok, "$action is still allowed on it" ) or diag($message);
  178. is( scalar @CALLS, 1, 'and reached libvirt' );
  179. }
  180. # Its neighbours are ordinary guests.
  181. @CALLS = ();
  182. my ($ok) = Trog::DataSource::Virt::act( 'destroy', 'test:///default', 'beta', 'specadmin' );
  183. ok( $ok, 'another guest on the same hypervisor is unaffected' );
  184. is_deeply( \@CALLS, [ [ 'destroy', 'beta' ] ], 'and is destroyed as asked' );
  185. };
  186. subtest 'screenshot() validates its inputs before anything else' => sub {
  187. my $hv = { id => 'hv-1', conn_uri => 'test:///default' };
  188. my ( $path, $why ) = Trog::DataSource::Virt::screenshot( $hv, '../../../etc/passwd' );
  189. is( $path, undef, 'a path-shaped guest name gets no screenshot' );
  190. like( $why, qr/bad guest name/, 'and is named as the reason' );
  191. ( $path, $why ) = Trog::DataSource::Virt::screenshot( $hv, 'alpha/../../beta' );
  192. is( $path, undef, 'nor does one with traversal in the middle' );
  193. # The cache path is built from the hypervisor id too, so it has to be
  194. # checked as well -- otherwise it is a directory traversal of its own.
  195. ( $path, $why ) = Trog::DataSource::Virt::screenshot( { id => '../../..', conn_uri => 'test:///default' }, 'alpha' );
  196. is( $path, undef, 'nor does a path-shaped hypervisor id' );
  197. like( $why, qr/bad hypervisor id/, 'which is reported separately' );
  198. };
  199. subtest 'the guest cache is scoped per hypervisor' => sub {
  200. # Two hypervisors, each with a guest called 'alpha' -- which is the normal
  201. # state of affairs, not a corner case.
  202. my $root = Path::Tiny->tempdir();
  203. local $Trog::DataSource::Virt::screenshot_dir = "$root";
  204. my @paths;
  205. foreach my $id (qw{hv-1 hv-2}) {
  206. my ( $path, $why ) = Trog::DataSource::Virt::screenshot( { id => $id, conn_uri => 'test:///default' }, 'alpha' );
  207. ok( $path, "screenshot taken for $id" ) or diag($why);
  208. push( @paths, $path );
  209. }
  210. isnt( $paths[0], $paths[1], "two hypervisors' guests do not share a cache entry" );
  211. like( $paths[0], qr{/hv-1/alpha\.png$}, 'the path names the hypervisor and the guest' );
  212. };
  213. subtest 'the datasource hook only loads what it should' => sub {
  214. require Trog::Routes::HTML;
  215. my $htmlmock = Test::MockModule->new('Trog::Routes::HTML');
  216. $htmlmock->redefine( WARN => sub { note(shift) } );
  217. my $declared;
  218. my $dmmock = Test::MockModule->new('Trog::DataModule');
  219. $dmmock->redefine( type_meta_for => sub { return { 'x-tcms-datasource' => $declared } } );
  220. my @stored = ( { title => 'a stored post' } );
  221. my $query = { primary_post => { child_form => 'guests.tx' }, user_acls => ['admin'] };
  222. # A type that declares nothing keeps its own posts -- this hook must be
  223. # invisible to the overwhelming majority of pages.
  224. $declared = undef;
  225. is_deeply( [ Trog::Routes::HTML::_datasource_posts( $query, \@stored ) ], \@stored, 'no datasource declared, posts untouched' );
  226. # The namespace restriction is the point: a sidecar is a file on disk, and
  227. # it must not be able to make us require an arbitrary module.
  228. foreach my $bad ( 'Trog::Routes::HTML', 'File::Path', '../../etc/passwd', 'Trog::DataSource::Virt::act' ) {
  229. $declared = $bad;
  230. is_deeply( [ Trog::Routes::HTML::_datasource_posts( $query, \@stored ) ], \@stored, "'$bad' is refused as a datasource" );
  231. }
  232. # One that does not exist is a warning, not a dead page.
  233. $declared = 'Trog::DataSource::Nonexistent';
  234. is_deeply( [ Trog::Routes::HTML::_datasource_posts( $query, \@stored ) ], \@stored, 'a datasource that will not load falls back' );
  235. # And a real one is actually used.
  236. $declared = 'Trog::DataSource::Virt';
  237. $query->{primary_post}{hypervisors} = [ { id => 'hv-1', title => 'spec-hv', conn_uri => 'test:///default' } ];
  238. my @got = Trog::Routes::HTML::_datasource_posts( $query, \@stored );
  239. is( scalar @got, 2, 'a declared datasource replaces the stored posts' );
  240. is( $got[0]{title}, 'alpha', 'with what it built' );
  241. };
  242. subtest 'the guest routes avoid the router\'s own query keys' => sub {
  243. require Trog::Routes::HTML;
  244. # TPSGI applies a route's captures in extract_query, and *then* overwrites
  245. # $query->{domain} with the request's own host. A capture or form field by
  246. # that name therefore never reaches the callback -- which silently aimed
  247. # the screenshot and action routes at a guest named after the web host.
  248. my @reserved = qw{domain route method scheme port user acls to};
  249. my $captures = $Trog::Routes::HTML::routes{'/guest/screenshot/(.*)/(.*)'}{captures};
  250. foreach my $capture (@$captures) {
  251. ok( !( grep { $_ eq $capture } @reserved ), "the screenshot route's '$capture' capture is not a router key" );
  252. }
  253. # The action form posts the same field names the handler reads, so check
  254. # the template rather than trusting that they still agree.
  255. my $form = Path::Tiny->new("$FindBin::Bin/../www/templates/html/components/forms/guests.tx")->slurp_utf8;
  256. foreach my $reserved (@reserved) {
  257. unlike( $form, qr/name="\Q$reserved\E"/, "the guest action form does not post a field called '$reserved'" )
  258. unless $reserved eq 'to'; # 'to' is the redirect target, and is meant to be the router's
  259. }
  260. like( $form, qr/name="guest"/, 'it posts the guest under a name that survives routing' );
  261. };
  262. subtest 'guests show nothing an unprivileged viewer cannot use' => sub {
  263. require Text::Xslate;
  264. # Rendered rather than grepped: what matters is what a given viewer ends up
  265. # looking at, and the template has enough branches that reading it is not
  266. # the same as knowing.
  267. my $tx = Text::Xslate->new(
  268. path => ["$FindBin::Bin/../www/templates/html/components"],
  269. function => { render_it => sub { $_[0] } },
  270. );
  271. my %post = (
  272. form => 'guests.tx',
  273. id => 'uuid-alpha', title => 'alpha', state => 'running', is_active => 1,
  274. preview => '/guest/screenshot/hv-1/alpha', domain => 'alpha',
  275. hypervisor => 'hv-1', hypervisor_title => 'spec-hv', vcpus => 2,
  276. addpost => 0, unreachable => 0,
  277. );
  278. my %views = (
  279. 'tiled, logged out' => { tiled => 1, can_edit => 0 },
  280. 'untiled, logged out' => { tiled => 0, can_edit => 0 },
  281. 'untiled, admin' => { tiled => 0, can_edit => 1 },
  282. );
  283. require Trog::Routes::HTML;
  284. foreach my $view ( sort keys %views ) {
  285. my $admin = $views{$view}{can_edit};
  286. # Redact the way posts() does before rendering, so this covers the
  287. # thing that actually protects the capture -- the template only decides
  288. # whether to draw an img for a value it was given.
  289. my %shown = %post;
  290. Trog::Routes::HTML::_redact_private( \%shown ) unless $admin;
  291. my $out = $tx->render( 'forms/guests.tx', { post => \%shown, style => '', route => '/vm', %{ $views{$view} } } );
  292. # The guest is always named -- that is the point of the page.
  293. like( $out, qr/alpha/, "$view: the guest is listed" );
  294. # The screenshot route requires the admin acl, so showing the img to
  295. # anyone else is a broken image and nothing else.
  296. is( scalar( () = $out =~ m/<img /g ), $admin ? 1 : 0, "$view: console capture shown only to an admin" );
  297. is( scalar( () = $out =~ m{href="/guest/screenshot}g ), $admin ? 1 : 0, "$view: and so is the link to it" );
  298. # Powering off, snapshotting and destroying likewise.
  299. is( scalar( () = $out =~ m{action="/guest/act"}g ), $admin ? 1 : 0, "$view: controls shown only to an admin" );
  300. foreach my $action (qw{poweroff snapshot destroy}) {
  301. is( scalar( () = $out =~ m/value="\Q$action\E"/g ), $admin ? 1 : 0, "$view: no $action button" ) unless $admin;
  302. }
  303. }
  304. };
  305. subtest 'the server itself is drawn without the controls that would kill it' => sub {
  306. require Text::Xslate;
  307. my $tx = Text::Xslate->new(
  308. path => ["$FindBin::Bin/../www/templates/html/components"],
  309. function => { render_it => sub { $_[0] } },
  310. );
  311. my %post = (
  312. form => 'guests.tx',
  313. id => 'uuid-alpha', title => 'alpha', state => 'running', is_active => 1,
  314. preview => '/guest/screenshot/hv-1/alpha', domain => 'alpha',
  315. hypervisor => 'hv-1', hypervisor_title => 'spec-hv', vcpus => 2,
  316. addpost => 0, unreachable => 0,
  317. );
  318. foreach my $tiled ( 0, 1 ) {
  319. my $view = $tiled ? 'tiled' : 'untiled';
  320. my $me = $tx->render( 'forms/guests.tx',
  321. { post => { %post, is_self => 1 }, style => '', route => '/vm', tiled => $tiled, can_edit => 1 } );
  322. my $them = $tx->render( 'forms/guests.tx',
  323. { post => { %post, is_self => 0 }, style => '', route => '/vm', tiled => $tiled, can_edit => 1 } );
  324. # Said out loud, so an admin knows why this one is different.
  325. like( $me, qr/dom0/, "$view: the guest we are running in says so" );
  326. unlike( $them, qr/dom0/, "$view: and an ordinary guest does not" );
  327. }
  328. # Only the untiled view draws controls at all.
  329. my $me = $tx->render( 'forms/guests.tx',
  330. { post => { %post, is_self => 1 }, style => '', route => '/vm', tiled => 0, can_edit => 1 } );
  331. foreach my $action (qw{poweroff destroy}) {
  332. is( scalar( () = $me =~ m/value="\Q$action\E"/g ), 0, "no $action button for the server itself" );
  333. }
  334. is( scalar( () = $me =~ m/value="snapshot"/g ), 1, 'but it can still be snapshotted' );
  335. like( $me, qr{action="/guest/act"}, 'and the form is still there to do it with' );
  336. # A guest that is merely switched off must keep its Power On button -- the
  337. # is_self guard wraps that branch too.
  338. my $off = $tx->render( 'forms/guests.tx',
  339. { post => { %post, is_self => 0, is_active => 0, state => 'shut off' }, style => '', route => '/vm', tiled => 0, can_edit => 1 } );
  340. is( scalar( () = $off =~ m/value="poweron"/g ), 1, 'an ordinary stopped guest can still be started' );
  341. };
  342. subtest 'a datasource says whether its posts can be edited' => sub {
  343. require Trog::Routes::HTML;
  344. my $sources = Trog::Routes::HTML::_get_datasources();
  345. ok( ( grep { $_ eq 'Trog::DataSource::Virt' } @$sources ), 'the wizard can find this datasource' );
  346. ok( !( grep { !m/^Trog::DataSource::\w+$/ } @$sources ), 'and finds nothing that is not one' );
  347. is( Trog::DataSource::Virt->EDITABLE, 0, 'a guest cannot be edited' );
  348. is( Trog::Routes::HTML::_datasource_editable('Trog::DataSource::Virt'), 0, 'so no editor is appropriate' );
  349. # The datastore is the default, and posts in it are written by people.
  350. is( Trog::Routes::HTML::_datasource_editable(''), 1, 'the datastore is editable' );
  351. # A datasource that says nothing is assumed editable, since that is what a
  352. # post type is unless it has a reason not to be.
  353. {
  354. no warnings qw{once};
  355. $INC{'Trog/DataSource/SpecMute.pm'} = 1;
  356. @Trog::DataSource::SpecMute::ISA = ();
  357. }
  358. is( Trog::Routes::HTML::_datasource_editable('Trog::DataSource::SpecMute'), 1, 'one that declares nothing is assumed editable' );
  359. };
  360. subtest 'the guests type is built by the wizard, from a datasource' => sub {
  361. my $sidecar = JSON::MaybeXS::decode_json(
  362. Path::Tiny->new("$FindBin::Bin/../www/templates/html/components/forms/guests.json")->slurp_utf8 );
  363. is( $sidecar->{'x-tcms-datasource'}, 'Trog::DataSource::Virt', 'it names its datasource' );
  364. ok( $sidecar->{'x-tcms-post-type'}{generated}, 'and is wizard generated rather than hand written' );
  365. # The relation is what tells the datasource which hypervisors to ask.
  366. is_deeply( $sidecar->{'x-tcms-relations'}, { hypervisors => { form => 'hypervisor.tx' } },
  367. 'and keeps the relation the datasource reads' );
  368. # No editor: a guest is built on every view and has nothing to save.
  369. my $form = Path::Tiny->new("$FindBin::Bin/../www/templates/html/components/forms/guests.tx")->slurp_utf8;
  370. unlike( $form, qr{action="/post/save"}, 'the template offers no editor' );
  371. };
  372. subtest 'the guests type declares its console capture private' => sub {
  373. require Trog::DataModule;
  374. is_deeply( Trog::DataModule::private_fields_for('guests.tx'), ['preview'],
  375. 'so the url to it is withheld rather than guarded in the template' );
  376. };
  377. subtest 'private fields are dropped before a non-editor sees them' => sub {
  378. require Trog::Routes::HTML;
  379. require Trog::DataModule;
  380. my $dmmock = Test::MockModule->new('Trog::DataModule');
  381. $dmmock->redefine( private_fields_for => sub { return $_[0] eq 'secretive.tx' ? ['hidden'] : [] } );
  382. my $post = {
  383. form => 'secretive.tx',
  384. title => 'a post',
  385. hidden => 'the secret',
  386. shown => 'not a secret',
  387. # A relation is a post in its own right, with its own private fields.
  388. related => { form => 'secretive.tx', title => 'related', hidden => 'another secret' },
  389. many => [ { form => 'secretive.tx', hidden => 'a third secret' } ],
  390. other => { form => 'ordinary.tx', hidden => 'not declared private here' },
  391. };
  392. Trog::Routes::HTML::_redact_private($post);
  393. ok( !exists $post->{hidden}, 'the private field is gone' );
  394. is( $post->{shown}, 'not a secret', 'and the public ones are not' );
  395. is( $post->{title}, 'a post', '...including the ones every post has' );
  396. ok( !exists $post->{related}{hidden}, 'a related post is redacted too' );
  397. ok( !exists $post->{many}[0]{hidden}, 'and so is one reached through a list' );
  398. is( $post->{other}{hidden}, 'not declared private here', 'a type that declares nothing keeps everything' );
  399. };
  400. subtest 'a post that refers to itself does not hang the redactor' => sub {
  401. require Trog::Routes::HTML;
  402. require Trog::DataModule;
  403. my $dmmock = Test::MockModule->new('Trog::DataModule');
  404. $dmmock->redefine( private_fields_for => sub { return ['hidden'] } );
  405. my $post = { form => 'loop.tx', hidden => 'secret' };
  406. $post->{itself} = $post;
  407. # A relation can point back at whatever pulled it in.
  408. is( exception { Trog::Routes::HTML::_redact_private($post) }, undef, 'it terminates' );
  409. ok( !exists $post->{hidden}, 'having done the job' );
  410. };
  411. subtest 'a hypervisor does not show its connection uri to everyone' => sub {
  412. require Trog::DataModule;
  413. # The uri carries a host and a username, and these pages are public. It is
  414. # declared private rather than guarded in the template, so the value is
  415. # dropped before rendering and the template needs no guard of its own.
  416. my $private = Trog::DataModule::private_fields_for('hypervisor.tx');
  417. is_deeply( $private, ['conn_uri'], 'the connection uri is declared private' );
  418. my $sidecar = JSON::MaybeXS::decode_json(
  419. Path::Tiny->new("$FindBin::Bin/../www/templates/html/components/forms/hypervisor.json")->slurp_utf8 );
  420. ok( $sidecar->{properties}{conn_uri}{'x-tcms-private'}, 'and says so in its sidecar' );
  421. };
  422. done_testing();