Trog-DataSource-ProvisionedVirt.t 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. #!/usr/bin/env perl
  2. # Reprovisioning destroys a machine and builds it again, so the whole of this
  3. # file is about what has to be true before anything runs. _spawn is mocked
  4. # throughout: nothing here forks, and nothing here executes a provisioner.
  5. use 5.040;
  6. use re '/aasx';
  7. use warnings FATAL => 'all';
  8. use FindBin;
  9. use FindBin::libs;
  10. use Test::More;
  11. use Test::MockModule qw{strict};
  12. our ( $REPO, $ROOT, $OLDCWD );
  13. BEGIN {
  14. require Cwd;
  15. require File::Copy;
  16. require File::Path;
  17. require File::Temp;
  18. $REPO = Cwd::abs_path("$FindBin::Bin/..");
  19. $OLDCWD = Cwd::getcwd();
  20. $ROOT = File::Temp::tempdir( 'tcms-provisioned-XXXXXX', TMPDIR => 1, CLEANUP => 1 );
  21. $ENV{HOME} = $ROOT;
  22. File::Path::make_path("$ROOT/$_") for qw{config schema logs totp www/assets};
  23. # A vault, so that the half of this which is about not having to type a
  24. # passphrase every time has somewhere to keep one. The key arrives the way
  25. # a deployment hands one over, and Trog::Vault takes it out of %ENV as it
  26. # loads -- so this has to be set before the SUT is required, below.
  27. File::Copy::copy( "$REPO/schema/auth.schema", "$ROOT/schema/auth.schema" ) or die $!;
  28. require Crypt::Misc;
  29. require Crypt::PRNG;
  30. $ENV{TPSGI_VAULT_KEY} = Crypt::Misc::encode_b64( Crypt::PRNG::random_bytes(32) );
  31. # A stand-in for the checkout, with the one program a reprovision runs.
  32. # Never executed -- _spawn is mocked -- but it has to be there and
  33. # executable, because reprovision() checks that before it commits to
  34. # anything.
  35. File::Path::make_path("$ROOT/trog-provisioner/bin");
  36. my $program = "$ROOT/trog-provisioner/bin/provision";
  37. open( my $fh, '>', $program ) or die $!;
  38. print {$fh} "#!/bin/sh\nexit 0\n";
  39. close $fh;
  40. chmod( 0755, $program );
  41. # And a stand-in for the installation's own files, which live where the
  42. # provisioner keeps them rather than anywhere tCMS is told about.
  43. $ENV{TROG_PROVISIONER_CONFIG} = "$ROOT/etc";
  44. File::Path::make_path("$ROOT/etc/recipes.d");
  45. open( my $recipe, '>', "$ROOT/etc/recipes.d/guest.example.com.yaml" ) or die $!;
  46. print {$recipe} "---\n_global:\n registrar: secret:x/y/z\n";
  47. close $recipe;
  48. chdir($ROOT) or die "could not chdir to the sandbox: $!";
  49. }
  50. END {
  51. chdir($OLDCWD) if $OLDCWD;
  52. }
  53. sub write_config {
  54. my (%section) = @_;
  55. open( my $fh, '>', "$ROOT/config/default.cfg" ) or die $!;
  56. print {$fh} "[general]\n data_model=FlatFile\n[provisioner]\n";
  57. print {$fh} " $_=$section{$_}\n" foreach sort keys %section;
  58. close $fh;
  59. # Trog::Config memoises, which is what a running server wants and a test
  60. # emphatically does not.
  61. no warnings qw{once redefine};
  62. require Config::Simple;
  63. my $conf = Config::Simple->new("$ROOT/config/default.cfg");
  64. local $@;
  65. *Trog::Config::get = sub { return $conf };
  66. return;
  67. }
  68. require_ok('Trog::DataSource::ProvisionedVirt') or BAIL_OUT("Can't find SUT");
  69. Trog::Auth::useradd( 'admin', 'The Admin', 'hunter2', ['admin'], 'admin@example.com' )
  70. or BAIL_OUT('could not make a user to test with');
  71. my $log = Test::MockModule->new('Trog::DataSource::ProvisionedVirt');
  72. $log->redefine( WARN => sub { note(shift) } );
  73. $log->redefine( INFO => sub { note(shift) } );
  74. # Nothing in this file forks, and nothing in it runs a provisioner.
  75. our @SPAWNED;
  76. $log->redefine(
  77. _spawn => sub {
  78. my ( $domain, $credentials, $dir, $command, $user ) = @_;
  79. push( @SPAWNED, { domain => $domain, credentials => $credentials, dir => $dir, command => $command, user => $user } );
  80. return ( 1, 'started' );
  81. }
  82. );
  83. # Nor reaches a hypervisor.
  84. my $virt = Test::MockModule->new('Trog::DataSource::Virt');
  85. $virt->redefine( _is_self => sub { return $_[0] eq 'thisserver.example.com' ? 1 : 0 } );
  86. write_config( trog_provisioner => "$ROOT/trog-provisioner" );
  87. sub reprovision {
  88. @SPAWNED = ();
  89. return Trog::DataSource::ProvisionedVirt::reprovision( passphrase => 'hunter2', user => 'admin', @_ );
  90. }
  91. require Trog::Auth;
  92. require Trog::Vault;
  93. subtest 'it is Virt, with more' => sub {
  94. ok( Trog::DataSource::ProvisionedVirt->isa('Trog::DataSource::Virt'), 'it is a Virt' );
  95. # can() resolves through @ISA, which is how the datasource dispatcher finds
  96. # the halves this does not override.
  97. foreach my $inherited (qw{filter lang help}) {
  98. my $mine = Trog::DataSource::ProvisionedVirt->can($inherited);
  99. my $theirs = Trog::DataSource::Virt->can($inherited);
  100. is( $mine, $theirs, "$inherited is the one Virt already had" );
  101. }
  102. # Virt has no order() of its own, so this correctly finds none and the
  103. # dispatcher falls back to Trog::DataSource::order.
  104. ok( !Trog::DataSource::ProvisionedVirt->can('order'), 'and the shared default ordering still applies' );
  105. # posts() is the one thing it does replace.
  106. isnt(
  107. Trog::DataSource::ProvisionedVirt->can('posts'),
  108. Trog::DataSource::Virt->can('posts'),
  109. 'posts() is its own, since that is where the recipe is added'
  110. );
  111. is( Trog::DataSource::ProvisionedVirt->EDITABLE, 0, 'still nothing to edit' );
  112. is( Trog::DataSource::ProvisionedVirt->CACHEABLE, 0, 'and still never cached, since a guest\'s state is live' );
  113. };
  114. subtest 'the recipe lands on the guest' => sub {
  115. $virt->redefine(
  116. posts => sub {
  117. return (
  118. { title => 'guest.example.com', domain => 'guest.example.com', is_self => 0 },
  119. { title => 'norecipe.example.com', domain => 'norecipe.example.com', is_self => 0 },
  120. { title => 'thisserver.example.com', domain => 'thisserver.example.com', is_self => 1 },
  121. { title => 'a hypervisor', unreachable => 1, state => 'nope' },
  122. );
  123. }
  124. );
  125. my @posts = Trog::DataSource::ProvisionedVirt::posts( {}, {} );
  126. is( scalar(@posts), 4, 'every guest Virt listed is still listed' );
  127. my ($provisioned) = grep { ( $_->{domain} // '' ) eq 'guest.example.com' } @posts;
  128. ok( $provisioned->{has_recipe}, 'the one with a recipe says so' );
  129. like( $provisioned->{recipe}, qr/registrar/, 'and carries the recipe itself' );
  130. like( $provisioned->{recipe_path}, qr{recipes\.d/guest\.example\.com\.yaml$}, 'and where it came from' );
  131. is( $provisioned->{can_reprovision}, 1, 'and may be reprovisioned' );
  132. my ($bare) = grep { ( $_->{domain} // '' ) eq 'norecipe.example.com' } @posts;
  133. ok( !$bare->{has_recipe}, 'a guest with no recipe says so' );
  134. is( $bare->{can_reprovision}, 0, 'and may not be reprovisioned' );
  135. ok( exists $bare->{title}, 'but is listed all the same, since plenty of guests were not built by this' );
  136. my ($self) = grep { ( $_->{domain} // '' ) eq 'thisserver.example.com' } @posts;
  137. is( $self->{can_reprovision}, 0, 'the server drawing the page may never be reprovisioned' );
  138. my ($dead) = grep { $_->{unreachable} } @posts;
  139. ok( !$dead->{has_recipe}, 'an unreachable hypervisor is left exactly as it was' );
  140. };
  141. subtest 'what it refuses to reprovision' => sub {
  142. my ( $ok, $why ) = reprovision( domain => 'thisserver.example.com' );
  143. is( $ok, 0, 'the server it is running on' );
  144. like( $why, qr/this[ ]server/, 'and says why' );
  145. is_deeply( \@SPAWNED, [], 'without running anything' );
  146. ( $ok, $why ) = reprovision( domain => 'norecipe.example.com' );
  147. is( $ok, 0, 'a guest with no recipe' );
  148. like( $why, qr/no[ ]recipe/, 'and says why' );
  149. ( $ok, $why ) = reprovision( domain => 'guest.example.com', passphrase => '' );
  150. is( $ok, 0, 'a run with no passphrase, which the provisioner would just hang waiting for' );
  151. like( $why, qr/passphrase/, 'and says why' );
  152. # The name reaches the filesystem and an argument list.
  153. foreach my $bad ( '../../etc/passwd', 'guest;rm -rf /', 'guest example.com', '', 'a' x 300, '.hidden' ) {
  154. my ( $refused, $message ) = reprovision( domain => $bad );
  155. is( $refused, 0, "'$bad' is refused" );
  156. like( $message, qr/bad[ ]guest[ ]name|no[ ]recipe/, '...before anything is run' );
  157. }
  158. is_deeply( \@SPAWNED, [], 'and none of that ran a provisioner' );
  159. };
  160. subtest 'what it would run' => sub {
  161. my ( $ok, $why ) = reprovision( domain => 'guest.example.com' );
  162. is( $ok, 1, 'a guest with a recipe is accepted' ) or diag($why);
  163. like( $why, qr/started/, 'and reports that it started rather than that it finished' );
  164. is( scalar(@SPAWNED), 1, 'exactly one run' );
  165. my $run = $SPAWNED[0];
  166. is( $run->{domain}, 'guest.example.com', 'for the guest asked about' );
  167. is( $run->{user}, 'admin', 'recording who asked' );
  168. # One program does the whole of it now: bin/provision generates the guest's
  169. # configuration from its recipe and then builds the machine.
  170. is( $run->{dir}, "$ROOT/trog-provisioner", 'run from the checkout' );
  171. like( $run->{command}[0], qr{/bin/provision$}, 'and it is bin/provision' );
  172. is( $run->{command}[1], '--credentials', 'told that its passwords are coming on stdin' );
  173. is( $run->{command}[2], 'guest.example.com', 'and passed the guest as an argument' );
  174. # Arguments, not a command line: there is no shell between us and this, so a
  175. # guest name can never be read as one.
  176. is( scalar( @{ $run->{command} } ), 3, 'a program, a flag and one argument -- nothing to be parsed' );
  177. };
  178. subtest 'a stored passphrase, and a code instead of one' => sub {
  179. no warnings qw{once};
  180. # Nothing stored yet, so the form asks for the passphrase and offers to keep
  181. # it -- there is a vault key in this sandbox, so keeping it is on the table.
  182. $virt->redefine( posts => sub { return ( { title => 'guest.example.com', domain => 'guest.example.com', is_self => 0 } ) } );
  183. my ($post) = Trog::DataSource::ProvisionedVirt::posts( {}, { user => 'admin' } );
  184. is( $post->{passphrase_remembered}, 0, 'with nothing stored the form asks for the passphrase' );
  185. is( $post->{can_remember}, 1, 'and can offer to remember it' );
  186. # A code is worth nothing when there is nothing stored to unlock: it is
  187. # proof somebody is here, not a password.
  188. my ( $ok, $why ) = reprovision( domain => 'guest.example.com', passphrase => undef, totp => '123456' );
  189. is( $ok, 0, 'a code with nothing stored behind it does not provision' );
  190. is_deeply( \@SPAWNED, [], 'having run nothing' );
  191. # Reprovision the old way, and ask for it to be kept.
  192. ( $ok, $why ) = reprovision( domain => 'guest.example.com', passphrase => 'correct horse', remember => 1 );
  193. is( $ok, 1, 'a typed passphrase still provisions' ) or diag($why);
  194. is( $SPAWNED[0]{credentials}{keepass}, 'correct horse', 'and is what reaches the provisioner' );
  195. ($post) = Trog::DataSource::ProvisionedVirt::posts( {}, { user => 'admin' } );
  196. is( $post->{passphrase_remembered}, 1, 'after which the form asks for a code instead' );
  197. # And now the point of all of it: a code, spent, exchanged for what was
  198. # stored. Enrol first -- a code is only meaningful for somebody enrolled.
  199. my ( $uri, undef, undef, $message, $totp ) = Trog::Auth::totp( 'admin', 'example.com' );
  200. ok( $uri, 'the user is enrolled' ) or diag($message);
  201. my $code = $totp->expected_totp_code( time() );
  202. ( $ok, $why ) = reprovision( domain => 'guest.example.com', passphrase => undef, totp => $code );
  203. is( $ok, 1, 'a code provisions' ) or diag($why);
  204. is( $SPAWNED[0]{credentials}{keepass}, 'correct horse', 'handing the provisioner the passphrase that was stored' );
  205. # Spent, so it is worth this one reprovision and not every reprovision
  206. # somebody can click inside the window.
  207. ( $ok, $why ) = reprovision( domain => 'guest.example.com', passphrase => undef, totp => $code );
  208. is( $ok, 0, 'and cannot be used again' );
  209. like( $why, qr/already[ ]been[ ]used/, 'saying so' );
  210. is_deeply( \@SPAWNED, [], 'without running a second one' );
  211. Trog::Vault::forget( 'admin', $Trog::DataSource::ProvisionedVirt::secret_name );
  212. };
  213. subtest 'the sudo password on the hypervisor' => sub {
  214. no warnings qw{once};
  215. $virt->redefine( posts => sub { return ( { title => 'guest.example.com', domain => 'guest.example.com', is_self => 0 } ) } );
  216. Trog::Vault::forget( 'admin', $Trog::DataSource::ProvisionedVirt::secret_name );
  217. Trog::Vault::forget( 'admin', $Trog::DataSource::ProvisionedVirt::sudo_name );
  218. my ($post) = Trog::DataSource::ProvisionedVirt::posts( {}, { user => 'admin' } );
  219. is( $post->{sudo_remembered}, 0, 'with none stored the form asks for one' );
  220. # The ordinary case, and the reason the field is not required: the login on
  221. # the hypervisor has passwordless sudo, so there is nothing to send.
  222. my ( $ok, $why ) = reprovision( domain => 'guest.example.com', passphrase => 'correct horse' );
  223. is( $ok, 1, 'a reprovision with no sudo password still runs' ) or diag($why);
  224. ok( !exists $SPAWNED[0]{credentials}{sudo}, 'and sends none, rather than sending an empty one' );
  225. # And the case this is for: a hypervisor that wants one. sudo over ssh has
  226. # no terminal to ask at, so the run would otherwise die minutes in.
  227. ( $ok, $why ) = reprovision( domain => 'guest.example.com', passphrase => 'correct horse', sudo => 'hunter2' );
  228. is( $ok, 1, 'one with a sudo password runs too' ) or diag($why);
  229. is( $SPAWNED[0]{credentials}{sudo}, 'hunter2', 'and it reaches the provisioner' );
  230. is( $SPAWNED[0]{credentials}{keepass}, 'correct horse', 'alongside the passphrase, not instead of it' );
  231. # Kept, so the next run is a code and neither has to be typed again.
  232. ( $ok, $why ) = reprovision( domain => 'guest.example.com', passphrase => 'correct horse', sudo => 'hunter2', remember => 1 );
  233. is( $ok, 1, 'both can be remembered' ) or diag($why);
  234. ($post) = Trog::DataSource::ProvisionedVirt::posts( {}, { user => 'admin' } );
  235. is( $post->{passphrase_remembered}, 1, 'after which the passphrase is stored' );
  236. is( $post->{sudo_remembered}, 1, 'and so is the sudo password' );
  237. my ( undef, undef, undef, undef, $totp ) = Trog::Auth::totp( 'admin', 'example.com' );
  238. require Trog::SQLite;
  239. Trog::SQLite::dbh( 'schema/auth.schema', 'config/auth.db' )->do("DELETE FROM totp_spent WHERE username='admin'");
  240. ( $ok, $why ) = reprovision( domain => 'guest.example.com', passphrase => undef, totp => $totp->expected_totp_code( time() ) );
  241. is( $ok, 1, 'a code unlocks the pair' ) or diag($why);
  242. is( $SPAWNED[0]{credentials}{keepass}, 'correct horse', 'the passphrase' );
  243. is( $SPAWNED[0]{credentials}{sudo}, 'hunter2', 'and the sudo password' );
  244. # Typed beats stored: somebody typing it has a reason to, and it is usually
  245. # that the stored one stopped working.
  246. Trog::SQLite::dbh( 'schema/auth.schema', 'config/auth.db' )->do("DELETE FROM totp_spent WHERE username='admin'");
  247. ( $ok, $why ) = reprovision( domain => 'guest.example.com', passphrase => undef, sudo => 'changed it', totp => $totp->expected_totp_code( time() ) );
  248. is( $ok, 1, 'a code and a typed sudo password together' ) or diag($why);
  249. is( $SPAWNED[0]{credentials}{sudo}, 'changed it', 'send what was typed' );
  250. Trog::Vault::forget( 'admin', $Trog::DataSource::ProvisionedVirt::secret_name );
  251. Trog::Vault::forget( 'admin', $Trog::DataSource::ProvisionedVirt::sudo_name );
  252. };
  253. subtest 'a password with a line break in it is refused' => sub {
  254. # One 'name: value' per line is the format on the far side, so a newline in
  255. # a value is a second line -- and the second line could name a credential
  256. # nobody asked us to send.
  257. my ( $ok, $why ) = reprovision( domain => 'guest.example.com', passphrase => "correct horse\nsudo: injected" );
  258. is( $ok, 0, 'a passphrase carrying a line break does not run' );
  259. like( $why, qr/line[ ]break/, 'saying so' );
  260. is_deeply( \@SPAWNED, [], 'having run nothing' );
  261. ( $ok, $why ) = reprovision( domain => 'guest.example.com', passphrase => 'correct horse', sudo => "hunter2\nkeepass: not this" );
  262. is( $ok, 0, 'and neither does a sudo password carrying one' );
  263. like( $why, qr/line[ ]break/, 'saying so too' );
  264. is_deeply( \@SPAWNED, [], 'having run nothing' );
  265. };
  266. subtest 'and when the vault key has gone' => sub {
  267. no warnings qw{once};
  268. # The key lives and dies with the machine, so this is the ordinary
  269. # consequence of rebuilding one rather than a disaster. What must not
  270. # happen is the page going on asking for a code it cannot honour.
  271. Trog::Vault::set( 'admin', $Trog::DataSource::ProvisionedVirt::secret_name, 'correct horse' );
  272. $virt->redefine( posts => sub { return ( { title => 'guest.example.com', domain => 'guest.example.com', is_self => 0 } ) } );
  273. my ($post) = Trog::DataSource::ProvisionedVirt::posts( {}, { user => 'admin' } );
  274. is( $post->{passphrase_remembered}, 1, 'with the key here, the form asks for a code' );
  275. local $Trog::Vault::master = Crypt::PRNG::random_bytes(32);
  276. ($post) = Trog::DataSource::ProvisionedVirt::posts( {}, { user => 'admin' } );
  277. is( $post->{passphrase_remembered}, 0, 'and with it gone, back to asking for the passphrase' );
  278. is( $post->{can_reprovision}, 1, 'the button is still offered, since it still works that way' );
  279. # Posted at directly, as somebody would from a page drawn a moment before
  280. # the key went away.
  281. my ( undef, undef, undef, undef, $totp ) = Trog::Auth::totp( 'admin', 'example.com' );
  282. # The subtest above spent this window's codes. Standing here for thirty
  283. # seconds would say the same thing and cost thirty seconds.
  284. require Trog::SQLite;
  285. Trog::SQLite::dbh( 'schema/auth.schema', 'config/auth.db' )->do("DELETE FROM totp_spent WHERE username='admin'");
  286. my $code = $totp->expected_totp_code( time() );
  287. my ( $ok, $why ) = reprovision( domain => 'guest.example.com', passphrase => undef, totp => $code );
  288. is( $ok, 0, 'a code is refused rather than exploding' );
  289. like( $why, qr/can[ ]open/, 'saying the passphrase cannot be opened' );
  290. like( $why, qr{/secrets}, 'and where to go about it' );
  291. is_deeply( \@SPAWNED, [], 'having provisioned nothing' );
  292. # And the refusal came before the code was spent, so the same code is still
  293. # good for the thing that does work. Being told to go and re-store a
  294. # passphrase should not also cost somebody thirty seconds.
  295. ( $ok, $why ) = Trog::Auth::spend_totp( 'admin', $code );
  296. is( $ok, 1, 'the code was not spent on being told no' ) or diag($why);
  297. ( $ok, $why ) = reprovision( domain => 'guest.example.com', passphrase => 'typed it again', remember => 1 );
  298. is( $ok, 1, 'and the passphrase still provisions' ) or diag($why);
  299. is( $SPAWNED[0]{credentials}{keepass}, 'typed it again', 'with what was typed' );
  300. ($post) = Trog::DataSource::ProvisionedVirt::posts( {}, { user => 'admin' } );
  301. is( $post->{passphrase_remembered}, 1, 'stored again under the key that is here now' );
  302. };
  303. subtest 'without the provisioner configured it is just Virt' => sub {
  304. write_config();
  305. my ( $ok, $why ) = reprovision( domain => 'guest.example.com' );
  306. is( $ok, 0, 'nothing to run' );
  307. like( $why, qr/not[ ]configured/, 'and says so plainly' );
  308. is_deeply( \@SPAWNED, [], 'having run nothing' );
  309. $virt->redefine( posts => sub { return ( { title => 'guest.example.com', domain => 'guest.example.com', is_self => 0 } ) } );
  310. my ($post) = Trog::DataSource::ProvisionedVirt::posts( {}, {} );
  311. ok( !$post->{has_recipe}, 'the listing still works' );
  312. is( $post->{can_reprovision}, 0, 'it simply offers no button' );
  313. # A path that is not there is a typo, and better found here than halfway
  314. # through a reprovision.
  315. write_config( trog_provisioner => "$ROOT/nonesuch" );
  316. ( $ok, $why ) = reprovision( domain => 'guest.example.com' );
  317. is( $ok, 0, 'a configured path which is not there is refused' );
  318. like( $why, qr/not[ ]configured/, 'the same as never having configured one' );
  319. write_config( trog_provisioner => "$ROOT/trog-provisioner" );
  320. };
  321. subtest 'the log is read back onto the page' => sub {
  322. no warnings qw{once};
  323. File::Path::make_path("$ROOT/logs/reprovision");
  324. open( my $fh, '>', "$ROOT/logs/reprovision/guest.example.com.log" ) or die $!;
  325. print {$fh} ( 'x' x 9000 ) . "\n=== finished ===\n";
  326. close $fh;
  327. my $tail = Trog::DataSource::ProvisionedVirt::_log_tail('guest.example.com');
  328. ok( length($tail) <= $Trog::DataSource::ProvisionedVirt::log_tail_bytes, 'only the tail of it' );
  329. like( $tail, qr/===[ ]finished[ ]===/, 'which is the part that says how it went' );
  330. is( Trog::DataSource::ProvisionedVirt::_log_tail('norecipe.example.com'), undef, 'nothing when it has never run' );
  331. is( Trog::DataSource::ProvisionedVirt::_log_tail('../../etc/passwd'), undef, 'and a name that is not one reads nothing' );
  332. };
  333. subtest 'the state a reprovision leaves behind' => sub {
  334. no warnings qw{once};
  335. File::Path::make_path("$ROOT/logs/reprovision");
  336. my $status = "$ROOT/logs/reprovision/guest.example.com.status";
  337. my $write = sub {
  338. open( my $fh, '>', $status ) or die $!;
  339. print {$fh} join( '', map { "$_\n" } @_ );
  340. close $fh;
  341. };
  342. # Nothing waits on the process which does the work, so this file is the
  343. # whole of what it can say for itself.
  344. $write->(qw{state=ok started=100 finished=200 exit=0 user=admin});
  345. my $got = Trog::DataSource::ProvisionedVirt::status('guest.example.com');
  346. is( $got->{state}, 'ok', 'a finished run reads back as finished' );
  347. is( $got->{exit}, '0', 'with what it exited' );
  348. is( $got->{user}, 'admin', 'and who asked for it' );
  349. is( $got->{finished}, '200', 'and when it stopped' );
  350. $write->(qw{state=failed exit=3 failed=/x/bin/provision});
  351. is( Trog::DataSource::ProvisionedVirt::status('guest.example.com')->{state}, 'failed', 'a failed one reads back failed' );
  352. # A live pid means it really is going on. Ours is alive by definition.
  353. $write->( 'state=running', "pid=$$", 'started=100', 'user=admin' );
  354. is( Trog::DataSource::ProvisionedVirt::status('guest.example.com')->{state}, 'running', 'a run whose process is alive is running' );
  355. # And a dead one means it stopped without saying so, which is the case that
  356. # would otherwise leave the page claiming a provision forever.
  357. my $dead = 999999;
  358. $dead++ while kill( 0, $dead ) && $dead < 4194304;
  359. $write->( 'state=running', "pid=$dead", 'started=100' );
  360. is(
  361. Trog::DataSource::ProvisionedVirt::status('guest.example.com')->{state},
  362. 'interrupted',
  363. 'a run whose process is gone reads as interrupted, not as still going'
  364. );
  365. $write->('state=running');
  366. is( Trog::DataSource::ProvisionedVirt::status('guest.example.com')->{state}, 'interrupted', 'and so does one with no pid at all' );
  367. # Half a file is not a status.
  368. $write->('garbage');
  369. is( Trog::DataSource::ProvisionedVirt::status('guest.example.com'), undef, 'an unparseable status is no status' );
  370. is( Trog::DataSource::ProvisionedVirt::status('never.example.com'), undef, 'nothing for a guest that has never run' );
  371. is( Trog::DataSource::ProvisionedVirt::status('../../etc/passwd'), undef, 'and a name that is not one reads nothing' );
  372. unlink($status);
  373. };
  374. subtest 'the listing says what is going on' => sub {
  375. no warnings qw{once};
  376. File::Path::make_path("$ROOT/logs/reprovision");
  377. my $status = "$ROOT/logs/reprovision/guest.example.com.status";
  378. open( my $log, '>', "$ROOT/logs/reprovision/guest.example.com.log" ) or die $!;
  379. print {$log} "some output\n";
  380. close $log;
  381. $virt->redefine( posts => sub { return ( { title => 'guest.example.com', domain => 'guest.example.com', is_self => 0 } ) } );
  382. open( my $fh, '>', $status ) or die $!;
  383. print {$fh} "state=running\npid=$$\nstarted=100\nuser=admin\n";
  384. close $fh;
  385. my ($post) = Trog::DataSource::ProvisionedVirt::posts( {}, {} );
  386. is( $post->{reprovision_state}, 'running', 'the guest says it is reprovisioning' );
  387. is( $post->{reprovision_status}, 'reprovisioning', 'in words a person reads' );
  388. is( $post->{is_reprovisioning}, 1, 'and is flagged as busy' );
  389. is( $post->{reprovision_by}, 'admin', 'naming who started it' );
  390. is( $post->{can_reprovision}, 0, 'and offers no button while one is going on' );
  391. is( $post->{reprovision_log_href}, '/guest/reprovision/log/guest.example.com', 'with a link to read the log' );
  392. # Starting a second one is refused for the same reason.
  393. my ( $ok, $why ) = reprovision( domain => 'guest.example.com' );
  394. is( $ok, 0, 'and a second run is refused while the first is going' );
  395. like( $why, qr/already[ ]running/, 'saying so' );
  396. is_deeply( \@SPAWNED, [], 'having started nothing' );
  397. open( $fh, '>', $status ) or die $!;
  398. print {$fh} "state=failed\nexit=3\nstarted=100\nfinished=200\nuser=admin\n";
  399. close $fh;
  400. ($post) = Trog::DataSource::ProvisionedVirt::posts( {}, {} );
  401. is( $post->{reprovision_state}, 'failed', 'a failed run says so' );
  402. is( $post->{reprovision_status}, 'reprovision failed', 'in words' );
  403. is( $post->{reprovision_exit}, '3', 'with what it exited' );
  404. is( $post->{is_reprovisioning}, 0, 'and is not busy' );
  405. is( $post->{can_reprovision}, 1, 'so it may be tried again' );
  406. unlink($status);
  407. ($post) = Trog::DataSource::ProvisionedVirt::posts( {}, {} );
  408. ok( !$post->{reprovision_state}, 'a guest which has never been reprovisioned says nothing about it' );
  409. is( $post->{can_reprovision}, 1, 'and may be' );
  410. };
  411. subtest 'reading the log' => sub {
  412. no warnings qw{once};
  413. is( Trog::DataSource::ProvisionedVirt::log_for('never.example.com'), undef, 'nothing when there has been no run' );
  414. is( Trog::DataSource::ProvisionedVirt::log_for('../../etc/passwd'), undef, 'and a name that is not one reads nothing' );
  415. open( my $fh, '>', "$ROOT/logs/reprovision/guest.example.com.log" ) or die $!;
  416. print {$fh} "the whole log\n";
  417. close $fh;
  418. like( Trog::DataSource::ProvisionedVirt::log_for('guest.example.com'), qr/the[ ]whole[ ]log/, 'and the whole of it when there has' );
  419. # A provisioner can be chatty, and this goes out in one response.
  420. local $Trog::DataSource::ProvisionedVirt::log_max_bytes = 64;
  421. open( $fh, '>', "$ROOT/logs/reprovision/guest.example.com.log" ) or die $!;
  422. print {$fh} ( 'x' x 500 ) . "END\n";
  423. close $fh;
  424. my $capped = Trog::DataSource::ProvisionedVirt::log_for('guest.example.com');
  425. like( $capped, qr/truncated/, 'a huge one is truncated' );
  426. like( $capped, qr/END/, 'keeping the end, which is where the answer is' );
  427. };
  428. subtest 'the route' => sub {
  429. no warnings qw{once};
  430. require Trog::Routes::HTML;
  431. my $route = $Trog::Routes::HTML::routes{'/guest/reprovision'};
  432. ok( $route, 'is registered' );
  433. is( $route->{method}, 'POST', 'POST only, since it is not a thing to do by following a link' );
  434. is( $route->{auth}, 1, 'and requires a login' );
  435. ok( $route->{nocache}, 'and is never cached' );
  436. ok( $route->{noindex}, 'nor indexed' );
  437. my $tpsgi = bless {}, 'FakeTPSGI3';
  438. {
  439. no warnings qw{once};
  440. *FakeTPSGI3::see_also = sub { return [ 303, [ Location => $_[1] ], [''] ] };
  441. *FakeTPSGI3::forbidden = sub { return [ 403, [], ['no'] ] };
  442. *FakeTPSGI3::notfound = sub { return [ 404, [], ['gone'] ] };
  443. }
  444. # Admin only, like every other thing that changes a guest.
  445. my $res = Trog::Routes::HTML::guest_reprovision( { user => 'bob', user_acls => ['public'], tpsgi => $tpsgi } );
  446. is( $res->[0], 403, 'a non-admin is refused' );
  447. is_deeply( \@SPAWNED, [], 'without running anything' );
  448. $res = Trog::Routes::HTML::guest_reprovision( { user => '', user_acls => [], tpsgi => $tpsgi } );
  449. is( $res->[0], 303, 'and somebody logged out is sent to log in' );
  450. # The passphrase must not survive the request: this hash gets cloned, logged
  451. # around and handed to renderers.
  452. @SPAWNED = ();
  453. my $query = { user => 'admin', user_acls => ['admin'], tpsgi => $tpsgi, guest => 'guest.example.com', passphrase => 'hunter2', sudo => 'letmein', to => '/vms' };
  454. Trog::Routes::HTML::guest_reprovision($query);
  455. is( scalar(@SPAWNED), 1, 'an admin gets their run' );
  456. is( $SPAWNED[0]{credentials}{keepass}, 'hunter2', 'the passphrase reaches the provisioner' );
  457. is( $SPAWNED[0]{credentials}{sudo}, 'letmein', 'and so does the sudo password' );
  458. # This hash is cloned, logged around and handed to renderers.
  459. ok( !exists $query->{$_}, "the $_ is gone from the query afterwards" ) foreach qw{passphrase sudo totp};
  460. # The log route. It lives in logs/ rather than under www/, and the output
  461. # of a provisioner is a fine place for a hostname or an IP plan to turn up.
  462. my $logroute = $Trog::Routes::HTML::routes{'/guest/reprovision/log/(.*)'};
  463. ok( $logroute, 'the log route is registered' );
  464. is( $logroute->{method}, 'GET', 'as a GET, since it only reads' );
  465. is( $logroute->{auth}, 1, 'behind a login' );
  466. is_deeply( $logroute->{captures}, ['guest'], "capturing 'guest', which survives routing" );
  467. $res = Trog::Routes::HTML::guest_reprovision_log( { user => 'bob', user_acls => ['public'], tpsgi => $tpsgi } );
  468. is( $res->[0], 403, 'a non-admin cannot read it' );
  469. $res = Trog::Routes::HTML::guest_reprovision_log( { user => 'admin', user_acls => ['admin'], tpsgi => $tpsgi, guest => 'never.example.com' } );
  470. is( $res->[0], 404, 'and a guest with no log is a 404 rather than an empty page' );
  471. };
  472. done_testing();