Trog-Vault.t 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. #!/usr/bin/env perl
  2. # The vault, the code that authorizes opening it, and the hashing underneath
  3. # both. Nothing here needs a webserver: what is being tested is that a database
  4. # on its own is not enough, and that a code is worth one thing.
  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-vault-XXXXXX', TMPDIR => 1, CLEANUP => 1 );
  21. $ENV{HOME} = $ROOT;
  22. File::Path::make_path( map { "$ROOT/$_" } qw{config schema logs totp} );
  23. File::Copy::copy( "$REPO/schema/auth.schema", "$ROOT/schema/auth.schema" ) or die $!;
  24. open( my $fh, '>', "$ROOT/config/default.cfg" ) or die $!;
  25. print {$fh} "[general]\n data_model=FlatFile\n hostname=vault.example.com\n";
  26. close($fh) or die $!;
  27. # The key the way a deployment hands one over: base64, in the environment,
  28. # put there by tpsgi.sh out of a systemd credential. Trog::Vault takes it
  29. # out of %ENV as it loads, which is the behaviour tested below.
  30. require Crypt::PRNG;
  31. require Crypt::Misc;
  32. $ENV{TPSGI_VAULT_KEY} = Crypt::Misc::encode_b64( Crypt::PRNG::random_bytes(32) );
  33. chdir($ROOT) or die "could not chdir to the sandbox: $!";
  34. }
  35. END {
  36. chdir($OLDCWD) if $OLDCWD;
  37. }
  38. require_ok('Trog::Auth') or BAIL_OUT("Can't find Trog::Auth");
  39. require_ok('Trog::Vault') or BAIL_OUT("Can't find SUT");
  40. Trog::Auth::useradd( 'bob', 'Bob Bobson', 'hunter2', ['admin'], 'bob@example.com' )
  41. or BAIL_OUT('could not make a user to test with');
  42. Trog::Auth::useradd( 'eve', 'Eve Evilson', 'letmein', ['public'], 'eve@example.com' )
  43. or BAIL_OUT('could not make a second user');
  44. subtest 'the key is taken out of the environment' => sub {
  45. ok( Trog::Vault::has_key(), 'the key was read' );
  46. ok( !exists $ENV{TPSGI_VAULT_KEY}, 'and is gone from the environment, so nothing we fork inherits it' );
  47. like( Trog::Vault::key_id(), qr/^[\da-f]{16}$/, 'and fingerprints to something a row can name' );
  48. };
  49. subtest 'what a secret looks like on disk' => sub {
  50. my ( $ok, $why ) = Trog::Vault::set( 'bob', 'keepass', 'correct horse battery staple' );
  51. is( $ok, 1, 'a secret can be stored' ) or diag($why);
  52. my $dbh = Trog::SQLite::dbh( 'schema/auth.schema', 'config/auth.db' );
  53. my $rows = $dbh->selectall_arrayref( "SELECT * FROM user_secret WHERE username='bob'", { Slice => {} } );
  54. is( scalar(@$rows), 1, 'and lands in one row' );
  55. my $row = $rows->[0];
  56. unlike( $row->{ciphertext}, qr/correct[ ]horse/, 'which does not contain the secret' );
  57. is( length( $row->{salt} ), 32, 'carries a fresh 32 byte salt' );
  58. is( length( $row->{tag} ), 16, 'and a GCM tag' );
  59. is( $row->{key_id}, Trog::Vault::key_id(), 'naming the key it was sealed under' );
  60. is( Trog::Vault::get( 'bob', 'keepass' ), 'correct horse battery staple', 'and it comes back out' );
  61. ( $ok, $why ) = Trog::Vault::set(qw{bob pin 0});
  62. is( $ok, 1, 'a secret of "0" is a secret, not nothing' ) or diag($why);
  63. is( Trog::Vault::get( 'bob', 'pin' ), '0', 'and comes back out' );
  64. };
  65. subtest 'a fresh salt every write' => sub {
  66. my $dbh = Trog::SQLite::dbh( 'schema/auth.schema', 'config/auth.db' );
  67. Trog::Vault::set( 'bob', 'same', 'the very same secret' );
  68. my ($first) = $dbh->selectrow_array("SELECT hex(ciphertext) FROM user_secret WHERE username='bob' AND name='same'");
  69. Trog::Vault::set( 'bob', 'same', 'the very same secret' );
  70. my ($second) = $dbh->selectrow_array("SELECT hex(ciphertext) FROM user_secret WHERE username='bob' AND name='same'");
  71. # Same plaintext, same key, different ciphertext -- which is what a random
  72. # salt per write buys, and what GCM needs to stay safe.
  73. isnt( $first, $second, 'the same secret stored twice does not look the same twice' );
  74. is( Trog::Vault::get( 'bob', 'same' ), 'the very same secret', 'and still reads back' );
  75. };
  76. subtest 'a row cannot be moved or renamed' => sub {
  77. my $dbh = Trog::SQLite::dbh( 'schema/auth.schema', 'config/auth.db' );
  78. # Exactly what somebody with write access to the database would try: take
  79. # the admin's sealed passphrase and make it their own.
  80. $dbh->do("INSERT OR REPLACE INTO user_secret (username, name, key_id, salt, ciphertext, tag, created) SELECT 'eve', name, key_id, salt, ciphertext, tag, created FROM user_secret WHERE username='bob' AND name='keepass'");
  81. is( Trog::Vault::get( 'eve', 'keepass' ), undef, 'a row lifted into another account does not open' );
  82. $dbh->do("INSERT OR REPLACE INTO user_secret (username, name, key_id, salt, ciphertext, tag, created) SELECT 'bob', 'renamed', key_id, salt, ciphertext, tag, created FROM user_secret WHERE username='bob' AND name='keepass'");
  83. is( Trog::Vault::get( 'bob', 'renamed' ), undef, 'nor does one renamed into being the answer to a different question' );
  84. is( Trog::Vault::get( 'bob', 'keepass' ), 'correct horse battery staple', 'while the row it was copied from is untouched' );
  85. $dbh->do("DELETE FROM user_secret WHERE name IN ('renamed') OR username='eve'");
  86. };
  87. subtest 'and not without the key it was sealed under' => sub {
  88. my $dbh = Trog::SQLite::dbh( 'schema/auth.schema', 'config/auth.db' );
  89. # A different installation's key, which is what a stolen database meets.
  90. {
  91. no warnings qw{once};
  92. local $Trog::Vault::master = Crypt::PRNG::random_bytes(32);
  93. is( Trog::Vault::get( 'bob', 'keepass' ), undef, 'the wrong key opens nothing' );
  94. my $listed = Trog::Vault::list('bob');
  95. my ($keepass) = grep { $_->{name} eq 'keepass' } @$listed;
  96. is( $keepass->{readable}, 0, 'and the listing says so rather than pretending' );
  97. }
  98. is( Trog::Vault::get( 'bob', 'keepass' ), 'correct horse battery staple', 'the right one still does' );
  99. # Tampering, as opposed to the wrong key: the tag is what notices.
  100. $dbh->do("UPDATE user_secret SET ciphertext = ciphertext || X'00' WHERE username='bob' AND name='keepass'");
  101. is( Trog::Vault::get( 'bob', 'keepass' ), undef, 'a row somebody edited does not open either' );
  102. Trog::Vault::set( 'bob', 'keepass', 'correct horse battery staple' );
  103. };
  104. subtest 'the listing never shows a value' => sub {
  105. my $listed = Trog::Vault::list('bob');
  106. ok( scalar(@$listed) >= 2, 'lists what bob has' );
  107. foreach my $secret (@$listed) {
  108. ok( !exists $secret->{ciphertext}, "$secret->{name} is listed without its ciphertext" );
  109. ok( exists $secret->{created}, "$secret->{name} says when it was stored" );
  110. }
  111. is_deeply( Trog::Vault::list('eve'), [], 'and one user cannot see another\'s' );
  112. ok( Trog::Vault::forget( 'bob', 'same' ), 'a secret can be forgotten' );
  113. is( Trog::Vault::get( 'bob', 'same' ), undef, 'after which it is gone' );
  114. is( Trog::Vault::forget( 'bob', 'same' ), 0, 'and forgetting it twice is not a thing that happened' );
  115. };
  116. subtest 'a name is a name' => sub {
  117. foreach my $bad ( '../../etc/passwd', 'has spaces', '', 'a' x 100, '.hidden' ) {
  118. my ( $ok, undef ) = Trog::Vault::set( 'bob', $bad, 'nope' );
  119. is( $ok, 0, "'$bad' is refused as a name" );
  120. }
  121. my ( $ok, undef ) = Trog::Vault::set( 'bob', 'fine', '' );
  122. is( $ok, 0, 'and an empty secret is not a secret' );
  123. };
  124. subtest 'no key, no vault' => sub {
  125. no warnings qw{once};
  126. local $Trog::Vault::master = undef;
  127. local $Trog::Vault::looked_further = 1;
  128. ok( !Trog::Vault::has_key(), 'an installation with no key has no vault' );
  129. my ( $ok, $why ) = Trog::Vault::set( 'bob', 'nowhere', 'to put it' );
  130. is( $ok, 0, 'storing is refused' );
  131. like( $why, qr/no[ ]vault[ ]key/, 'saying why, since this is a thing to go and configure' );
  132. is( Trog::Vault::get( 'bob', 'keepass' ), undef, 'and nothing already stored is offered' );
  133. };
  134. subtest 'the other two places a key can be' => sub {
  135. no warnings qw{once};
  136. require Crypt::Misc;
  137. # A key file, for a machine not running systemd. bin/tcms-vault-key --file
  138. # writes exactly this: base64 and a newline.
  139. my $on_disk = Crypt::Misc::encode_b64( Crypt::PRNG::random_bytes(32) );
  140. open( my $fh, '>', 'config/secrets.key' ) or die $!;
  141. print {$fh} "$on_disk\n";
  142. close($fh) or die $!;
  143. chmod( oct('600'), 'config/secrets.key' );
  144. {
  145. local $Trog::Vault::master = undef;
  146. local $Trog::Vault::looked_further = 0;
  147. is( Crypt::Misc::encode_b64( Trog::Vault::key() ), $on_disk, 'a key file is found, newline and all' );
  148. }
  149. # And systemd's credential store, which is where it should be: the directory
  150. # systemd hands over, for a service that is not chrooted away from it.
  151. my $in_store = Crypt::Misc::encode_b64( Crypt::PRNG::random_bytes(32) );
  152. File::Path::make_path('creds');
  153. open( $fh, '>', 'creds/tpsgi-vault' ) or die $!;
  154. print {$fh} $in_store;
  155. close($fh) or die $!;
  156. {
  157. local $ENV{CREDENTIALS_DIRECTORY} = 'creds';
  158. local $Trog::Vault::master = undef;
  159. local $Trog::Vault::looked_further = 0;
  160. is( Crypt::Misc::encode_b64( Trog::Vault::key() ), $in_store, 'the credential store wins over the file beside the database' );
  161. }
  162. # Something that is not a key is not quietly used as one.
  163. open( $fh, '>', 'config/secrets.key' ) or die $!;
  164. print {$fh} "hunter2\n";
  165. close($fh) or die $!;
  166. {
  167. local $Trog::Vault::master = undef;
  168. local $Trog::Vault::looked_further = 0;
  169. is( Trog::Vault::key(), undef, 'a key that is not 32 bytes of base64 is refused' );
  170. }
  171. unlink('config/secrets.key');
  172. };
  173. subtest 'a code is worth one thing' => sub {
  174. my ( $uri, undef, undef, $message, $totp ) = Trog::Auth::totp( 'bob', 'vault.example.com' );
  175. ok( $uri, 'bob is enrolled' ) or diag($message);
  176. my $now = time();
  177. my $code = $totp->expected_totp_code($now);
  178. my ( $ok, $why ) = Trog::Auth::spend_totp( 'bob', $code );
  179. is( $ok, 1, 'the code from their authenticator is accepted' ) or diag($why);
  180. ( $ok, $why ) = Trog::Auth::spend_totp( 'bob', $code );
  181. is( $ok, 0, 'and is not accepted a second time' );
  182. like( $why, qr/already[ ]been[ ]used/, 'saying so, since the answer is to wait thirty seconds' );
  183. # A code from before the one just spent is also spent, whatever the
  184. # arithmetic says: that is what walking the counter forward is for.
  185. my $previous = $totp->expected_totp_code( $now - 30 );
  186. ( $ok, $why ) = Trog::Auth::spend_totp( 'bob', $previous );
  187. is( $ok, 0, 'nor is an older code from inside the tolerance window' );
  188. ( $ok, $why ) = Trog::Auth::spend_totp( 'bob', '000000' );
  189. is( $ok, 0, 'a wrong code is refused' );
  190. ( $ok, $why ) = Trog::Auth::spend_totp( 'bob', 'notacode' );
  191. is( $ok, 0, 'and so is something that is not a code at all' );
  192. ( $ok, $why ) = Trog::Auth::spend_totp( 'eve', $totp->expected_totp_code( $now + 30 ) );
  193. is( $ok, 0, 'somebody who has not enrolled cannot spend anything' );
  194. like( $why, qr/no[ ]second[ ]factor/, 'and is told that rather than that their code was wrong' );
  195. # The next window is a new code and works, which is the whole cost of this.
  196. ( $ok, $why ) = Trog::Auth::spend_totp( 'bob', $totp->expected_totp_code( $now + 30 ) );
  197. is( $ok, 1, 'the next code works' ) or diag($why);
  198. };
  199. subtest 'passwords are argon2id, and become it' => sub {
  200. my $dbh = Trog::SQLite::dbh( 'schema/auth.schema', 'config/auth.db' );
  201. my ($hash) = $dbh->selectrow_array("SELECT hash FROM user WHERE name='bob'");
  202. like( $hash, qr/^\$argon2id\$/, 'a user made today is stored as argon2id' );
  203. ok( Trog::Auth::check_password( 'bob', 'hunter2' ), 'and their password checks out' );
  204. ok( !Trog::Auth::check_password( 'bob', 'hunter3' ), 'while a wrong one does not' );
  205. ok( !Trog::Auth::check_password( 'bob', '' ), 'and neither does nothing at all' );
  206. # A row as it was before this change: one unstretched sha256 of the password
  207. # and the salt beside it.
  208. require Digest::SHA;
  209. $dbh->do( "UPDATE user SET hash=?, salt=? WHERE name=?", undef, Digest::SHA::sha256( 'letmein' . 'oldsalt' ), 'oldsalt', 'eve' );
  210. my ($legacy) = $dbh->selectrow_array("SELECT hash FROM user WHERE name='eve'");
  211. unlike( $legacy, qr/^\$argon2/, 'a row from before this reads as the old kind' );
  212. ok( !Trog::Auth::check_password( 'eve', 'wrong' ), 'which still refuses a wrong password' );
  213. ($legacy) = $dbh->selectrow_array("SELECT hash FROM user WHERE name='eve'");
  214. unlike( $legacy, qr/^\$argon2/, 'and is left alone when it does' );
  215. ok( Trog::Auth::check_password( 'eve', 'letmein' ), 'and accepts the right one' );
  216. my ($upgraded) = $dbh->selectrow_array("SELECT hash FROM user WHERE name='eve'");
  217. like( $upgraded, qr/^\$argon2id\$/, 'rewriting it as argon2id on the way past' );
  218. ok( Trog::Auth::check_password( 'eve', 'letmein' ), 'after which the same password still works' );
  219. # Raising the cost later is a one line change, not a migration, for the same
  220. # reason: the next correct password rewrites the row.
  221. {
  222. no warnings qw{once};
  223. local $Trog::Auth::argon2_time = $Trog::Auth::argon2_time + 1;
  224. ok( Trog::Auth::check_password( 'eve', 'letmein' ), 'a hash made under weaker parameters still verifies' );
  225. my ($rehashed) = $dbh->selectrow_array("SELECT hash FROM user WHERE name='eve'");
  226. isnt( $rehashed, $upgraded, 'and is rewritten under the stronger ones' );
  227. }
  228. };
  229. subtest 'logging in spends a code' => sub {
  230. my ( undef, undef, undef, undef, $totp ) = Trog::Auth::totp( 'bob', 'vault.example.com' );
  231. # The subtest above spent the code for the window we are standing in, and
  232. # the counter only walks forwards. Standing here for thirty seconds would
  233. # say the same thing and cost thirty seconds.
  234. my $dbh = Trog::SQLite::dbh( 'schema/auth.schema', 'config/auth.db' );
  235. $dbh->do("DELETE FROM totp_spent WHERE username='bob'");
  236. my $now = time();
  237. my $code = $totp->expected_totp_code($now);
  238. is( Trog::Auth::mksession( 'bob', 'hunter2', '' ), '', 'an enrolled user cannot log in without a code' );
  239. is( Trog::Auth::mksession( 'bob', 'wrong', $code ), '', 'nor with a wrong password' );
  240. # And a login that failed on the password did not spend the code on the way
  241. # past, or a wrong guess would cost the person their next thirty seconds.
  242. ok( Trog::Auth::mksession( 'bob', 'hunter2', $code ), 'the right password and a live code get a session' );
  243. is( Trog::Auth::mksession( 'bob', 'hunter2', $code ), '', 'and that code cannot be replayed into a second one' );
  244. };
  245. subtest 'when the key is gone' => sub {
  246. no warnings qw{once};
  247. require Trog::Routes::HTML;
  248. my $tpsgi = bless {}, 'FakeTPSGI2';
  249. {
  250. no warnings qw{once};
  251. *FakeTPSGI2::see_also = sub { return [ 303, [ Location => $_[1] ], [''] ] };
  252. }
  253. my $rendered;
  254. my $index = Test::MockModule->new('Trog::Routes::HTML');
  255. $index->redefine( index => sub { $rendered = $_[0]; return [ 200, [], [''] ] } );
  256. Trog::Vault::set( 'bob', 'keepass', 'correct horse battery staple' );
  257. # The machine was rebuilt and the credential went with it. A key lives and
  258. # dies with its machine on purpose, so this is the ordinary case rather than
  259. # a disaster: everything sealed under the old one is gone, and the users
  260. # store theirs again.
  261. foreach my $gone (
  262. [ 'no key at all', sub { $Trog::Vault::master = undef; $Trog::Vault::looked_further = 1 } ],
  263. [ 'a different key', sub { $Trog::Vault::master = Crypt::PRNG::random_bytes(32) } ],
  264. ) {
  265. my ( $what, $break ) = @$gone;
  266. local $Trog::Vault::master = Trog::Vault::key();
  267. local $Trog::Vault::looked_further = 1;
  268. $break->();
  269. # Nothing explodes, and nothing claims a secret is usable.
  270. is( Trog::Vault::has( 'bob', 'keepass' ), 0, "$what: nothing reads as usable" );
  271. is( Trog::Vault::get( 'bob', 'keepass' ), undef, "$what: and nothing opens" );
  272. Trog::Routes::HTML::secrets( { user => 'bob', user_acls => ['admin'], tpsgi => $tpsgi } );
  273. my ($listed) = grep { $_->{name} eq 'keepass' } @{ $rendered->{secrets} };
  274. ok( $listed, "$what: the row is still listed rather than vanishing" );
  275. is( $listed->{readable}, 0, "$what: marked as one that will not open" );
  276. # And a page which knows storing cannot work does not draw the form for
  277. # it -- has_vault is what the template hangs that on.
  278. is( $rendered->{has_vault}, ( $what eq 'no key at all' ? 0 : 1 ), "$what: the page knows whether there is a vault to store into" );
  279. my ( $stored, $why ) = Trog::Vault::set( 'bob', 'replacement', 'a new one' );
  280. if ( $what eq 'no key at all' ) {
  281. is( $stored, 0, "$what: storing is refused rather than silently lost" );
  282. like( $why, qr/no[ ]vault[ ]key/, "$what: saying why" );
  283. }
  284. else {
  285. is( $stored, 1, "$what: a new key stores new secrets fine" );
  286. is( Trog::Vault::get( 'bob', 'replacement' ), 'a new one', "$what: and opens them" );
  287. Trog::Vault::forget( 'bob', 'replacement' );
  288. }
  289. }
  290. # The key came back: what was sealed under it was never damaged, only
  291. # unreadable while it was away.
  292. is( Trog::Vault::get( 'bob', 'keepass' ), 'correct horse battery staple', 'and the original key still opens the original row' );
  293. };
  294. subtest 'the page a user manages them from' => sub {
  295. require Trog::Routes::HTML;
  296. my $tpsgi = bless {}, 'FakeTPSGI';
  297. {
  298. no warnings qw{once};
  299. *FakeTPSGI::see_also = sub { return [ 303, [ Location => $_[1] ], [''] ] };
  300. *FakeTPSGI::forbidden = sub { return [ 403, [], ['no'] ] };
  301. }
  302. no warnings 'once';
  303. my $route = $Trog::Routes::HTML::routes{'/secrets'};
  304. ok( $route, 'the page is a route' );
  305. ok( $route->{auth}, 'behind a login' );
  306. ok( $route->{nocache}, 'and never cached, since it is about who is asking' );
  307. ok( !$route->{totp_exempt}, 'and not somewhere an unenrolled login can get to' );
  308. my $rendered;
  309. my $index = Test::MockModule->new('Trog::Routes::HTML');
  310. $index->redefine( index => sub { $rendered = $_[0]; return [ 200, [], [''] ] } );
  311. Trog::Routes::HTML::secrets( { user => 'bob', user_acls => ['admin'], tpsgi => $tpsgi } );
  312. ok( $rendered->{has_vault}, 'the page knows there is a vault' );
  313. my ($keepass) = grep { $_->{name} eq 'keepass' } @{ $rendered->{secrets} };
  314. ok( $keepass, "bob's own secret is listed" );
  315. ok( !exists $keepass->{ciphertext}, 'without its ciphertext' );
  316. ok( $keepass->{stored}, 'with when it was stored' );
  317. # The username comes off the session, so there is no field to put somebody
  318. # else's in.
  319. Trog::Routes::HTML::secrets( { user => 'eve', user_acls => ['public'], tpsgi => $tpsgi } );
  320. is_deeply( $rendered->{secrets}, [], "and eve sees none of bob's" );
  321. # Storing, and the thing stored not surviving the request that stored it.
  322. my $query = { user => 'eve', tpsgi => $tpsgi, name => 'ssh', secret => 'a passphrase' };
  323. my $res = Trog::Routes::HTML::secrets_save($query);
  324. is( $res->[0], 303, 'saving redirects back to the page' );
  325. ok( !exists $query->{secret}, 'and the secret is gone from the query afterwards' );
  326. is( Trog::Vault::get( 'eve', 'ssh' ), 'a passphrase', 'having been stored' );
  327. $res = Trog::Routes::HTML::secrets_forget( { user => 'eve', tpsgi => $tpsgi, name => 'ssh' } );
  328. is( $res->[0], 303, 'forgetting redirects too' );
  329. is( Trog::Vault::get( 'eve', 'ssh' ), undef, 'and it is gone' );
  330. # One user cannot reach into another's, whatever they post.
  331. Trog::Routes::HTML::secrets_forget( { user => 'eve', tpsgi => $tpsgi, name => 'keepass' } );
  332. is( Trog::Vault::get( 'bob', 'keepass' ), 'correct horse battery staple', "bob's is untouched by eve asking to forget it" );
  333. };
  334. # The handle raises on every error, so these two are the writes whose failure
  335. # must still come back as an answer rather than as a die.
  336. subtest 'a write the database refuses is an answer, not a crash' => sub {
  337. my ( $ok, $why ) = Trog::Vault::set( 'nobody', 'thing', 'a secret for a user who does not exist' );
  338. is( $ok, 0, 'a secret for a user the foreign key does not know is refused' );
  339. is( $why, 'could not store it', 'with the message the page shows' );
  340. my $dbh = Trog::SQLite::dbh( 'schema/auth.schema', 'config/auth.db' );
  341. $dbh->do("DELETE FROM totp_spent WHERE username='bob'");
  342. $dbh->do("CREATE TEMP TRIGGER refuse_spend BEFORE INSERT ON totp_spent BEGIN SELECT RAISE(ABORT, 'refused for the test'); END");
  343. my ( undef, undef, undef, undef, $totp ) = Trog::Auth::totp( 'bob', 'vault.example.com' );
  344. ( $ok, $why ) = Trog::Auth::spend_totp( 'bob', $totp->expected_totp_code( time() ) );
  345. $dbh->do("DROP TRIGGER temp.refuse_spend");
  346. is( $ok, 0, 'a right code that cannot be recorded as spent is refused' );
  347. like( $why, qr/could[ ]not[ ]record[ ]the[ ]code/, 'saying why' );
  348. };
  349. done_testing();