forked from keepassxreboot/keepassxc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TestCli.cpp
2395 lines (2013 loc) · 91.9 KB
/
TestCli.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2020 KeePassXC Team <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 or (at your option)
* version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "TestCli.h"
#include "config-keepassx-tests.h"
#include "core/Bootstrap.h"
#include "core/Config.h"
#include "core/Group.h"
#include "core/Metadata.h"
#include "core/Tools.h"
#include "crypto/Crypto.h"
#include "keys/FileKey.h"
#include "keys/drivers/YubiKey.h"
#include "cli/Add.h"
#include "cli/AddGroup.h"
#include "cli/Analyze.h"
#include "cli/AttachmentExport.h"
#include "cli/AttachmentImport.h"
#include "cli/AttachmentRemove.h"
#include "cli/Clip.h"
#include "cli/DatabaseCreate.h"
#include "cli/DatabaseEdit.h"
#include "cli/DatabaseInfo.h"
#include "cli/Diceware.h"
#include "cli/Edit.h"
#include "cli/Estimate.h"
#include "cli/Export.h"
#include "cli/Generate.h"
#include "cli/Help.h"
#include "cli/Import.h"
#include "cli/List.h"
#include "cli/Merge.h"
#include "cli/Move.h"
#include "cli/Open.h"
#include "cli/Remove.h"
#include "cli/RemoveGroup.h"
#include "cli/Search.h"
#include "cli/Show.h"
#include "cli/Utils.h"
#include <QClipboard>
#include <QSignalSpy>
#include <QTest>
#include <QtConcurrent>
#include <zxcvbn.h>
QTEST_MAIN(TestCli)
void TestCli::initTestCase()
{
QVERIFY(Crypto::init());
Config::createTempFileInstance();
QLocale::setDefault(QLocale::c());
Bootstrap::bootstrap();
m_devNull.reset(new QFile());
#ifdef Q_OS_WIN
m_devNull->open(fopen("nul", "w"), QIODevice::WriteOnly);
#else
m_devNull->open(fopen("/dev/null", "w"), QIODevice::WriteOnly);
#endif
Utils::DEVNULL.setDevice(m_devNull.data());
}
void TestCli::init()
{
const auto file = QString(KEEPASSX_TEST_DATA_DIR).append("/%1");
m_dbFile.reset(new TemporaryFile());
m_dbFile->copyFromFile(file.arg("NewDatabase.kdbx"));
m_dbFile2.reset(new TemporaryFile());
m_dbFile2->copyFromFile(file.arg("NewDatabase2.kdbx"));
m_dbFileMulti.reset(new TemporaryFile());
m_dbFileMulti->copyFromFile(file.arg("NewDatabaseMulti.kdbx"));
m_xmlFile.reset(new TemporaryFile());
m_xmlFile->copyFromFile(file.arg("NewDatabase.xml"));
m_keyFileProtectedDbFile.reset(new TemporaryFile());
m_keyFileProtectedDbFile->copyFromFile(file.arg("KeyFileProtected.kdbx"));
m_keyFileProtectedNoPasswordDbFile.reset(new TemporaryFile());
m_keyFileProtectedNoPasswordDbFile->copyFromFile(file.arg("KeyFileProtectedNoPassword.kdbx"));
m_yubiKeyProtectedDbFile.reset(new TemporaryFile());
m_yubiKeyProtectedDbFile->copyFromFile(file.arg("YubiKeyProtectedPasswords.kdbx"));
m_nonAsciiDbFile.reset(new TemporaryFile());
m_nonAsciiDbFile->copyFromFile(file.arg("NonAscii.kdbx"));
m_stdout.reset(new QBuffer());
m_stdout->open(QIODevice::ReadWrite);
Utils::STDOUT.setDevice(m_stdout.data());
m_stderr.reset(new QBuffer());
m_stderr->open(QIODevice::ReadWrite);
Utils::STDERR.setDevice(m_stderr.data());
m_stdin.reset(new QBuffer());
m_stdin->open(QIODevice::ReadWrite);
Utils::STDIN.setDevice(m_stdin.data());
}
void TestCli::cleanup()
{
m_dbFile.reset();
m_dbFile2.reset();
m_dbFileMulti.reset();
m_keyFileProtectedDbFile.reset();
m_keyFileProtectedNoPasswordDbFile.reset();
m_yubiKeyProtectedDbFile.reset();
Utils::STDOUT.setDevice(nullptr);
Utils::STDERR.setDevice(nullptr);
Utils::STDIN.setDevice(nullptr);
}
void TestCli::cleanupTestCase()
{
m_devNull.reset();
}
QSharedPointer<Database> TestCli::readDatabase(const QString& filename, const QString& pw, const QString& keyfile)
{
auto db = QSharedPointer<Database>::create();
auto key = QSharedPointer<CompositeKey>::create();
if (filename.isEmpty()) {
// Open the default test database
key->addKey(QSharedPointer<PasswordKey>::create("a"));
if (!db->open(m_dbFile->fileName(), key)) {
return {};
}
} else {
// Open the specified database file using supplied credentials
key->addKey(QSharedPointer<PasswordKey>::create(pw));
if (!keyfile.isEmpty()) {
auto filekey = QSharedPointer<FileKey>::create();
filekey->load(keyfile);
key->addKey(filekey);
}
if (!db->open(filename, key)) {
return {};
}
}
return db;
}
int TestCli::execCmd(Command& cmd, const QStringList& args) const
{
// Move to end of stream
m_stdout->readAll();
m_stderr->readAll();
// Record stream position
auto outPos = m_stdout->pos();
auto errPos = m_stderr->pos();
// Execute command
int ret = cmd.execute(args);
// Move back to recorded position
m_stdout->seek(outPos);
m_stderr->seek(errPos);
// Skip over blank lines
QByteArray newline("\n");
while (m_stdout->peek(1) == newline) {
m_stdout->readLine();
}
while (m_stderr->peek(1) == newline) {
m_stderr->readLine();
}
return ret;
}
bool TestCli::isTotp(const QString& value)
{
static const QRegularExpression totp("^\\d{6}$");
return totp.match(value.trimmed()).hasMatch();
}
void TestCli::setInput(const QString& input)
{
setInput(QStringList(input));
}
void TestCli::setInput(const QStringList& input)
{
auto ba = input.join("\n").toLatin1();
// Always end in newline
if (!ba.endsWith("\n")) {
ba.append("\n");
}
auto pos = m_stdin->pos();
m_stdin->write(ba);
m_stdin->seek(pos);
}
void TestCli::testBatchCommands()
{
Commands::setupCommands(false);
QVERIFY(Commands::getCommand("add"));
QVERIFY(Commands::getCommand("analyze"));
QVERIFY(Commands::getCommand("attachment-export"));
QVERIFY(Commands::getCommand("attachment-import"));
QVERIFY(Commands::getCommand("attachment-rm"));
QVERIFY(Commands::getCommand("clip"));
QVERIFY(Commands::getCommand("close"));
QVERIFY(Commands::getCommand("db-create"));
QVERIFY(Commands::getCommand("db-info"));
QVERIFY(Commands::getCommand("diceware"));
QVERIFY(Commands::getCommand("edit"));
QVERIFY(Commands::getCommand("estimate"));
QVERIFY(Commands::getCommand("export"));
QVERIFY(Commands::getCommand("generate"));
QVERIFY(Commands::getCommand("help"));
QVERIFY(Commands::getCommand("import"));
QVERIFY(Commands::getCommand("ls"));
QVERIFY(Commands::getCommand("merge"));
QVERIFY(Commands::getCommand("mkdir"));
QVERIFY(Commands::getCommand("mv"));
QVERIFY(Commands::getCommand("open"));
QVERIFY(Commands::getCommand("rm"));
QVERIFY(Commands::getCommand("rmdir"));
QVERIFY(Commands::getCommand("show"));
QVERIFY(Commands::getCommand("search"));
QVERIFY(!Commands::getCommand("doesnotexist"));
QCOMPARE(Commands::getCommands().size(), 26);
}
void TestCli::testInteractiveCommands()
{
Commands::setupCommands(true);
QVERIFY(Commands::getCommand("add"));
QVERIFY(Commands::getCommand("analyze"));
QVERIFY(Commands::getCommand("attachment-export"));
QVERIFY(Commands::getCommand("attachment-import"));
QVERIFY(Commands::getCommand("attachment-rm"));
QVERIFY(Commands::getCommand("clip"));
QVERIFY(Commands::getCommand("close"));
QVERIFY(Commands::getCommand("db-create"));
QVERIFY(Commands::getCommand("db-info"));
QVERIFY(Commands::getCommand("diceware"));
QVERIFY(Commands::getCommand("edit"));
QVERIFY(Commands::getCommand("estimate"));
QVERIFY(Commands::getCommand("exit"));
QVERIFY(Commands::getCommand("generate"));
QVERIFY(Commands::getCommand("help"));
QVERIFY(Commands::getCommand("ls"));
QVERIFY(Commands::getCommand("merge"));
QVERIFY(Commands::getCommand("mkdir"));
QVERIFY(Commands::getCommand("mv"));
QVERIFY(Commands::getCommand("open"));
QVERIFY(Commands::getCommand("quit"));
QVERIFY(Commands::getCommand("rm"));
QVERIFY(Commands::getCommand("rmdir"));
QVERIFY(Commands::getCommand("show"));
QVERIFY(Commands::getCommand("search"));
QVERIFY(!Commands::getCommand("doesnotexist"));
QCOMPARE(Commands::getCommands().size(), 26);
}
void TestCli::testAdd()
{
Add addCmd;
QVERIFY(!addCmd.name.isEmpty());
QVERIFY(addCmd.getDescriptionLine().contains(addCmd.name));
setInput("a");
execCmd(addCmd,
{"add",
"-u",
"newuser",
"--url",
"https://example.com/",
"-g",
"-L",
"20",
"--notes",
"some notes",
m_dbFile->fileName(),
"/newuser-entry"});
m_stderr->readLine(); // Skip password prompt
QCOMPARE(m_stderr->readAll(), QByteArray());
QVERIFY(m_stdout->readAll().contains("Successfully added entry newuser-entry."));
auto db = readDatabase();
auto* entry = db->rootGroup()->findEntryByPath("/newuser-entry");
QVERIFY(entry);
QCOMPARE(entry->username(), QString("newuser"));
QCOMPARE(entry->url(), QString("https://example.com/"));
QCOMPARE(entry->password().size(), 20);
QCOMPARE(entry->notes(), QString("some notes"));
// Quiet option
setInput("a");
execCmd(addCmd, {"add", "-q", "-u", "newuser", "-g", "-L", "20", m_dbFile->fileName(), "/newentry-quiet"});
QCOMPARE(m_stderr->readAll(), QByteArray());
QCOMPARE(m_stdout->readAll(), QByteArray());
db = readDatabase();
entry = db->rootGroup()->findEntryByPath("/newentry-quiet");
QVERIFY(entry);
QCOMPARE(entry->password().size(), 20);
setInput({"a", "newpassword"});
execCmd(addCmd,
{"add", "-u", "newuser2", "--url", "https://example.net/", "-p", m_dbFile->fileName(), "/newuser-entry2"});
QVERIFY(m_stdout->readAll().contains("Successfully added entry newuser-entry2."));
db = readDatabase();
entry = db->rootGroup()->findEntryByPath("/newuser-entry2");
QVERIFY(entry);
QCOMPARE(entry->username(), QString("newuser2"));
QCOMPARE(entry->url(), QString("https://example.net/"));
QCOMPARE(entry->password(), QString("newpassword"));
// Password generation options
setInput("a");
execCmd(addCmd, {"add", "-u", "newuser3", "-g", "-L", "34", m_dbFile->fileName(), "/newuser-entry3"});
QVERIFY(m_stdout->readAll().contains("Successfully added entry newuser-entry3."));
db = readDatabase();
entry = db->rootGroup()->findEntryByPath("/newuser-entry3");
QVERIFY(entry);
QCOMPARE(entry->username(), QString("newuser3"));
QCOMPARE(entry->password().size(), 34);
QRegularExpression defaultPasswordClassesRegex("^[a-zA-Z0-9]+$");
QVERIFY(defaultPasswordClassesRegex.match(entry->password()).hasMatch());
setInput("a");
execCmd(addCmd,
{"add",
"-u",
"newuser4",
"-g",
"-L",
"20",
"--every-group",
"-s",
"-n",
"-U",
"-l",
m_dbFile->fileName(),
"/newuser-entry4"});
QVERIFY(m_stdout->readAll().contains("Successfully added entry newuser-entry4."));
db = readDatabase();
entry = db->rootGroup()->findEntryByPath("/newuser-entry4");
QVERIFY(entry);
QCOMPARE(entry->username(), QString("newuser4"));
QCOMPARE(entry->password().size(), 20);
QVERIFY(!defaultPasswordClassesRegex.match(entry->password()).hasMatch());
setInput("a");
execCmd(addCmd, {"add", "-u", "newuser5", "--notes", "test\\nnew line", m_dbFile->fileName(), "/newuser-entry5"});
m_stderr->readLine(); // skip password prompt
QCOMPARE(m_stderr->readAll(), QByteArray(""));
QCOMPARE(m_stdout->readAll(), QByteArray("Successfully added entry newuser-entry5.\n"));
db = readDatabase();
entry = db->rootGroup()->findEntryByPath("/newuser-entry5");
QVERIFY(entry);
QCOMPARE(entry->username(), QString("newuser5"));
QCOMPARE(entry->notes(), QString("test\nnew line"));
}
void TestCli::testAddGroup()
{
AddGroup addGroupCmd;
QVERIFY(!addGroupCmd.name.isEmpty());
QVERIFY(addGroupCmd.getDescriptionLine().contains(addGroupCmd.name));
setInput("a");
execCmd(addGroupCmd, {"mkdir", m_dbFile->fileName(), "/new_group"});
m_stderr->readLine(); // Skip password prompt
QCOMPARE(m_stderr->readAll(), QByteArray());
QCOMPARE(m_stdout->readAll(), QByteArray("Successfully added group new_group.\n"));
auto db = readDatabase();
auto* group = db->rootGroup()->findGroupByPath("new_group");
QVERIFY(group);
QCOMPARE(group->name(), QString("new_group"));
// Trying to add the same group should fail.
setInput("a");
execCmd(addGroupCmd, {"mkdir", m_dbFile->fileName(), "/new_group"});
QVERIFY(m_stderr->readAll().contains("Group /new_group already exists!"));
QCOMPARE(m_stdout->readAll(), QByteArray());
// Should be able to add groups down the tree.
setInput("a");
execCmd(addGroupCmd, {"mkdir", m_dbFile->fileName(), "/new_group/newer_group"});
QVERIFY(m_stdout->readAll().contains("Successfully added group newer_group."));
db = readDatabase();
group = db->rootGroup()->findGroupByPath("new_group/newer_group");
QVERIFY(group);
QCOMPARE(group->name(), QString("newer_group"));
// Should fail if the path is invalid.
setInput("a");
execCmd(addGroupCmd, {"mkdir", m_dbFile->fileName(), "/invalid_group/newer_group"});
QVERIFY(m_stderr->readAll().contains("Group /invalid_group not found."));
QCOMPARE(m_stdout->readAll(), QByteArray());
// Should fail to add the root group.
setInput("a");
execCmd(addGroupCmd, {"mkdir", m_dbFile->fileName(), "/"});
QVERIFY(m_stderr->readAll().contains("Group / already exists!"));
QCOMPARE(m_stdout->readAll(), QByteArray());
}
void TestCli::testAnalyze()
{
Analyze analyzeCmd;
QVERIFY(!analyzeCmd.name.isEmpty());
QVERIFY(analyzeCmd.getDescriptionLine().contains(analyzeCmd.name));
const QString hibpPath = QString(KEEPASSX_TEST_DATA_DIR).append("/hibp.txt");
setInput("a");
execCmd(analyzeCmd, {"analyze", "--hibp", hibpPath, m_dbFile->fileName()});
auto output = m_stdout->readAll();
QVERIFY(output.contains("Sample Entry"));
QVERIFY(output.contains("123"));
m_stderr->readLine(); // Skip password prompt
QCOMPARE(m_stderr->readAll(), QByteArray());
}
void TestCli::testAttachmentExport()
{
AttachmentExport attachmentExportCmd;
QVERIFY(!attachmentExportCmd.name.isEmpty());
QVERIFY(attachmentExportCmd.getDescriptionLine().contains(attachmentExportCmd.name));
TemporaryFile exportOutput;
exportOutput.open(QIODevice::WriteOnly);
exportOutput.close();
// Try exporting an attachment of a non-existent entry
setInput("a");
execCmd(attachmentExportCmd,
{"attachment-export",
m_dbFile->fileName(),
"invalid_entry_path",
"invalid_attachment_name",
exportOutput.fileName()});
m_stderr->readLine(); // skip password prompt
QCOMPARE(m_stderr->readAll(), QByteArray("Could not find entry with path invalid_entry_path.\n"));
QCOMPARE(m_stdout->readAll(), QByteArray());
// Try exporting a non-existent attachment
setInput("a");
execCmd(attachmentExportCmd,
{"attachment-export",
m_dbFile->fileName(),
"/Sample Entry",
"invalid_attachment_name",
exportOutput.fileName()});
m_stderr->readLine(); // skip password prompt
QCOMPARE(m_stderr->readAll(), QByteArray("Could not find attachment with name invalid_attachment_name.\n"));
QCOMPARE(m_stdout->readAll(), QByteArray());
// Export an existing attachment to a file
setInput("a");
execCmd(
attachmentExportCmd,
{"attachment-export", m_dbFile->fileName(), "/Sample Entry", "Sample attachment.txt", exportOutput.fileName()});
m_stderr->readLine(); // skip password prompt
QCOMPARE(m_stderr->readAll(), QByteArray());
QCOMPARE(m_stdout->readAll(),
QByteArray(qPrintable(QString("Successfully exported attachment %1 of entry %2 to %3.\n")
.arg("Sample attachment.txt", "/Sample Entry", exportOutput.fileName()))));
exportOutput.open(QIODevice::ReadOnly);
QCOMPARE(exportOutput.readAll(), QByteArray("Sample content\n"));
// Export an existing attachment to stdout
setInput("a");
execCmd(attachmentExportCmd,
{"attachment-export", "--stdout", m_dbFile->fileName(), "/Sample Entry", "Sample attachment.txt"});
m_stderr->readLine(); // skip password prompt
QCOMPARE(m_stderr->readAll(), QByteArray());
QCOMPARE(m_stdout->readAll(), QByteArray("Sample content\n"));
// Ensure --stdout works even in quiet mode
setInput("a");
execCmd(
attachmentExportCmd,
{"attachment-export", "--quiet", "--stdout", m_dbFile->fileName(), "/Sample Entry", "Sample attachment.txt"});
m_stderr->readLine(); // skip password prompt
QCOMPARE(m_stderr->readAll(), QByteArray());
QCOMPARE(m_stdout->readAll(), QByteArray("Sample content\n"));
}
void TestCli::testAttachmentImport()
{
AttachmentImport attachmentImportCmd;
QVERIFY(!attachmentImportCmd.name.isEmpty());
QVERIFY(attachmentImportCmd.getDescriptionLine().contains(attachmentImportCmd.name));
const QString attachmentPath = QString(KEEPASSX_TEST_DATA_DIR).append("/Attachment.txt");
QVERIFY(QFile::exists(attachmentPath));
// Try importing an attachment to a non-existent entry
setInput("a");
execCmd(attachmentImportCmd,
{"attachment-import",
m_dbFile->fileName(),
"invalid_entry_path",
"invalid_attachment_name",
"invalid_attachment_path"});
m_stderr->readLine(); // skip password prompt
QCOMPARE(m_stderr->readAll(), QByteArray("Could not find entry with path invalid_entry_path.\n"));
QCOMPARE(m_stdout->readAll(), QByteArray());
// Try importing an attachment with an occupied name without -f option
setInput("a");
execCmd(attachmentImportCmd,
{"attachment-import",
m_dbFile->fileName(),
"/Sample Entry",
"Sample attachment.txt",
"invalid_attachment_path"});
m_stderr->readLine(); // skip password prompt
QCOMPARE(m_stderr->readAll(),
QByteArray("Attachment Sample attachment.txt already exists for entry /Sample Entry.\n"));
QCOMPARE(m_stdout->readAll(), QByteArray());
// Try importing a non-existent attachment
setInput("a");
execCmd(attachmentImportCmd,
{"attachment-import",
m_dbFile->fileName(),
"/Sample Entry",
"Sample attachment 2.txt",
"invalid_attachment_path"});
m_stderr->readLine(); // skip password prompt
QCOMPARE(m_stderr->readAll(), QByteArray("Could not open attachment file invalid_attachment_path.\n"));
QCOMPARE(m_stdout->readAll(), QByteArray());
// Try importing an attachment with an occupied name with -f option
setInput("a");
execCmd(
attachmentImportCmd,
{"attachment-import", "-f", m_dbFile->fileName(), "/Sample Entry", "Sample attachment.txt", attachmentPath});
m_stderr->readLine(); // skip password prompt
QCOMPARE(m_stderr->readAll(), QByteArray());
QCOMPARE(m_stdout->readAll(),
QByteArray(qPrintable(
QString("Successfully imported attachment %1 as Sample attachment.txt to entry /Sample Entry.\n")
.arg(attachmentPath))));
// Try importing an attachment with an unoccupied name
setInput("a");
execCmd(attachmentImportCmd,
{"attachment-import", m_dbFile->fileName(), "/Sample Entry", "Attachment.txt", attachmentPath});
m_stderr->readLine(); // skip password prompt
QCOMPARE(m_stderr->readAll(), QByteArray());
QCOMPARE(
m_stdout->readAll(),
QByteArray(qPrintable(QString("Successfully imported attachment %1 as Attachment.txt to entry /Sample Entry.\n")
.arg(attachmentPath))));
}
void TestCli::testAttachmentRemove()
{
AttachmentRemove attachmentRemoveCmd;
QVERIFY(!attachmentRemoveCmd.name.isEmpty());
QVERIFY(attachmentRemoveCmd.getDescriptionLine().contains(attachmentRemoveCmd.name));
// Try deleting an attachment belonging to an non-existent entry
setInput("a");
execCmd(attachmentRemoveCmd,
{"attachment-rm", m_dbFile->fileName(), "invalid_entry_path", "invalid_attachment_name"});
m_stderr->readLine(); // skip password prompt
QCOMPARE(m_stderr->readAll(), QByteArray("Could not find entry with path invalid_entry_path.\n"));
QCOMPARE(m_stdout->readAll(), QByteArray());
// Try deleting a non-existent attachment from an entry
setInput("a");
execCmd(attachmentRemoveCmd, {"attachment-rm", m_dbFile->fileName(), "/Sample Entry", "invalid_attachment_name"});
m_stderr->readLine(); // skip password prompt
QCOMPARE(m_stderr->readAll(), QByteArray("Could not find attachment with name invalid_attachment_name.\n"));
QCOMPARE(m_stdout->readAll(), QByteArray());
// Finally delete an existing attachment from an existing entry
auto db = readDatabase();
QVERIFY(db);
const Entry* entry = db->rootGroup()->findEntryByPath("/Sample Entry");
QVERIFY(entry);
QVERIFY(entry->attachments()->hasKey("Sample attachment.txt"));
setInput("a");
execCmd(attachmentRemoveCmd, {"attachment-rm", m_dbFile->fileName(), "/Sample Entry", "Sample attachment.txt"});
m_stderr->readLine(); // skip password prompt
QCOMPARE(m_stderr->readAll(), QByteArray());
QCOMPARE(m_stdout->readAll(),
QByteArray("Successfully removed attachment Sample attachment.txt from entry /Sample Entry.\n"));
db = readDatabase();
QVERIFY(db);
QVERIFY(!db->rootGroup()->findEntryByPath("/Sample Entry")->attachments()->hasKey("Sample attachment.txt"));
}
void TestCli::testClip()
{
if (QProcessEnvironment::systemEnvironment().contains("WAYLAND_DISPLAY")) {
QSKIP("Clip test skipped due to QClipboard and Wayland issues on Linux");
}
QClipboard* clipboard = QGuiApplication::clipboard();
clipboard->clear();
Clip clipCmd;
QVERIFY(!clipCmd.name.isEmpty());
QVERIFY(clipCmd.getDescriptionLine().contains(clipCmd.name));
// Password
setInput("a");
execCmd(clipCmd, {"clip", m_dbFile->fileName(), "/Sample Entry", "0"});
QString errorOutput(m_stderr->readAll());
if (errorOutput.contains("Unable to start program")
|| errorOutput.contains("No program defined for clipboard manipulation")) {
QSKIP("Clip test skipped due to missing clipboard tool");
}
QVERIFY(!errorOutput.contains("All clipping programs failed"));
m_stderr->readLine(); // Skip password prompt
QCOMPARE(m_stderr->readAll(), QByteArray());
QTRY_COMPARE(clipboard->text(), QString("Password"));
QCOMPARE(m_stdout->readLine(), QByteArray("Entry's \"Password\" attribute copied to the clipboard!\n"));
// Quiet option
setInput("a");
execCmd(clipCmd, {"clip", m_dbFile->fileName(), "/Sample Entry", "0", "-q"});
QCOMPARE(m_stderr->readAll(), QByteArray());
QCOMPARE(m_stdout->readAll(), QByteArray());
QTRY_COMPARE(clipboard->text(), QString("Password"));
// Username
setInput("a");
execCmd(clipCmd, {"clip", m_dbFile->fileName(), "/Sample Entry", "0", "-a", "username"});
QTRY_COMPARE(clipboard->text(), QString("User Name"));
// Uuid (top-level field)
setInput("a");
execCmd(clipCmd, {"clip", m_dbFile->fileName(), "/Sample Entry", "0", "-a", "Uuid"});
QTRY_COMPARE(clipboard->text(), QString("{9f4544c2-ab00-c74a-8a1a-6eaf26cf57e9}"));
// TOTP
setInput("a");
execCmd(clipCmd, {"clip", m_dbFile->fileName(), "/Sample Entry", "0", "--totp"});
QTRY_VERIFY(isTotp(clipboard->text()));
QCOMPARE(m_stdout->readLine(), QByteArray("Entry's \"totp\" attribute copied to the clipboard!\n"));
// Test Unicode
setInput("a");
execCmd(clipCmd, {"clip", m_dbFile2->fileName(), "/General/Unicode", "0", "-a", "username"});
QTRY_COMPARE(clipboard->text(), QString(R"(¯\_(ツ)_/¯)"));
// Password with timeout
setInput("a");
// clang-format off
QFuture<void> future = QtConcurrent::run(&clipCmd,
static_cast<int(Clip::*)(const QStringList&)>(&DatabaseCommand::execute),
QStringList{"clip", m_dbFile->fileName(), "/Sample Entry", "1"});
// clang-format on
QTRY_COMPARE(clipboard->text(), QString("Password"));
QTRY_COMPARE_WITH_TIMEOUT(clipboard->text(), QString(""), 3000);
future.waitForFinished();
// TOTP with timeout
setInput("a");
future = QtConcurrent::run(&clipCmd,
static_cast<int (Clip::*)(const QStringList&)>(&DatabaseCommand::execute),
QStringList{"clip", m_dbFile->fileName(), "/Sample Entry", "1", "-t"});
QTRY_VERIFY(isTotp(clipboard->text()));
QTRY_COMPARE_WITH_TIMEOUT(clipboard->text(), QString(""), 3000);
future.waitForFinished();
setInput("a");
execCmd(clipCmd, {"clip", m_dbFile->fileName(), "--totp", "/Sample Entry", "bleuh"});
QVERIFY(m_stderr->readAll().contains("Invalid timeout value bleuh.\n"));
setInput("a");
execCmd(clipCmd, {"clip", m_dbFile2->fileName(), "--totp", "/Sample Entry", "0"});
QVERIFY(m_stderr->readAll().contains("Entry with path /Sample Entry has no TOTP set up.\n"));
setInput("a");
execCmd(clipCmd, {"clip", m_dbFile->fileName(), "-a", "TESTAttribute1", "/Sample Entry", "0"});
QVERIFY(m_stderr->readAll().contains("ERROR: attribute TESTAttribute1 is ambiguous"));
setInput("a");
execCmd(clipCmd, {"clip", m_dbFile2->fileName(), "--attribute", "Username", "--totp", "/Sample Entry", "0"});
QVERIFY(m_stderr->readAll().contains("ERROR: Please specify one of --attribute or --totp, not both.\n"));
// Best option
setInput("a");
execCmd(clipCmd, {"clip", m_dbFileMulti->fileName(), "Multi", "0", "-b"});
QByteArray errorChoices = m_stderr->readAll();
QVERIFY(errorChoices.contains("Multi Entry 1"));
QVERIFY(errorChoices.contains("Multi Entry 2"));
setInput("a");
execCmd(clipCmd, {"clip", m_dbFileMulti->fileName(), "Entry 2", "0", "-b"});
QTRY_COMPARE(clipboard->text(), QString("Password2"));
}
void TestCli::testCreate()
{
DatabaseCreate createCmd;
QVERIFY(!createCmd.name.isEmpty());
QVERIFY(createCmd.getDescriptionLine().contains(createCmd.name));
QScopedPointer<QTemporaryDir> testDir(new QTemporaryDir());
QString dbFilename;
// Testing password option, password mismatch
dbFilename = testDir->path() + "/testCreate_pw.kdbx";
setInput({"a", "b"});
execCmd(createCmd, {"db-create", dbFilename, "-p"});
QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
QCOMPARE(m_stderr->readLine(), QByteArray("Repeat password: \n"));
QCOMPARE(m_stderr->readLine(), QByteArray("Error: Passwords do not match.\n"));
QCOMPARE(m_stderr->readLine(), QByteArray("Failed to set database password.\n"));
// Testing password option
setInput({"a", "a"});
execCmd(createCmd, {"db-create", dbFilename, "-p"});
QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
QCOMPARE(m_stderr->readLine(), QByteArray("Repeat password: \n"));
QCOMPARE(m_stdout->readLine(), QByteArray("Successfully created new database.\n"));
auto db = readDatabase(dbFilename, "a");
QVERIFY(db);
// Testing with empty password (deny it)
dbFilename = testDir->path() + "/testCreate_blankpw.kdbx";
setInput({"", "n"});
execCmd(createCmd, {"db-create", dbFilename, "-p"});
QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
QVERIFY(m_stderr->readLine().contains("empty password"));
QCOMPARE(m_stderr->readLine(), QByteArray("Failed to set database password.\n"));
// Testing with empty password (accept it)
setInput({"", "y"});
execCmd(createCmd, {"db-create", dbFilename, "-p"});
QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
QVERIFY(m_stderr->readLine().contains("empty password"));
QCOMPARE(m_stdout->readLine(), QByteArray("Successfully created new database.\n"));
db = readDatabase(dbFilename, "");
QVERIFY(db);
// Should refuse to create the database if it already exists.
execCmd(createCmd, {"db-create", dbFilename, "-p"});
// Output should be empty when there is an error.
QCOMPARE(m_stdout->readAll(), QByteArray());
QString errorMessage = QString("File " + dbFilename + " already exists.\n");
QCOMPARE(m_stderr->readAll(), errorMessage.toUtf8());
// Should refuse to create without any key provided.
dbFilename = testDir->path() + "/testCreate_key.kdbx";
execCmd(createCmd, {"db-create", dbFilename});
QCOMPARE(m_stdout->readAll(), QByteArray());
QCOMPARE(m_stderr->readLine(), QByteArray("No key is set. Aborting database creation.\n"));
// Testing with keyfile creation
dbFilename = testDir->path() + "/testCreate_key2.kdbx";
QString keyfilePath = testDir->path() + "/keyfile.txt";
setInput({"a", "a"});
execCmd(createCmd, {"db-create", dbFilename, "-p", "-k", keyfilePath});
QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
QCOMPARE(m_stderr->readLine(), QByteArray("Repeat password: \n"));
QCOMPARE(m_stdout->readLine(), QByteArray("Successfully created new database.\n"));
db = readDatabase(dbFilename, "a", keyfilePath);
QVERIFY(db);
// Testing with existing keyfile
dbFilename = testDir->path() + "/testCreate_key3.kdbx";
setInput({"a", "a"});
execCmd(createCmd, {"db-create", dbFilename, "-p", "-k", keyfilePath});
QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
QCOMPARE(m_stderr->readLine(), QByteArray("Repeat password: \n"));
QCOMPARE(m_stdout->readLine(), QByteArray("Successfully created new database.\n"));
db = readDatabase(dbFilename, "a", keyfilePath);
QVERIFY(db);
// Invalid decryption time (format).
dbFilename = testDir->path() + "/testCreate_time.kdbx";
execCmd(createCmd, {"db-create", dbFilename, "-p", "-t", "NAN"});
QCOMPARE(m_stdout->readAll(), QByteArray());
QCOMPARE(m_stderr->readAll(), QByteArray("Invalid decryption time NAN.\n"));
// Invalid decryption time (range).
execCmd(createCmd, {"db-create", dbFilename, "-p", "-t", "10"});
QCOMPARE(m_stdout->readAll(), QByteArray());
QVERIFY(m_stderr->readAll().contains(QByteArray("Target decryption time must be between")));
int encryptionTime = 500;
// Custom encryption time
setInput({"a", "a"});
int epochBefore = QDateTime::currentMSecsSinceEpoch();
execCmd(createCmd, {"db-create", dbFilename, "-p", "-t", QString::number(encryptionTime)});
// Removing 100ms to make sure we account for changes in computation time.
QVERIFY(QDateTime::currentMSecsSinceEpoch() > (epochBefore + encryptionTime - 100));
QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
QCOMPARE(m_stderr->readLine(), QByteArray("Repeat password: \n"));
QCOMPARE(m_stdout->readLine(), QByteArray("Benchmarking key derivation function for 500ms delay.\n"));
QVERIFY(m_stdout->readLine().contains(QByteArray("rounds for key derivation function.\n")));
db = readDatabase(dbFilename, "a");
QVERIFY(db);
}
void TestCli::testDatabaseEdit()
{
TemporaryFile firstKeyFile;
firstKeyFile.open();
firstKeyFile.write(QString("keyFilePassword").toLatin1());
firstKeyFile.close();
TemporaryFile secondKeyFile;
secondKeyFile.open();
secondKeyFile.write(QString("newKeyFilePassword").toLatin1());
secondKeyFile.close();
QScopedPointer<QTemporaryDir> testDir(new QTemporaryDir());
DatabaseCreate createCmd;
DatabaseEdit editCmd;
QVERIFY(!editCmd.name.isEmpty());
QVERIFY(editCmd.getDescriptionLine().contains(editCmd.name));
QString dbFilename;
dbFilename = testDir->path() + "/testDatabaseEdit.kdbx";
// Creating a database for testing
setInput({"a", "a"});
execCmd(createCmd, {"db-create", dbFilename, "-p"});
QCOMPARE(m_stdout->readLine(), QByteArray("Successfully created new database.\n"));
// Sanity check.
auto db = readDatabase(dbFilename, "a");
QVERIFY(!db.isNull());
setInput("a");
execCmd(editCmd, {"db-edit", dbFilename, "-p", "--unset-password"});
QCOMPARE(m_stdout->readAll(), QByteArray(""));
m_stderr->readLine();
QCOMPARE(m_stderr->readAll(), QByteArray("Cannot use p and unset-password at the same time.\n"));
setInput("a");
execCmd(editCmd, {"db-edit", dbFilename, "--set-key-file", "/key/file/path", "--unset-key-file"});
QCOMPARE(m_stdout->readAll(), QByteArray(""));
// Skipping the password prompt.
m_stderr->readLine();
QCOMPARE(m_stderr->readAll(), QByteArray("Cannot use set-key-file and unset-key-file at the same time.\n"));
// Sanity check.
db = readDatabase(dbFilename, "a");
QVERIFY(!db.isNull());
setInput({"a", "b", "b"});
execCmd(editCmd, {"db-edit", dbFilename, "-p"});
QCOMPARE(m_stdout->readAll(), QByteArray("Successfully edited the database.\n"));
// Sanity check
db = readDatabase(dbFilename, "b");
QVERIFY(!db.isNull());
setInput("b");
execCmd(editCmd, {"db-edit", dbFilename, "--set-key-file", firstKeyFile.fileName()});
// Skipping the password prompt.
m_stderr->readLine();
QCOMPARE(m_stderr->readAll(), QByteArray(""));
QCOMPARE(m_stdout->readAll(), QByteArray("Successfully edited the database.\n"));
// Sanity check
db = readDatabase(dbFilename, "b");
QVERIFY(db.isNull());
db = readDatabase(dbFilename, "b", firstKeyFile.fileName());
QVERIFY(!db.isNull());
setInput("b");
execCmd(editCmd,
{"db-edit", dbFilename, "-k", firstKeyFile.fileName(), "--set-key-file", secondKeyFile.fileName()});
QCOMPARE(m_stdout->readAll(), QByteArray("Successfully edited the database.\n"));
// Sanity check
db = readDatabase(dbFilename, "b", firstKeyFile.fileName());
QVERIFY(db.isNull());
db = readDatabase(dbFilename, "b", secondKeyFile.fileName());
QVERIFY(!db.isNull());
setInput("b");
execCmd(editCmd, {"db-edit", dbFilename, "-k", secondKeyFile.fileName(), "--unset-password"});
// Skipping the password prompt.
m_stderr->readLine();
QCOMPARE(m_stderr->readAll(), QByteArray(""));
QCOMPARE(m_stdout->readAll(), QByteArray("Successfully edited the database.\n"));
execCmd(editCmd,
{"db-edit",
dbFilename,
"--no-password",
"-k",
secondKeyFile.fileName(),
"--set-key-file",
firstKeyFile.fileName()});
// Skipping the password prompt.
m_stderr->readLine();
QCOMPARE(m_stderr->readAll(), QByteArray(""));
QCOMPARE(m_stdout->readAll(), QByteArray("Successfully edited the database.\n"));
setInput({"b", "b"});
execCmd(editCmd, {"db-edit", dbFilename, "-k", firstKeyFile.fileName(), "--no-password", "--set-password"});
// Skipping over the password setting prompts.
m_stderr->readLine();
m_stderr->readLine();
QCOMPARE(m_stderr->readAll(), QByteArray(""));
QCOMPARE(m_stdout->readAll(), QByteArray("Successfully edited the database.\n"));
setInput("b");
execCmd(editCmd, {"db-edit", dbFilename, "-k", firstKeyFile.fileName(), "--unset-key-file"});
// Skipping the password prompt.
m_stderr->readLine();
QCOMPARE(m_stderr->readAll(), QByteArray(""));
QCOMPARE(m_stdout->readAll(), QByteArray("Successfully edited the database.\n"));
// Sanity check
db = readDatabase(dbFilename, "b", firstKeyFile.fileName());
QVERIFY(db.isNull());
db = readDatabase(dbFilename, "b");
QVERIFY(!db.isNull());
// Trying to remove the key file when there is none set should
// raise an error.
setInput("b");
execCmd(editCmd, {"db-edit", dbFilename, "-p", "--unset-key-file"});
QCOMPARE(m_stdout->readAll(), QByteArray(""));
m_stderr->readLine();
QCOMPARE(m_stderr->readLine(), QByteArray("Cannot remove file key: The database does not have a file key.\n"));
QCOMPARE(m_stderr->readLine(), QByteArray("Could not change the database key.\n"));
setInput("b");
execCmd(editCmd, {"db-edit", dbFilename, "--unset-password"});
QCOMPARE(m_stdout->readAll(), QByteArray(""));
// Skipping the password prompt.
m_stderr->readLine();
QCOMPARE(m_stderr->readLine(), QByteArray("Cannot remove all the keys from a database.\n"));
}
void TestCli::testInfo()
{
DatabaseInfo infoCmd;
QVERIFY(!infoCmd.name.isEmpty());
QVERIFY(infoCmd.getDescriptionLine().contains(infoCmd.name));