TestCli.cpp 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396
  1. /*
  2. * Copyright (C) 2020 KeePassXC Team <team@keepassxc.org>
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 2 or (at your option)
  7. * version 3 of the License.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include "TestCli.h"
  18. #include "config-keepassx-tests.h"
  19. #include "core/Bootstrap.h"
  20. #include "core/Config.h"
  21. #include "core/Group.h"
  22. #include "core/Metadata.h"
  23. #include "core/Tools.h"
  24. #include "crypto/Crypto.h"
  25. #include "keys/FileKey.h"
  26. #include "keys/drivers/YubiKey.h"
  27. #include "cli/Add.h"
  28. #include "cli/AddGroup.h"
  29. #include "cli/Analyze.h"
  30. #include "cli/AttachmentExport.h"
  31. #include "cli/AttachmentImport.h"
  32. #include "cli/AttachmentRemove.h"
  33. #include "cli/Clip.h"
  34. #include "cli/DatabaseCreate.h"
  35. #include "cli/DatabaseEdit.h"
  36. #include "cli/DatabaseInfo.h"
  37. #include "cli/Diceware.h"
  38. #include "cli/Edit.h"
  39. #include "cli/Estimate.h"
  40. #include "cli/Export.h"
  41. #include "cli/Generate.h"
  42. #include "cli/Help.h"
  43. #include "cli/Import.h"
  44. #include "cli/List.h"
  45. #include "cli/Merge.h"
  46. #include "cli/Move.h"
  47. #include "cli/Open.h"
  48. #include "cli/Remove.h"
  49. #include "cli/RemoveGroup.h"
  50. #include "cli/Search.h"
  51. #include "cli/Show.h"
  52. #include "cli/Utils.h"
  53. #include <QClipboard>
  54. #include <QSignalSpy>
  55. #include <QTest>
  56. #include <QtConcurrent>
  57. #include <zxcvbn.h>
  58. QTEST_MAIN(TestCli)
  59. void TestCli::initTestCase()
  60. {
  61. QVERIFY(Crypto::init());
  62. Config::createTempFileInstance();
  63. QLocale::setDefault(QLocale::c());
  64. Bootstrap::bootstrap();
  65. m_devNull.reset(new QFile());
  66. #ifdef Q_OS_WIN
  67. m_devNull->open(fopen("nul", "w"), QIODevice::WriteOnly);
  68. #else
  69. m_devNull->open(fopen("/dev/null", "w"), QIODevice::WriteOnly);
  70. #endif
  71. Utils::DEVNULL.setDevice(m_devNull.data());
  72. }
  73. void TestCli::init()
  74. {
  75. const auto file = QString(KEEPASSX_TEST_DATA_DIR).append("/%1");
  76. m_dbFile.reset(new TemporaryFile());
  77. m_dbFile->copyFromFile(file.arg("NewDatabase.kdbx"));
  78. m_dbFile2.reset(new TemporaryFile());
  79. m_dbFile2->copyFromFile(file.arg("NewDatabase2.kdbx"));
  80. m_dbFileMulti.reset(new TemporaryFile());
  81. m_dbFileMulti->copyFromFile(file.arg("NewDatabaseMulti.kdbx"));
  82. m_xmlFile.reset(new TemporaryFile());
  83. m_xmlFile->copyFromFile(file.arg("NewDatabase.xml"));
  84. m_keyFileProtectedDbFile.reset(new TemporaryFile());
  85. m_keyFileProtectedDbFile->copyFromFile(file.arg("KeyFileProtected.kdbx"));
  86. m_keyFileProtectedNoPasswordDbFile.reset(new TemporaryFile());
  87. m_keyFileProtectedNoPasswordDbFile->copyFromFile(file.arg("KeyFileProtectedNoPassword.kdbx"));
  88. m_yubiKeyProtectedDbFile.reset(new TemporaryFile());
  89. m_yubiKeyProtectedDbFile->copyFromFile(file.arg("YubiKeyProtectedPasswords.kdbx"));
  90. m_nonAsciiDbFile.reset(new TemporaryFile());
  91. m_nonAsciiDbFile->copyFromFile(file.arg("NonAscii.kdbx"));
  92. m_stdout.reset(new QBuffer());
  93. m_stdout->open(QIODevice::ReadWrite);
  94. Utils::STDOUT.setDevice(m_stdout.data());
  95. m_stderr.reset(new QBuffer());
  96. m_stderr->open(QIODevice::ReadWrite);
  97. Utils::STDERR.setDevice(m_stderr.data());
  98. m_stdin.reset(new QBuffer());
  99. m_stdin->open(QIODevice::ReadWrite);
  100. Utils::STDIN.setDevice(m_stdin.data());
  101. }
  102. void TestCli::cleanup()
  103. {
  104. m_dbFile.reset();
  105. m_dbFile2.reset();
  106. m_dbFileMulti.reset();
  107. m_keyFileProtectedDbFile.reset();
  108. m_keyFileProtectedNoPasswordDbFile.reset();
  109. m_yubiKeyProtectedDbFile.reset();
  110. Utils::STDOUT.setDevice(nullptr);
  111. Utils::STDERR.setDevice(nullptr);
  112. Utils::STDIN.setDevice(nullptr);
  113. }
  114. void TestCli::cleanupTestCase()
  115. {
  116. m_devNull.reset();
  117. }
  118. QSharedPointer<Database> TestCli::readDatabase(const QString& filename, const QString& pw, const QString& keyfile)
  119. {
  120. auto db = QSharedPointer<Database>::create();
  121. auto key = QSharedPointer<CompositeKey>::create();
  122. if (filename.isEmpty()) {
  123. // Open the default test database
  124. key->addKey(QSharedPointer<PasswordKey>::create("a"));
  125. if (!db->open(m_dbFile->fileName(), key)) {
  126. return {};
  127. }
  128. } else {
  129. // Open the specified database file using supplied credentials
  130. key->addKey(QSharedPointer<PasswordKey>::create(pw));
  131. if (!keyfile.isEmpty()) {
  132. auto filekey = QSharedPointer<FileKey>::create();
  133. filekey->load(keyfile);
  134. key->addKey(filekey);
  135. }
  136. if (!db->open(filename, key)) {
  137. return {};
  138. }
  139. }
  140. return db;
  141. }
  142. int TestCli::execCmd(Command& cmd, const QStringList& args) const
  143. {
  144. // Move to end of stream
  145. m_stdout->readAll();
  146. m_stderr->readAll();
  147. // Record stream position
  148. auto outPos = m_stdout->pos();
  149. auto errPos = m_stderr->pos();
  150. // Execute command
  151. int ret = cmd.execute(args);
  152. // Move back to recorded position
  153. m_stdout->seek(outPos);
  154. m_stderr->seek(errPos);
  155. // Skip over blank lines
  156. QByteArray newline("\n");
  157. while (m_stdout->peek(1) == newline) {
  158. m_stdout->readLine();
  159. }
  160. while (m_stderr->peek(1) == newline) {
  161. m_stderr->readLine();
  162. }
  163. return ret;
  164. }
  165. bool TestCli::isTotp(const QString& value)
  166. {
  167. static const QRegularExpression totp("^\\d{6}$");
  168. return totp.match(value.trimmed()).hasMatch();
  169. }
  170. void TestCli::setInput(const QString& input)
  171. {
  172. setInput(QStringList(input));
  173. }
  174. void TestCli::setInput(const QStringList& input)
  175. {
  176. auto ba = input.join("\n").toLatin1();
  177. // Always end in newline
  178. if (!ba.endsWith("\n")) {
  179. ba.append("\n");
  180. }
  181. auto pos = m_stdin->pos();
  182. m_stdin->write(ba);
  183. m_stdin->seek(pos);
  184. }
  185. void TestCli::testBatchCommands()
  186. {
  187. Commands::setupCommands(false);
  188. QVERIFY(Commands::getCommand("add"));
  189. QVERIFY(Commands::getCommand("analyze"));
  190. QVERIFY(Commands::getCommand("attachment-export"));
  191. QVERIFY(Commands::getCommand("attachment-import"));
  192. QVERIFY(Commands::getCommand("attachment-rm"));
  193. QVERIFY(Commands::getCommand("clip"));
  194. QVERIFY(Commands::getCommand("close"));
  195. QVERIFY(Commands::getCommand("db-create"));
  196. QVERIFY(Commands::getCommand("db-info"));
  197. QVERIFY(Commands::getCommand("diceware"));
  198. QVERIFY(Commands::getCommand("edit"));
  199. QVERIFY(Commands::getCommand("estimate"));
  200. QVERIFY(Commands::getCommand("export"));
  201. QVERIFY(Commands::getCommand("generate"));
  202. QVERIFY(Commands::getCommand("help"));
  203. QVERIFY(Commands::getCommand("import"));
  204. QVERIFY(Commands::getCommand("ls"));
  205. QVERIFY(Commands::getCommand("merge"));
  206. QVERIFY(Commands::getCommand("mkdir"));
  207. QVERIFY(Commands::getCommand("mv"));
  208. QVERIFY(Commands::getCommand("open"));
  209. QVERIFY(Commands::getCommand("rm"));
  210. QVERIFY(Commands::getCommand("rmdir"));
  211. QVERIFY(Commands::getCommand("show"));
  212. QVERIFY(Commands::getCommand("search"));
  213. QVERIFY(!Commands::getCommand("doesnotexist"));
  214. QCOMPARE(Commands::getCommands().size(), 26);
  215. }
  216. void TestCli::testInteractiveCommands()
  217. {
  218. Commands::setupCommands(true);
  219. QVERIFY(Commands::getCommand("add"));
  220. QVERIFY(Commands::getCommand("analyze"));
  221. QVERIFY(Commands::getCommand("attachment-export"));
  222. QVERIFY(Commands::getCommand("attachment-import"));
  223. QVERIFY(Commands::getCommand("attachment-rm"));
  224. QVERIFY(Commands::getCommand("clip"));
  225. QVERIFY(Commands::getCommand("close"));
  226. QVERIFY(Commands::getCommand("db-create"));
  227. QVERIFY(Commands::getCommand("db-info"));
  228. QVERIFY(Commands::getCommand("diceware"));
  229. QVERIFY(Commands::getCommand("edit"));
  230. QVERIFY(Commands::getCommand("estimate"));
  231. QVERIFY(Commands::getCommand("exit"));
  232. QVERIFY(Commands::getCommand("generate"));
  233. QVERIFY(Commands::getCommand("help"));
  234. QVERIFY(Commands::getCommand("ls"));
  235. QVERIFY(Commands::getCommand("merge"));
  236. QVERIFY(Commands::getCommand("mkdir"));
  237. QVERIFY(Commands::getCommand("mv"));
  238. QVERIFY(Commands::getCommand("open"));
  239. QVERIFY(Commands::getCommand("quit"));
  240. QVERIFY(Commands::getCommand("rm"));
  241. QVERIFY(Commands::getCommand("rmdir"));
  242. QVERIFY(Commands::getCommand("show"));
  243. QVERIFY(Commands::getCommand("search"));
  244. QVERIFY(!Commands::getCommand("doesnotexist"));
  245. QCOMPARE(Commands::getCommands().size(), 26);
  246. }
  247. void TestCli::testAdd()
  248. {
  249. Add addCmd;
  250. QVERIFY(!addCmd.name.isEmpty());
  251. QVERIFY(addCmd.getDescriptionLine().contains(addCmd.name));
  252. setInput("a");
  253. execCmd(addCmd,
  254. {"add",
  255. "-u",
  256. "newuser",
  257. "--url",
  258. "https://example.com/",
  259. "-g",
  260. "-L",
  261. "20",
  262. "--notes",
  263. "some notes",
  264. m_dbFile->fileName(),
  265. "/newuser-entry"});
  266. m_stderr->readLine(); // Skip password prompt
  267. QCOMPARE(m_stderr->readAll(), QByteArray());
  268. QVERIFY(m_stdout->readAll().contains("Successfully added entry newuser-entry."));
  269. auto db = readDatabase();
  270. auto* entry = db->rootGroup()->findEntryByPath("/newuser-entry");
  271. QVERIFY(entry);
  272. QCOMPARE(entry->username(), QString("newuser"));
  273. QCOMPARE(entry->url(), QString("https://example.com/"));
  274. QCOMPARE(entry->password().size(), 20);
  275. QCOMPARE(entry->notes(), QString("some notes"));
  276. // Quiet option
  277. setInput("a");
  278. execCmd(addCmd, {"add", "-q", "-u", "newuser", "-g", "-L", "20", m_dbFile->fileName(), "/newentry-quiet"});
  279. QCOMPARE(m_stderr->readAll(), QByteArray());
  280. QCOMPARE(m_stdout->readAll(), QByteArray());
  281. db = readDatabase();
  282. entry = db->rootGroup()->findEntryByPath("/newentry-quiet");
  283. QVERIFY(entry);
  284. QCOMPARE(entry->password().size(), 20);
  285. setInput({"a", "newpassword"});
  286. execCmd(addCmd,
  287. {"add", "-u", "newuser2", "--url", "https://example.net/", "-p", m_dbFile->fileName(), "/newuser-entry2"});
  288. QVERIFY(m_stdout->readAll().contains("Successfully added entry newuser-entry2."));
  289. db = readDatabase();
  290. entry = db->rootGroup()->findEntryByPath("/newuser-entry2");
  291. QVERIFY(entry);
  292. QCOMPARE(entry->username(), QString("newuser2"));
  293. QCOMPARE(entry->url(), QString("https://example.net/"));
  294. QCOMPARE(entry->password(), QString("newpassword"));
  295. // Password generation options
  296. setInput("a");
  297. execCmd(addCmd, {"add", "-u", "newuser3", "-g", "-L", "34", m_dbFile->fileName(), "/newuser-entry3"});
  298. QVERIFY(m_stdout->readAll().contains("Successfully added entry newuser-entry3."));
  299. db = readDatabase();
  300. entry = db->rootGroup()->findEntryByPath("/newuser-entry3");
  301. QVERIFY(entry);
  302. QCOMPARE(entry->username(), QString("newuser3"));
  303. QCOMPARE(entry->password().size(), 34);
  304. QRegularExpression defaultPasswordClassesRegex("^[a-zA-Z0-9]+$");
  305. QVERIFY(defaultPasswordClassesRegex.match(entry->password()).hasMatch());
  306. setInput("a");
  307. execCmd(addCmd,
  308. {"add",
  309. "-u",
  310. "newuser4",
  311. "-g",
  312. "-L",
  313. "20",
  314. "--every-group",
  315. "-s",
  316. "-n",
  317. "-U",
  318. "-l",
  319. m_dbFile->fileName(),
  320. "/newuser-entry4"});
  321. QVERIFY(m_stdout->readAll().contains("Successfully added entry newuser-entry4."));
  322. db = readDatabase();
  323. entry = db->rootGroup()->findEntryByPath("/newuser-entry4");
  324. QVERIFY(entry);
  325. QCOMPARE(entry->username(), QString("newuser4"));
  326. QCOMPARE(entry->password().size(), 20);
  327. QVERIFY(!defaultPasswordClassesRegex.match(entry->password()).hasMatch());
  328. setInput("a");
  329. execCmd(addCmd, {"add", "-u", "newuser5", "--notes", "test\\nnew line", m_dbFile->fileName(), "/newuser-entry5"});
  330. m_stderr->readLine(); // skip password prompt
  331. QCOMPARE(m_stderr->readAll(), QByteArray(""));
  332. QCOMPARE(m_stdout->readAll(), QByteArray("Successfully added entry newuser-entry5.\n"));
  333. db = readDatabase();
  334. entry = db->rootGroup()->findEntryByPath("/newuser-entry5");
  335. QVERIFY(entry);
  336. QCOMPARE(entry->username(), QString("newuser5"));
  337. QCOMPARE(entry->notes(), QString("test\nnew line"));
  338. }
  339. void TestCli::testAddGroup()
  340. {
  341. AddGroup addGroupCmd;
  342. QVERIFY(!addGroupCmd.name.isEmpty());
  343. QVERIFY(addGroupCmd.getDescriptionLine().contains(addGroupCmd.name));
  344. setInput("a");
  345. execCmd(addGroupCmd, {"mkdir", m_dbFile->fileName(), "/new_group"});
  346. m_stderr->readLine(); // Skip password prompt
  347. QCOMPARE(m_stderr->readAll(), QByteArray());
  348. QCOMPARE(m_stdout->readAll(), QByteArray("Successfully added group new_group.\n"));
  349. auto db = readDatabase();
  350. auto* group = db->rootGroup()->findGroupByPath("new_group");
  351. QVERIFY(group);
  352. QCOMPARE(group->name(), QString("new_group"));
  353. // Trying to add the same group should fail.
  354. setInput("a");
  355. execCmd(addGroupCmd, {"mkdir", m_dbFile->fileName(), "/new_group"});
  356. QVERIFY(m_stderr->readAll().contains("Group /new_group already exists!"));
  357. QCOMPARE(m_stdout->readAll(), QByteArray());
  358. // Should be able to add groups down the tree.
  359. setInput("a");
  360. execCmd(addGroupCmd, {"mkdir", m_dbFile->fileName(), "/new_group/newer_group"});
  361. QVERIFY(m_stdout->readAll().contains("Successfully added group newer_group."));
  362. db = readDatabase();
  363. group = db->rootGroup()->findGroupByPath("new_group/newer_group");
  364. QVERIFY(group);
  365. QCOMPARE(group->name(), QString("newer_group"));
  366. // Should fail if the path is invalid.
  367. setInput("a");
  368. execCmd(addGroupCmd, {"mkdir", m_dbFile->fileName(), "/invalid_group/newer_group"});
  369. QVERIFY(m_stderr->readAll().contains("Group /invalid_group not found."));
  370. QCOMPARE(m_stdout->readAll(), QByteArray());
  371. // Should fail to add the root group.
  372. setInput("a");
  373. execCmd(addGroupCmd, {"mkdir", m_dbFile->fileName(), "/"});
  374. QVERIFY(m_stderr->readAll().contains("Group / already exists!"));
  375. QCOMPARE(m_stdout->readAll(), QByteArray());
  376. }
  377. void TestCli::testAnalyze()
  378. {
  379. Analyze analyzeCmd;
  380. QVERIFY(!analyzeCmd.name.isEmpty());
  381. QVERIFY(analyzeCmd.getDescriptionLine().contains(analyzeCmd.name));
  382. const QString hibpPath = QString(KEEPASSX_TEST_DATA_DIR).append("/hibp.txt");
  383. setInput("a");
  384. execCmd(analyzeCmd, {"analyze", "--hibp", hibpPath, m_dbFile->fileName()});
  385. auto output = m_stdout->readAll();
  386. QVERIFY(output.contains("Sample Entry"));
  387. QVERIFY(output.contains("123"));
  388. m_stderr->readLine(); // Skip password prompt
  389. QCOMPARE(m_stderr->readAll(), QByteArray());
  390. }
  391. void TestCli::testAttachmentExport()
  392. {
  393. AttachmentExport attachmentExportCmd;
  394. QVERIFY(!attachmentExportCmd.name.isEmpty());
  395. QVERIFY(attachmentExportCmd.getDescriptionLine().contains(attachmentExportCmd.name));
  396. TemporaryFile exportOutput;
  397. exportOutput.open(QIODevice::WriteOnly);
  398. exportOutput.close();
  399. // Try exporting an attachment of a non-existent entry
  400. setInput("a");
  401. execCmd(attachmentExportCmd,
  402. {"attachment-export",
  403. m_dbFile->fileName(),
  404. "invalid_entry_path",
  405. "invalid_attachment_name",
  406. exportOutput.fileName()});
  407. m_stderr->readLine(); // skip password prompt
  408. QCOMPARE(m_stderr->readAll(), QByteArray("Could not find entry with path invalid_entry_path.\n"));
  409. QCOMPARE(m_stdout->readAll(), QByteArray());
  410. // Try exporting a non-existent attachment
  411. setInput("a");
  412. execCmd(attachmentExportCmd,
  413. {"attachment-export",
  414. m_dbFile->fileName(),
  415. "/Sample Entry",
  416. "invalid_attachment_name",
  417. exportOutput.fileName()});
  418. m_stderr->readLine(); // skip password prompt
  419. QCOMPARE(m_stderr->readAll(), QByteArray("Could not find attachment with name invalid_attachment_name.\n"));
  420. QCOMPARE(m_stdout->readAll(), QByteArray());
  421. // Export an existing attachment to a file
  422. setInput("a");
  423. execCmd(
  424. attachmentExportCmd,
  425. {"attachment-export", m_dbFile->fileName(), "/Sample Entry", "Sample attachment.txt", exportOutput.fileName()});
  426. m_stderr->readLine(); // skip password prompt
  427. QCOMPARE(m_stderr->readAll(), QByteArray());
  428. QCOMPARE(m_stdout->readAll(),
  429. QByteArray(qPrintable(QString("Successfully exported attachment %1 of entry %2 to %3.\n")
  430. .arg("Sample attachment.txt", "/Sample Entry", exportOutput.fileName()))));
  431. exportOutput.open(QIODevice::ReadOnly);
  432. QCOMPARE(exportOutput.readAll(), QByteArray("Sample content\n"));
  433. // Export an existing attachment to stdout
  434. setInput("a");
  435. execCmd(attachmentExportCmd,
  436. {"attachment-export", "--stdout", m_dbFile->fileName(), "/Sample Entry", "Sample attachment.txt"});
  437. m_stderr->readLine(); // skip password prompt
  438. QCOMPARE(m_stderr->readAll(), QByteArray());
  439. QCOMPARE(m_stdout->readAll(), QByteArray("Sample content\n"));
  440. // Ensure --stdout works even in quiet mode
  441. setInput("a");
  442. execCmd(
  443. attachmentExportCmd,
  444. {"attachment-export", "--quiet", "--stdout", m_dbFile->fileName(), "/Sample Entry", "Sample attachment.txt"});
  445. m_stderr->readLine(); // skip password prompt
  446. QCOMPARE(m_stderr->readAll(), QByteArray());
  447. QCOMPARE(m_stdout->readAll(), QByteArray("Sample content\n"));
  448. }
  449. void TestCli::testAttachmentImport()
  450. {
  451. AttachmentImport attachmentImportCmd;
  452. QVERIFY(!attachmentImportCmd.name.isEmpty());
  453. QVERIFY(attachmentImportCmd.getDescriptionLine().contains(attachmentImportCmd.name));
  454. const QString attachmentPath = QString(KEEPASSX_TEST_DATA_DIR).append("/Attachment.txt");
  455. QVERIFY(QFile::exists(attachmentPath));
  456. // Try importing an attachment to a non-existent entry
  457. setInput("a");
  458. execCmd(attachmentImportCmd,
  459. {"attachment-import",
  460. m_dbFile->fileName(),
  461. "invalid_entry_path",
  462. "invalid_attachment_name",
  463. "invalid_attachment_path"});
  464. m_stderr->readLine(); // skip password prompt
  465. QCOMPARE(m_stderr->readAll(), QByteArray("Could not find entry with path invalid_entry_path.\n"));
  466. QCOMPARE(m_stdout->readAll(), QByteArray());
  467. // Try importing an attachment with an occupied name without -f option
  468. setInput("a");
  469. execCmd(attachmentImportCmd,
  470. {"attachment-import",
  471. m_dbFile->fileName(),
  472. "/Sample Entry",
  473. "Sample attachment.txt",
  474. "invalid_attachment_path"});
  475. m_stderr->readLine(); // skip password prompt
  476. QCOMPARE(m_stderr->readAll(),
  477. QByteArray("Attachment Sample attachment.txt already exists for entry /Sample Entry.\n"));
  478. QCOMPARE(m_stdout->readAll(), QByteArray());
  479. // Try importing a non-existent attachment
  480. setInput("a");
  481. execCmd(attachmentImportCmd,
  482. {"attachment-import",
  483. m_dbFile->fileName(),
  484. "/Sample Entry",
  485. "Sample attachment 2.txt",
  486. "invalid_attachment_path"});
  487. m_stderr->readLine(); // skip password prompt
  488. QCOMPARE(m_stderr->readAll(), QByteArray("Could not open attachment file invalid_attachment_path.\n"));
  489. QCOMPARE(m_stdout->readAll(), QByteArray());
  490. // Try importing an attachment with an occupied name with -f option
  491. setInput("a");
  492. execCmd(
  493. attachmentImportCmd,
  494. {"attachment-import", "-f", m_dbFile->fileName(), "/Sample Entry", "Sample attachment.txt", attachmentPath});
  495. m_stderr->readLine(); // skip password prompt
  496. QCOMPARE(m_stderr->readAll(), QByteArray());
  497. QCOMPARE(m_stdout->readAll(),
  498. QByteArray(qPrintable(
  499. QString("Successfully imported attachment %1 as Sample attachment.txt to entry /Sample Entry.\n")
  500. .arg(attachmentPath))));
  501. // Try importing an attachment with an unoccupied name
  502. setInput("a");
  503. execCmd(attachmentImportCmd,
  504. {"attachment-import", m_dbFile->fileName(), "/Sample Entry", "Attachment.txt", attachmentPath});
  505. m_stderr->readLine(); // skip password prompt
  506. QCOMPARE(m_stderr->readAll(), QByteArray());
  507. QCOMPARE(
  508. m_stdout->readAll(),
  509. QByteArray(qPrintable(QString("Successfully imported attachment %1 as Attachment.txt to entry /Sample Entry.\n")
  510. .arg(attachmentPath))));
  511. }
  512. void TestCli::testAttachmentRemove()
  513. {
  514. AttachmentRemove attachmentRemoveCmd;
  515. QVERIFY(!attachmentRemoveCmd.name.isEmpty());
  516. QVERIFY(attachmentRemoveCmd.getDescriptionLine().contains(attachmentRemoveCmd.name));
  517. // Try deleting an attachment belonging to an non-existent entry
  518. setInput("a");
  519. execCmd(attachmentRemoveCmd,
  520. {"attachment-rm", m_dbFile->fileName(), "invalid_entry_path", "invalid_attachment_name"});
  521. m_stderr->readLine(); // skip password prompt
  522. QCOMPARE(m_stderr->readAll(), QByteArray("Could not find entry with path invalid_entry_path.\n"));
  523. QCOMPARE(m_stdout->readAll(), QByteArray());
  524. // Try deleting a non-existent attachment from an entry
  525. setInput("a");
  526. execCmd(attachmentRemoveCmd, {"attachment-rm", m_dbFile->fileName(), "/Sample Entry", "invalid_attachment_name"});
  527. m_stderr->readLine(); // skip password prompt
  528. QCOMPARE(m_stderr->readAll(), QByteArray("Could not find attachment with name invalid_attachment_name.\n"));
  529. QCOMPARE(m_stdout->readAll(), QByteArray());
  530. // Finally delete an existing attachment from an existing entry
  531. auto db = readDatabase();
  532. QVERIFY(db);
  533. const Entry* entry = db->rootGroup()->findEntryByPath("/Sample Entry");
  534. QVERIFY(entry);
  535. QVERIFY(entry->attachments()->hasKey("Sample attachment.txt"));
  536. setInput("a");
  537. execCmd(attachmentRemoveCmd, {"attachment-rm", m_dbFile->fileName(), "/Sample Entry", "Sample attachment.txt"});
  538. m_stderr->readLine(); // skip password prompt
  539. QCOMPARE(m_stderr->readAll(), QByteArray());
  540. QCOMPARE(m_stdout->readAll(),
  541. QByteArray("Successfully removed attachment Sample attachment.txt from entry /Sample Entry.\n"));
  542. db = readDatabase();
  543. QVERIFY(db);
  544. QVERIFY(!db->rootGroup()->findEntryByPath("/Sample Entry")->attachments()->hasKey("Sample attachment.txt"));
  545. }
  546. void TestCli::testClip()
  547. {
  548. if (QProcessEnvironment::systemEnvironment().contains("WAYLAND_DISPLAY")) {
  549. QSKIP("Clip test skipped due to QClipboard and Wayland issues on Linux");
  550. }
  551. QClipboard* clipboard = QGuiApplication::clipboard();
  552. clipboard->clear();
  553. Clip clipCmd;
  554. QVERIFY(!clipCmd.name.isEmpty());
  555. QVERIFY(clipCmd.getDescriptionLine().contains(clipCmd.name));
  556. // Password
  557. setInput("a");
  558. execCmd(clipCmd, {"clip", m_dbFile->fileName(), "/Sample Entry", "0"});
  559. QString errorOutput(m_stderr->readAll());
  560. if (errorOutput.contains("Unable to start program")
  561. || errorOutput.contains("No program defined for clipboard manipulation")) {
  562. QSKIP("Clip test skipped due to missing clipboard tool");
  563. }
  564. QVERIFY(!errorOutput.contains("All clipping programs failed"));
  565. m_stderr->readLine(); // Skip password prompt
  566. QCOMPARE(m_stderr->readAll(), QByteArray());
  567. QTRY_COMPARE(clipboard->text(), QString("Password"));
  568. QCOMPARE(m_stdout->readLine(), QByteArray("Entry's \"Password\" attribute copied to the clipboard!\n"));
  569. // Quiet option
  570. setInput("a");
  571. execCmd(clipCmd, {"clip", m_dbFile->fileName(), "/Sample Entry", "0", "-q"});
  572. QCOMPARE(m_stderr->readAll(), QByteArray());
  573. QCOMPARE(m_stdout->readAll(), QByteArray());
  574. QTRY_COMPARE(clipboard->text(), QString("Password"));
  575. // Username
  576. setInput("a");
  577. execCmd(clipCmd, {"clip", m_dbFile->fileName(), "/Sample Entry", "0", "-a", "username"});
  578. QTRY_COMPARE(clipboard->text(), QString("User Name"));
  579. // Uuid (top-level field)
  580. setInput("a");
  581. execCmd(clipCmd, {"clip", m_dbFile->fileName(), "/Sample Entry", "0", "-a", "Uuid"});
  582. QTRY_COMPARE(clipboard->text(), QString("{9f4544c2-ab00-c74a-8a1a-6eaf26cf57e9}"));
  583. // TOTP
  584. setInput("a");
  585. execCmd(clipCmd, {"clip", m_dbFile->fileName(), "/Sample Entry", "0", "--totp"});
  586. QTRY_VERIFY(isTotp(clipboard->text()));
  587. QCOMPARE(m_stdout->readLine(), QByteArray("Entry's \"totp\" attribute copied to the clipboard!\n"));
  588. // Test Unicode
  589. setInput("a");
  590. execCmd(clipCmd, {"clip", m_dbFile2->fileName(), "/General/Unicode", "0", "-a", "username"});
  591. QTRY_COMPARE(clipboard->text(), QString(R"(¯\_(ツ)_/¯)"));
  592. // Password with timeout
  593. setInput("a");
  594. // clang-format off
  595. QFuture<void> future = QtConcurrent::run(&clipCmd,
  596. static_cast<int(Clip::*)(const QStringList&)>(&DatabaseCommand::execute),
  597. QStringList{"clip", m_dbFile->fileName(), "/Sample Entry", "1"});
  598. // clang-format on
  599. QTRY_COMPARE(clipboard->text(), QString("Password"));
  600. QTRY_COMPARE_WITH_TIMEOUT(clipboard->text(), QString(""), 3000);
  601. future.waitForFinished();
  602. // TOTP with timeout
  603. setInput("a");
  604. future = QtConcurrent::run(&clipCmd,
  605. static_cast<int (Clip::*)(const QStringList&)>(&DatabaseCommand::execute),
  606. QStringList{"clip", m_dbFile->fileName(), "/Sample Entry", "1", "-t"});
  607. QTRY_VERIFY(isTotp(clipboard->text()));
  608. QTRY_COMPARE_WITH_TIMEOUT(clipboard->text(), QString(""), 3000);
  609. future.waitForFinished();
  610. setInput("a");
  611. execCmd(clipCmd, {"clip", m_dbFile->fileName(), "--totp", "/Sample Entry", "bleuh"});
  612. QVERIFY(m_stderr->readAll().contains("Invalid timeout value bleuh.\n"));
  613. setInput("a");
  614. execCmd(clipCmd, {"clip", m_dbFile2->fileName(), "--totp", "/Sample Entry", "0"});
  615. QVERIFY(m_stderr->readAll().contains("Entry with path /Sample Entry has no TOTP set up.\n"));
  616. setInput("a");
  617. execCmd(clipCmd, {"clip", m_dbFile->fileName(), "-a", "TESTAttribute1", "/Sample Entry", "0"});
  618. QVERIFY(m_stderr->readAll().contains("ERROR: attribute TESTAttribute1 is ambiguous"));
  619. setInput("a");
  620. execCmd(clipCmd, {"clip", m_dbFile2->fileName(), "--attribute", "Username", "--totp", "/Sample Entry", "0"});
  621. QVERIFY(m_stderr->readAll().contains("ERROR: Please specify one of --attribute or --totp, not both.\n"));
  622. // Best option
  623. setInput("a");
  624. execCmd(clipCmd, {"clip", m_dbFileMulti->fileName(), "Multi", "0", "-b"});
  625. QByteArray errorChoices = m_stderr->readAll();
  626. QVERIFY(errorChoices.contains("Multi Entry 1"));
  627. QVERIFY(errorChoices.contains("Multi Entry 2"));
  628. setInput("a");
  629. execCmd(clipCmd, {"clip", m_dbFileMulti->fileName(), "Entry 2", "0", "-b"});
  630. QTRY_COMPARE(clipboard->text(), QString("Password2"));
  631. }
  632. void TestCli::testCreate()
  633. {
  634. DatabaseCreate createCmd;
  635. QVERIFY(!createCmd.name.isEmpty());
  636. QVERIFY(createCmd.getDescriptionLine().contains(createCmd.name));
  637. QScopedPointer<QTemporaryDir> testDir(new QTemporaryDir());
  638. QString dbFilename;
  639. // Testing password option, password mismatch
  640. dbFilename = testDir->path() + "/testCreate_pw.kdbx";
  641. setInput({"a", "b"});
  642. execCmd(createCmd, {"db-create", dbFilename, "-p"});
  643. QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
  644. QCOMPARE(m_stderr->readLine(), QByteArray("Repeat password: \n"));
  645. QCOMPARE(m_stderr->readLine(), QByteArray("Error: Passwords do not match.\n"));
  646. QCOMPARE(m_stderr->readLine(), QByteArray("Failed to set database password.\n"));
  647. // Testing password option
  648. setInput({"a", "a"});
  649. execCmd(createCmd, {"db-create", dbFilename, "-p"});
  650. QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
  651. QCOMPARE(m_stderr->readLine(), QByteArray("Repeat password: \n"));
  652. QCOMPARE(m_stdout->readLine(), QByteArray("Successfully created new database.\n"));
  653. auto db = readDatabase(dbFilename, "a");
  654. QVERIFY(db);
  655. // Testing with empty password (deny it)
  656. dbFilename = testDir->path() + "/testCreate_blankpw.kdbx";
  657. setInput({"", "n"});
  658. execCmd(createCmd, {"db-create", dbFilename, "-p"});
  659. QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
  660. QVERIFY(m_stderr->readLine().contains("empty password"));
  661. QCOMPARE(m_stderr->readLine(), QByteArray("Failed to set database password.\n"));
  662. // Testing with empty password (accept it)
  663. setInput({"", "y"});
  664. execCmd(createCmd, {"db-create", dbFilename, "-p"});
  665. QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
  666. QVERIFY(m_stderr->readLine().contains("empty password"));
  667. QCOMPARE(m_stdout->readLine(), QByteArray("Successfully created new database.\n"));
  668. db = readDatabase(dbFilename, "");
  669. QVERIFY(db);
  670. // Should refuse to create the database if it already exists.
  671. execCmd(createCmd, {"db-create", dbFilename, "-p"});
  672. // Output should be empty when there is an error.
  673. QCOMPARE(m_stdout->readAll(), QByteArray());
  674. QString errorMessage = QString("File " + dbFilename + " already exists.\n");
  675. QCOMPARE(m_stderr->readAll(), errorMessage.toUtf8());
  676. // Should refuse to create without any key provided.
  677. dbFilename = testDir->path() + "/testCreate_key.kdbx";
  678. execCmd(createCmd, {"db-create", dbFilename});
  679. QCOMPARE(m_stdout->readAll(), QByteArray());
  680. QCOMPARE(m_stderr->readLine(), QByteArray("No key is set. Aborting database creation.\n"));
  681. // Testing with keyfile creation
  682. dbFilename = testDir->path() + "/testCreate_key2.kdbx";
  683. QString keyfilePath = testDir->path() + "/keyfile.txt";
  684. setInput({"a", "a"});
  685. execCmd(createCmd, {"db-create", dbFilename, "-p", "-k", keyfilePath});
  686. QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
  687. QCOMPARE(m_stderr->readLine(), QByteArray("Repeat password: \n"));
  688. QCOMPARE(m_stdout->readLine(), QByteArray("Successfully created new database.\n"));
  689. db = readDatabase(dbFilename, "a", keyfilePath);
  690. QVERIFY(db);
  691. // Testing with existing keyfile
  692. dbFilename = testDir->path() + "/testCreate_key3.kdbx";
  693. setInput({"a", "a"});
  694. execCmd(createCmd, {"db-create", dbFilename, "-p", "-k", keyfilePath});
  695. QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
  696. QCOMPARE(m_stderr->readLine(), QByteArray("Repeat password: \n"));
  697. QCOMPARE(m_stdout->readLine(), QByteArray("Successfully created new database.\n"));
  698. db = readDatabase(dbFilename, "a", keyfilePath);
  699. QVERIFY(db);
  700. // Invalid decryption time (format).
  701. dbFilename = testDir->path() + "/testCreate_time.kdbx";
  702. execCmd(createCmd, {"db-create", dbFilename, "-p", "-t", "NAN"});
  703. QCOMPARE(m_stdout->readAll(), QByteArray());
  704. QCOMPARE(m_stderr->readAll(), QByteArray("Invalid decryption time NAN.\n"));
  705. // Invalid decryption time (range).
  706. execCmd(createCmd, {"db-create", dbFilename, "-p", "-t", "10"});
  707. QCOMPARE(m_stdout->readAll(), QByteArray());
  708. QVERIFY(m_stderr->readAll().contains(QByteArray("Target decryption time must be between")));
  709. int encryptionTime = 500;
  710. // Custom encryption time
  711. setInput({"a", "a"});
  712. int epochBefore = QDateTime::currentMSecsSinceEpoch();
  713. execCmd(createCmd, {"db-create", dbFilename, "-p", "-t", QString::number(encryptionTime)});
  714. // Removing 100ms to make sure we account for changes in computation time.
  715. QVERIFY(QDateTime::currentMSecsSinceEpoch() > (epochBefore + encryptionTime - 100));
  716. QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
  717. QCOMPARE(m_stderr->readLine(), QByteArray("Repeat password: \n"));
  718. QCOMPARE(m_stdout->readLine(), QByteArray("Benchmarking key derivation function for 500ms delay.\n"));
  719. QVERIFY(m_stdout->readLine().contains(QByteArray("rounds for key derivation function.\n")));
  720. db = readDatabase(dbFilename, "a");
  721. QVERIFY(db);
  722. }
  723. void TestCli::testDatabaseEdit()
  724. {
  725. TemporaryFile firstKeyFile;
  726. firstKeyFile.open();
  727. firstKeyFile.write(QString("keyFilePassword").toLatin1());
  728. firstKeyFile.close();
  729. TemporaryFile secondKeyFile;
  730. secondKeyFile.open();
  731. secondKeyFile.write(QString("newKeyFilePassword").toLatin1());
  732. secondKeyFile.close();
  733. QScopedPointer<QTemporaryDir> testDir(new QTemporaryDir());
  734. DatabaseCreate createCmd;
  735. DatabaseEdit editCmd;
  736. QVERIFY(!editCmd.name.isEmpty());
  737. QVERIFY(editCmd.getDescriptionLine().contains(editCmd.name));
  738. QString dbFilename;
  739. dbFilename = testDir->path() + "/testDatabaseEdit.kdbx";
  740. // Creating a database for testing
  741. setInput({"a", "a"});
  742. execCmd(createCmd, {"db-create", dbFilename, "-p"});
  743. QCOMPARE(m_stdout->readLine(), QByteArray("Successfully created new database.\n"));
  744. // Sanity check.
  745. auto db = readDatabase(dbFilename, "a");
  746. QVERIFY(!db.isNull());
  747. setInput("a");
  748. execCmd(editCmd, {"db-edit", dbFilename, "-p", "--unset-password"});
  749. QCOMPARE(m_stdout->readAll(), QByteArray(""));
  750. m_stderr->readLine();
  751. QCOMPARE(m_stderr->readAll(), QByteArray("Cannot use p and unset-password at the same time.\n"));
  752. setInput("a");
  753. execCmd(editCmd, {"db-edit", dbFilename, "--set-key-file", "/key/file/path", "--unset-key-file"});
  754. QCOMPARE(m_stdout->readAll(), QByteArray(""));
  755. // Skipping the password prompt.
  756. m_stderr->readLine();
  757. QCOMPARE(m_stderr->readAll(), QByteArray("Cannot use set-key-file and unset-key-file at the same time.\n"));
  758. // Sanity check.
  759. db = readDatabase(dbFilename, "a");
  760. QVERIFY(!db.isNull());
  761. setInput({"a", "b", "b"});
  762. execCmd(editCmd, {"db-edit", dbFilename, "-p"});
  763. QCOMPARE(m_stdout->readAll(), QByteArray("Successfully edited the database.\n"));
  764. // Sanity check
  765. db = readDatabase(dbFilename, "b");
  766. QVERIFY(!db.isNull());
  767. setInput("b");
  768. execCmd(editCmd, {"db-edit", dbFilename, "--set-key-file", firstKeyFile.fileName()});
  769. // Skipping the password prompt.
  770. m_stderr->readLine();
  771. QCOMPARE(m_stderr->readAll(), QByteArray(""));
  772. QCOMPARE(m_stdout->readAll(), QByteArray("Successfully edited the database.\n"));
  773. // Sanity check
  774. db = readDatabase(dbFilename, "b");
  775. QVERIFY(db.isNull());
  776. db = readDatabase(dbFilename, "b", firstKeyFile.fileName());
  777. QVERIFY(!db.isNull());
  778. setInput("b");
  779. execCmd(editCmd,
  780. {"db-edit", dbFilename, "-k", firstKeyFile.fileName(), "--set-key-file", secondKeyFile.fileName()});
  781. QCOMPARE(m_stdout->readAll(), QByteArray("Successfully edited the database.\n"));
  782. // Sanity check
  783. db = readDatabase(dbFilename, "b", firstKeyFile.fileName());
  784. QVERIFY(db.isNull());
  785. db = readDatabase(dbFilename, "b", secondKeyFile.fileName());
  786. QVERIFY(!db.isNull());
  787. setInput("b");
  788. execCmd(editCmd, {"db-edit", dbFilename, "-k", secondKeyFile.fileName(), "--unset-password"});
  789. // Skipping the password prompt.
  790. m_stderr->readLine();
  791. QCOMPARE(m_stderr->readAll(), QByteArray(""));
  792. QCOMPARE(m_stdout->readAll(), QByteArray("Successfully edited the database.\n"));
  793. execCmd(editCmd,
  794. {"db-edit",
  795. dbFilename,
  796. "--no-password",
  797. "-k",
  798. secondKeyFile.fileName(),
  799. "--set-key-file",
  800. firstKeyFile.fileName()});
  801. // Skipping the password prompt.
  802. m_stderr->readLine();
  803. QCOMPARE(m_stderr->readAll(), QByteArray(""));
  804. QCOMPARE(m_stdout->readAll(), QByteArray("Successfully edited the database.\n"));
  805. setInput({"b", "b"});
  806. execCmd(editCmd, {"db-edit", dbFilename, "-k", firstKeyFile.fileName(), "--no-password", "--set-password"});
  807. // Skipping over the password setting prompts.
  808. m_stderr->readLine();
  809. m_stderr->readLine();
  810. QCOMPARE(m_stderr->readAll(), QByteArray(""));
  811. QCOMPARE(m_stdout->readAll(), QByteArray("Successfully edited the database.\n"));
  812. setInput("b");
  813. execCmd(editCmd, {"db-edit", dbFilename, "-k", firstKeyFile.fileName(), "--unset-key-file"});
  814. // Skipping the password prompt.
  815. m_stderr->readLine();
  816. QCOMPARE(m_stderr->readAll(), QByteArray(""));
  817. QCOMPARE(m_stdout->readAll(), QByteArray("Successfully edited the database.\n"));
  818. // Sanity check
  819. db = readDatabase(dbFilename, "b", firstKeyFile.fileName());
  820. QVERIFY(db.isNull());
  821. db = readDatabase(dbFilename, "b");
  822. QVERIFY(!db.isNull());
  823. // Trying to remove the key file when there is none set should
  824. // raise an error.
  825. setInput("b");
  826. execCmd(editCmd, {"db-edit", dbFilename, "-p", "--unset-key-file"});
  827. QCOMPARE(m_stdout->readAll(), QByteArray(""));
  828. m_stderr->readLine();
  829. QCOMPARE(m_stderr->readLine(), QByteArray("Cannot remove file key: The database does not have a file key.\n"));
  830. QCOMPARE(m_stderr->readLine(), QByteArray("Could not change the database key.\n"));
  831. setInput("b");
  832. execCmd(editCmd, {"db-edit", dbFilename, "--unset-password"});
  833. QCOMPARE(m_stdout->readAll(), QByteArray(""));
  834. // Skipping the password prompt.
  835. m_stderr->readLine();
  836. QCOMPARE(m_stderr->readLine(), QByteArray("Cannot remove all the keys from a database.\n"));
  837. }
  838. void TestCli::testInfo()
  839. {
  840. DatabaseInfo infoCmd;
  841. QVERIFY(!infoCmd.name.isEmpty());
  842. QVERIFY(infoCmd.getDescriptionLine().contains(infoCmd.name));
  843. setInput("a");
  844. execCmd(infoCmd, {"db-info", m_dbFile->fileName()});
  845. m_stderr->readLine(); // Skip password prompt
  846. QCOMPARE(m_stderr->readAll(), QByteArray());
  847. QVERIFY(m_stdout->readLine().contains(QByteArray("UUID: ")));
  848. QCOMPARE(m_stdout->readLine(), QByteArray("Name: \n"));
  849. QCOMPARE(m_stdout->readLine(), QByteArray("Description: \n"));
  850. QCOMPARE(m_stdout->readLine(), QByteArray("Cipher: AES 256-bit\n"));
  851. QCOMPARE(m_stdout->readLine(), QByteArray("KDF: AES (6000 rounds)\n"));
  852. QCOMPARE(m_stdout->readLine(), QByteArray("Recycle bin is enabled.\n"));
  853. QVERIFY(m_stdout->readLine().contains(m_dbFile->fileName().toUtf8()));
  854. QVERIFY(m_stdout->readLine().contains(
  855. QByteArray("Database created: "))); // date changes often, so just test for the first part
  856. QVERIFY(m_stdout->readLine().contains(
  857. QByteArray("Last saved: "))); // date changes often, so just test for the first part
  858. QCOMPARE(m_stdout->readLine(), QByteArray("Unsaved changes: no\n"));
  859. QCOMPARE(m_stdout->readLine(), QByteArray("Number of groups: 8\n"));
  860. QCOMPARE(m_stdout->readLine(), QByteArray("Number of entries: 2\n"));
  861. QCOMPARE(m_stdout->readLine(), QByteArray("Number of expired entries: 0\n"));
  862. QCOMPARE(m_stdout->readLine(), QByteArray("Unique passwords: 2\n"));
  863. QCOMPARE(m_stdout->readLine(), QByteArray("Non-unique passwords: 0\n"));
  864. QCOMPARE(m_stdout->readLine(), QByteArray("Maximum password reuse: 1\n"));
  865. QCOMPARE(m_stdout->readLine(), QByteArray("Number of short passwords: 0\n"));
  866. QCOMPARE(m_stdout->readLine(), QByteArray("Number of weak passwords: 2\n"));
  867. QCOMPARE(m_stdout->readLine(), QByteArray("Entries excluded from reports: 0\n"));
  868. QCOMPARE(m_stdout->readLine(), QByteArray("Average password length: 11 characters\n"));
  869. // Test with quiet option.
  870. setInput("a");
  871. execCmd(infoCmd, {"db-info", "-q", m_dbFile->fileName()});
  872. QCOMPARE(m_stderr->readAll(), QByteArray());
  873. QVERIFY(m_stdout->readLine().contains(QByteArray("UUID: ")));
  874. QCOMPARE(m_stdout->readLine(), QByteArray("Name: \n"));
  875. QCOMPARE(m_stdout->readLine(), QByteArray("Description: \n"));
  876. QCOMPARE(m_stdout->readLine(), QByteArray("Cipher: AES 256-bit\n"));
  877. QCOMPARE(m_stdout->readLine(), QByteArray("KDF: AES (6000 rounds)\n"));
  878. QCOMPARE(m_stdout->readLine(), QByteArray("Recycle bin is enabled.\n"));
  879. }
  880. void TestCli::testDiceware()
  881. {
  882. Diceware dicewareCmd;
  883. QVERIFY(!dicewareCmd.name.isEmpty());
  884. QVERIFY(dicewareCmd.getDescriptionLine().contains(dicewareCmd.name));
  885. execCmd(dicewareCmd, {"diceware"});
  886. QString passphrase(m_stdout->readLine());
  887. QVERIFY(!passphrase.isEmpty());
  888. execCmd(dicewareCmd, {"diceware", "-W", "2"});
  889. passphrase = m_stdout->readLine();
  890. QCOMPARE(passphrase.split(" ").size(), 2);
  891. execCmd(dicewareCmd, {"diceware", "-W", "10"});
  892. passphrase = m_stdout->readLine();
  893. QCOMPARE(passphrase.split(" ").size(), 10);
  894. // Testing with invalid word count
  895. execCmd(dicewareCmd, {"diceware", "-W", "-10"});
  896. QCOMPARE(m_stderr->readLine(), QByteArray("Invalid word count -10\n"));
  897. // Testing with invalid word count format
  898. execCmd(dicewareCmd, {"diceware", "-W", "bleuh"});
  899. QCOMPARE(m_stderr->readLine(), QByteArray("Invalid word count bleuh\n"));
  900. TemporaryFile wordFile;
  901. wordFile.open();
  902. for (int i = 0; i < 4500; ++i) {
  903. wordFile.write(QString("word" + QString::number(i) + "\n").toLatin1());
  904. }
  905. wordFile.close();
  906. execCmd(dicewareCmd, {"diceware", "-W", "11", "-w", wordFile.fileName()});
  907. passphrase = m_stdout->readLine();
  908. const auto words = passphrase.split(" ");
  909. QCOMPARE(words.size(), 11);
  910. QRegularExpression regex("^word\\d+$");
  911. for (const auto& word : words) {
  912. QVERIFY2(regex.match(word).hasMatch(), qPrintable("Word " + word + " was not on the word list"));
  913. }
  914. TemporaryFile smallWordFile;
  915. smallWordFile.open();
  916. for (int i = 0; i < 50; ++i) {
  917. smallWordFile.write(QString("word" + QString::number(i) + "\n").toLatin1());
  918. }
  919. smallWordFile.close();
  920. execCmd(dicewareCmd, {"diceware", "-W", "11", "-w", smallWordFile.fileName()});
  921. QCOMPARE(m_stderr->readLine(), QByteArray("Cannot generate valid passphrases because the wordlist is too short\n"));
  922. }
  923. void TestCli::testEdit()
  924. {
  925. Edit editCmd;
  926. QVERIFY(!editCmd.name.isEmpty());
  927. QVERIFY(editCmd.getDescriptionLine().contains(editCmd.name));
  928. setInput("a");
  929. execCmd(editCmd,
  930. {"edit",
  931. "-u",
  932. "newuser",
  933. "--url",
  934. "https://otherurl.example.com/",
  935. "--notes",
  936. "newnotes",
  937. "-t",
  938. "newtitle",
  939. m_dbFile->fileName(),
  940. "/Sample Entry"});
  941. QCOMPARE(m_stdout->readLine(), QByteArray("Successfully edited entry newtitle.\n"));
  942. auto db = readDatabase();
  943. auto* entry = db->rootGroup()->findEntryByPath("/newtitle");
  944. QVERIFY(entry);
  945. QCOMPARE(entry->username(), QString("newuser"));
  946. QCOMPARE(entry->url(), QString("https://otherurl.example.com/"));
  947. QCOMPARE(entry->password(), QString("Password"));
  948. QCOMPARE(entry->notes(), QString("newnotes"));
  949. // Quiet option
  950. setInput("a");
  951. execCmd(editCmd, {"edit", m_dbFile->fileName(), "-q", "-t", "newertitle", "/newtitle"});
  952. QCOMPARE(m_stderr->readAll(), QByteArray());
  953. QCOMPARE(m_stdout->readAll(), QByteArray());
  954. setInput("a");
  955. execCmd(editCmd, {"edit", "-g", m_dbFile->fileName(), "/newertitle"});
  956. db = readDatabase();
  957. entry = db->rootGroup()->findEntryByPath("/newertitle");
  958. QVERIFY(entry);
  959. QCOMPARE(entry->username(), QString("newuser"));
  960. QCOMPARE(entry->url(), QString("https://otherurl.example.com/"));
  961. QVERIFY(!entry->password().isEmpty());
  962. QVERIFY(entry->password() != QString("Password"));
  963. setInput("a");
  964. execCmd(editCmd, {"edit", "-g", "-L", "34", "-t", "evennewertitle", m_dbFile->fileName(), "/newertitle"});
  965. db = readDatabase();
  966. entry = db->rootGroup()->findEntryByPath("/evennewertitle");
  967. QVERIFY(entry);
  968. QCOMPARE(entry->username(), QString("newuser"));
  969. QCOMPARE(entry->url(), QString("https://otherurl.example.com/"));
  970. QVERIFY(entry->password() != QString("Password"));
  971. QCOMPARE(entry->password().size(), 34);
  972. QRegularExpression defaultPasswordClassesRegex("^[a-zA-Z0-9]+$");
  973. QVERIFY(defaultPasswordClassesRegex.match(entry->password()).hasMatch());
  974. setInput("a");
  975. execCmd(editCmd,
  976. {"edit",
  977. "-g",
  978. "-L",
  979. "20",
  980. "--every-group",
  981. "-s",
  982. "-n",
  983. "--upper",
  984. "-l",
  985. m_dbFile->fileName(),
  986. "/evennewertitle"});
  987. QCOMPARE(m_stdout->readAll(), QByteArray("Successfully edited entry evennewertitle.\n"));
  988. db = readDatabase();
  989. entry = db->rootGroup()->findEntryByPath("/evennewertitle");
  990. QVERIFY(entry);
  991. QCOMPARE(entry->password().size(), 20);
  992. QVERIFY(!defaultPasswordClassesRegex.match(entry->password()).hasMatch());
  993. setInput({"a", "newpassword"});
  994. execCmd(editCmd, {"edit", "-p", m_dbFile->fileName(), "/evennewertitle"});
  995. db = readDatabase();
  996. QVERIFY(db);
  997. entry = db->rootGroup()->findEntryByPath("/evennewertitle");
  998. QVERIFY(entry);
  999. QCOMPARE(entry->password(), QString("newpassword"));
  1000. // with line break in notes
  1001. setInput("a");
  1002. execCmd(editCmd, {"edit", m_dbFile->fileName(), "--notes", "testing\\nline breaks", "/evennewertitle"});
  1003. db = readDatabase();
  1004. entry = db->rootGroup()->findEntryByPath("/evennewertitle");
  1005. QVERIFY(entry);
  1006. QCOMPARE(entry->notes(), QString("testing\nline breaks"));
  1007. }
  1008. void TestCli::testEstimate_data()
  1009. {
  1010. // clang-format off
  1011. QTest::addColumn<QString>("input");
  1012. QTest::addColumn<QStringList>("searchStrings");
  1013. QTest::newRow("Dictionary")
  1014. << "password"
  1015. << QStringList{"Type: Dictionary", "\tpassword"};
  1016. QTest::newRow("Spatial")
  1017. << "sdfg"
  1018. << QStringList{"Type: Spatial", "\tsdfg"};
  1019. QTest::newRow("Spatial(Rep)")
  1020. << "sdfgsdfg"
  1021. << QStringList{"Type: Spatial(Rep)", "\tsdfgsdfg"};
  1022. QTest::newRow("Dictionary / Sequence")
  1023. << "password123"
  1024. << QStringList{"Type: Dictionary", "Type: Sequence", "\tpassword", "\t123"};
  1025. QTest::newRow("Dict+Leet")
  1026. << "p455w0rd"
  1027. << QStringList{"Type: Dict+Leet", "\tp455w0rd"};
  1028. QTest::newRow("Dictionary(Rep)")
  1029. << "hellohello"
  1030. << QStringList{"Type: Dictionary(Rep)", "\thellohello"};
  1031. QTest::newRow("Sequence(Rep) / Dictionary")
  1032. << "456456foobar"
  1033. << QStringList{"Type: Sequence(Rep)", "Type: Dictionary", "\t456456", "\tfoobar"};
  1034. QTest::newRow("Bruteforce(Rep) / Bruteforce")
  1035. << "xzxzy"
  1036. << QStringList{"Type: Bruteforce(Rep)", "Type: Bruteforce", "\txzxz", "\ty"};
  1037. QTest::newRow("Dictionary / Date(Rep)")
  1038. << "pass20182018"
  1039. << QStringList{"Type: Dictionary", "Type: Date(Rep)", "\tpass", "\t20182018"};
  1040. QTest::newRow("Dictionary / Date / Bruteforce")
  1041. << "mypass2018-2"
  1042. << QStringList{"Type: Dictionary", "Type: Date", "Type: Bruteforce", "\tmypass", "\t2018", "\t-2"};
  1043. QTest::newRow("Strong Password")
  1044. << "E*!%.Qw{t.X,&bafw)\"Q!ah$%;U/"
  1045. << QStringList{"Type: Bruteforce", "\tE*"};
  1046. // TODO: detect passphrases and adjust entropy calculation accordingly (issue #2347)
  1047. QTest::newRow("Strong Passphrase")
  1048. << "squint wooing resupply dangle isolation axis headsman"
  1049. << QStringList{"Type: Dictionary", "Type: Bruteforce", "Multi-word extra bits 22.0", "\tsquint", "\t ", "\twooing"};
  1050. // clang-format on
  1051. }
  1052. void TestCli::testEstimate()
  1053. {
  1054. QFETCH(QString, input);
  1055. QFETCH(QStringList, searchStrings);
  1056. // Calculate expected values since zxcvbn output can vary by platform if different wordlists are used
  1057. const auto e = ZxcvbnMatch(input.toUtf8(), nullptr, nullptr);
  1058. auto length = QString::number(input.length());
  1059. auto entropy = QString("%1").arg(e, 0, 'f', 3);
  1060. auto log10 = QString("%1").arg(e * 0.301029996, 0, 'f', 3);
  1061. Estimate estimateCmd;
  1062. QVERIFY(!estimateCmd.name.isEmpty());
  1063. QVERIFY(estimateCmd.getDescriptionLine().contains(estimateCmd.name));
  1064. setInput(input);
  1065. execCmd(estimateCmd, {"estimate", "-a"});
  1066. auto result = QString(m_stdout->readAll());
  1067. QVERIFY(result.contains("Length " + length));
  1068. QVERIFY(result.contains("Entropy " + entropy));
  1069. QVERIFY(result.contains("Log10 " + log10));
  1070. for (const auto& string : asConst(searchStrings)) {
  1071. QVERIFY2(result.contains(string), qPrintable("String " + string + " missing"));
  1072. }
  1073. }
  1074. void TestCli::testExport()
  1075. {
  1076. Export exportCmd;
  1077. QVERIFY(!exportCmd.name.isEmpty());
  1078. QVERIFY(exportCmd.getDescriptionLine().contains(exportCmd.name));
  1079. setInput("a");
  1080. execCmd(exportCmd, {"export", m_dbFile->fileName()});
  1081. TemporaryFile xmlOutput;
  1082. xmlOutput.open(QIODevice::WriteOnly);
  1083. xmlOutput.write(m_stdout->readAll());
  1084. xmlOutput.close();
  1085. QScopedPointer<Database> db(new Database());
  1086. QVERIFY(db->import(xmlOutput.fileName()));
  1087. auto* entry = db->rootGroup()->findEntryByPath("/Sample Entry");
  1088. QVERIFY(entry);
  1089. QCOMPARE(entry->password(), QString("Password"));
  1090. // Quiet option
  1091. QScopedPointer<Database> dbQuiet(new Database());
  1092. setInput("a");
  1093. execCmd(exportCmd, {"export", "-f", "xml", "-q", m_dbFile->fileName()});
  1094. QCOMPARE(m_stderr->readAll(), QByteArray());
  1095. xmlOutput.open(QIODevice::WriteOnly);
  1096. xmlOutput.write(m_stdout->readAll());
  1097. xmlOutput.close();
  1098. QVERIFY(db->import(xmlOutput.fileName()));
  1099. // CSV exporting
  1100. setInput("a");
  1101. execCmd(exportCmd, {"export", "-f", "csv", m_dbFile->fileName()});
  1102. QByteArray csvHeader = m_stdout->readLine();
  1103. QVERIFY(csvHeader.contains(QByteArray("\"Group\",\"Title\",\"Username\",\"Password\",\"URL\",\"Notes\"")));
  1104. QByteArray csvData = m_stdout->readAll();
  1105. QVERIFY(csvData.contains(QByteArray(
  1106. "\"NewDatabase\",\"Sample Entry\",\"User Name\",\"Password\",\"http://www.somesite.com/\",\"Notes\"")));
  1107. // test invalid format
  1108. setInput("a");
  1109. execCmd(exportCmd, {"export", "-f", "yaml", m_dbFile->fileName()});
  1110. m_stderr->readLine(); // Skip password prompt
  1111. QCOMPARE(m_stderr->readLine(), QByteArray("Unsupported format yaml\n"));
  1112. }
  1113. void TestCli::testGenerate_data()
  1114. {
  1115. QTest::addColumn<QStringList>("parameters");
  1116. QTest::addColumn<QString>("pattern");
  1117. QTest::newRow("default") << QStringList{"generate"} << "^[^\r\n]+$";
  1118. QTest::newRow("length") << QStringList{"generate", "-L", "13"} << "^.{13}$";
  1119. QTest::newRow("lowercase") << QStringList{"generate", "-L", "14", "-l"} << "^[a-z]{14}$";
  1120. QTest::newRow("uppercase") << QStringList{"generate", "-L", "15", "--upper"} << "^[A-Z]{15}$";
  1121. QTest::newRow("numbers") << QStringList{"generate", "-L", "16", "-n"} << "^[0-9]{16}$";
  1122. QTest::newRow("special") << QStringList{"generate", "-L", "200", "-s"}
  1123. << R"(^[\(\)\[\]\{\}\.\-*|\\,:;"'\/\_!+-<=>?#$%&^`@~]{200}$)";
  1124. QTest::newRow("special (exclude)") << QStringList{"generate", "-L", "200", "-s", "-x", "+.?@&"}
  1125. << R"(^[\(\)\[\]\{\}\.\-*|\\,:;"'\/\_!-<=>#$%^`~]{200}$)";
  1126. QTest::newRow("extended") << QStringList{"generate", "-L", "50", "-e"}
  1127. << R"(^[^a-zA-Z0-9\(\)\[\]\{\}\.\-\*\|\\,:;"'\/\_!+-<=>?#$%&^`@~]{50}$)";
  1128. QTest::newRow("numbers + lowercase + uppercase")
  1129. << QStringList{"generate", "-L", "16", "-n", "--upper", "-l"} << "^[0-9a-zA-Z]{16}$";
  1130. QTest::newRow("numbers + lowercase + uppercase (exclude)")
  1131. << QStringList{"generate", "-L", "500", "-n", "-U", "-l", "-x", "abcdefg0123@"} << "^[^abcdefg0123@]{500}$";
  1132. QTest::newRow("numbers + lowercase + uppercase (exclude similar)")
  1133. << QStringList{"generate", "-L", "200", "-n", "-U", "-l", "--exclude-similar"} << "^[^l1IO0]{200}$";
  1134. QTest::newRow("uppercase + lowercase (every)")
  1135. << QStringList{"generate", "-L", "2", "--upper", "-l", "--every-group"} << "^[a-z][A-Z]|[A-Z][a-z]$";
  1136. QTest::newRow("numbers + lowercase (every)")
  1137. << QStringList{"generate", "-L", "2", "-n", "-l", "--every-group"} << "^[a-z][0-9]|[0-9][a-z]$";
  1138. QTest::newRow("custom character set")
  1139. << QStringList{"generate", "-L", "200", "-n", "-c", "abc"} << "^[abc0-9]{200}$";
  1140. QTest::newRow("custom character set without extra options uses only custom chars")
  1141. << QStringList{"generate", "-L", "200", "-c", "a"} << "^a{200}$";
  1142. }
  1143. void TestCli::testGenerate()
  1144. {
  1145. QFETCH(QStringList, parameters);
  1146. QFETCH(QString, pattern);
  1147. Generate generateCmd;
  1148. QVERIFY(!generateCmd.name.isEmpty());
  1149. QVERIFY(generateCmd.getDescriptionLine().contains(generateCmd.name));
  1150. for (int i = 0; i < 10; ++i) {
  1151. execCmd(generateCmd, parameters);
  1152. QRegularExpression regex(pattern);
  1153. #ifdef Q_OS_UNIX
  1154. QString password = QString::fromUtf8(m_stdout->readLine());
  1155. #else
  1156. QString password = QString::fromLatin1(m_stdout->readLine());
  1157. #endif
  1158. QVERIFY2(regex.match(password).hasMatch(),
  1159. qPrintable("Password " + password + " does not match pattern " + pattern));
  1160. QCOMPARE(m_stderr->readAll(), QByteArray());
  1161. }
  1162. // Testing with invalid password length
  1163. execCmd(generateCmd, {"generate", "-L", "-10"});
  1164. QCOMPARE(m_stderr->readLine(), QByteArray("Invalid password length -10\n"));
  1165. execCmd(generateCmd, {"generate", "-L", "0"});
  1166. QCOMPARE(m_stderr->readLine(), QByteArray("Invalid password length 0\n"));
  1167. // Testing with invalid word count format
  1168. execCmd(generateCmd, {"generate", "-L", "bleuh"});
  1169. QCOMPARE(m_stderr->readLine(), QByteArray("Invalid password length bleuh\n"));
  1170. }
  1171. void TestCli::testImport()
  1172. {
  1173. Import importCmd;
  1174. QVERIFY(!importCmd.name.isEmpty());
  1175. QVERIFY(importCmd.getDescriptionLine().contains(importCmd.name));
  1176. QScopedPointer<QTemporaryDir> testDir(new QTemporaryDir());
  1177. QString databaseFilename = testDir->path() + "/testImport1.kdbx";
  1178. setInput({"a", "a"});
  1179. execCmd(importCmd, {"import", m_xmlFile->fileName(), databaseFilename, "-p"});
  1180. QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
  1181. QCOMPARE(m_stderr->readLine(), QByteArray("Repeat password: \n"));
  1182. QCOMPARE(m_stdout->readLine(), QByteArray("Successfully imported database.\n"));
  1183. auto db = readDatabase(databaseFilename, "a");
  1184. QVERIFY(db);
  1185. auto* entry = db->rootGroup()->findEntryByPath("/Sample Entry 1");
  1186. QVERIFY(entry);
  1187. QCOMPARE(entry->username(), QString("User Name"));
  1188. // Should refuse to create the database if it already exists.
  1189. execCmd(importCmd, {"import", m_xmlFile->fileName(), databaseFilename});
  1190. // Output should be empty when there is an error.
  1191. QCOMPARE(m_stdout->readAll(), QByteArray());
  1192. QString errorMessage = QString("File " + databaseFilename + " already exists.\n");
  1193. QCOMPARE(m_stderr->readAll(), errorMessage.toUtf8());
  1194. // Testing import with non-existing keyfile
  1195. databaseFilename = testDir->path() + "/testImport2.kdbx";
  1196. QString keyfilePath = testDir->path() + "/keyfile.txt";
  1197. setInput({"a", "a"});
  1198. execCmd(importCmd, {"import", "-p", "-k", keyfilePath, m_xmlFile->fileName(), databaseFilename});
  1199. QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
  1200. QCOMPARE(m_stderr->readLine(), QByteArray("Repeat password: \n"));
  1201. QCOMPARE(m_stdout->readLine(), QByteArray("Successfully imported database.\n"));
  1202. db = readDatabase(databaseFilename, "a", keyfilePath);
  1203. QVERIFY(db);
  1204. // Testing import with existing keyfile
  1205. databaseFilename = testDir->path() + "/testImport3.kdbx";
  1206. setInput({"a", "a"});
  1207. execCmd(importCmd, {"import", "-p", "-k", keyfilePath, m_xmlFile->fileName(), databaseFilename});
  1208. QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
  1209. QCOMPARE(m_stderr->readLine(), QByteArray("Repeat password: \n"));
  1210. QCOMPARE(m_stdout->readLine(), QByteArray("Successfully imported database.\n"));
  1211. db = readDatabase(databaseFilename, "a", keyfilePath);
  1212. QVERIFY(db);
  1213. // Invalid decryption time (format).
  1214. databaseFilename = testDir->path() + "/testCreate_time.kdbx";
  1215. execCmd(importCmd, {"import", "-p", "-t", "NAN", m_xmlFile->fileName(), databaseFilename});
  1216. QCOMPARE(m_stdout->readAll(), QByteArray());
  1217. QCOMPARE(m_stderr->readAll(), QByteArray("Invalid decryption time NAN.\n"));
  1218. // Invalid decryption time (range).
  1219. execCmd(importCmd, {"import", "-p", "-t", "10", m_xmlFile->fileName(), databaseFilename});
  1220. QCOMPARE(m_stdout->readAll(), QByteArray());
  1221. QVERIFY(m_stderr->readAll().contains(QByteArray("Target decryption time must be between")));
  1222. int encryptionTime = 500;
  1223. // Custom encryption time
  1224. setInput({"a", "a"});
  1225. int epochBefore = QDateTime::currentMSecsSinceEpoch();
  1226. execCmd(importCmd,
  1227. {"import", "-p", "-t", QString::number(encryptionTime), m_xmlFile->fileName(), databaseFilename});
  1228. // Removing 100ms to make sure we account for changes in computation time.
  1229. QVERIFY(QDateTime::currentMSecsSinceEpoch() > (epochBefore + encryptionTime - 100));
  1230. QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
  1231. QCOMPARE(m_stderr->readLine(), QByteArray("Repeat password: \n"));
  1232. QCOMPARE(m_stdout->readLine(), QByteArray("Benchmarking key derivation function for 500ms delay.\n"));
  1233. QVERIFY(m_stdout->readLine().contains(QByteArray("rounds for key derivation function.\n")));
  1234. db = readDatabase(databaseFilename, "a");
  1235. QVERIFY(db);
  1236. // Quiet option
  1237. QScopedPointer<QTemporaryDir> testDirQuiet(new QTemporaryDir());
  1238. QString databaseFilenameQuiet = testDirQuiet->path() + "/testImport2.kdbx";
  1239. setInput({"a", "a"});
  1240. execCmd(importCmd, {"import", "-p", "-q", m_xmlFile->fileName(), databaseFilenameQuiet});
  1241. QCOMPARE(m_stderr->readLine(), QByteArray("Enter password to encrypt database (optional): \n"));
  1242. QCOMPARE(m_stderr->readLine(), QByteArray("Repeat password: \n"));
  1243. QCOMPARE(m_stdout->readLine(), QByteArray());
  1244. db = readDatabase(databaseFilenameQuiet, "a");
  1245. QVERIFY(db);
  1246. }
  1247. void TestCli::testKeyFileOption()
  1248. {
  1249. List listCmd;
  1250. QString keyFilePath(QString(KEEPASSX_TEST_DATA_DIR).append("/KeyFileProtected.key"));
  1251. setInput("a");
  1252. execCmd(listCmd, {"ls", "-k", keyFilePath, m_keyFileProtectedDbFile->fileName()});
  1253. m_stderr->readLine(); // Skip password prompt
  1254. QCOMPARE(m_stderr->readAll(), QByteArray());
  1255. QCOMPARE(m_stdout->readAll(),
  1256. QByteArray("entry1\n"
  1257. "entry2\n"));
  1258. // Should raise an error with no key file.
  1259. setInput("a");
  1260. execCmd(listCmd, {"ls", m_keyFileProtectedDbFile->fileName()});
  1261. QCOMPARE(m_stdout->readAll(), QByteArray());
  1262. QVERIFY(m_stderr->readAll().contains("Invalid credentials were provided"));
  1263. // Should raise an error if key file path is invalid.
  1264. setInput("a");
  1265. execCmd(listCmd, {"ls", "-k", "invalidpath", m_keyFileProtectedDbFile->fileName()});
  1266. m_stderr->readLine(); // skip password prompt
  1267. QCOMPARE(m_stdout->readAll(), QByteArray());
  1268. QCOMPARE(m_stderr->readAll().split(':').at(0), QByteArray("Failed to load key file invalidpath"));
  1269. }
  1270. void TestCli::testNoPasswordOption()
  1271. {
  1272. List listCmd;
  1273. QString keyFilePath(QString(KEEPASSX_TEST_DATA_DIR).append("/KeyFileProtectedNoPassword.key"));
  1274. execCmd(listCmd, {"ls", "-k", keyFilePath, "--no-password", m_keyFileProtectedNoPasswordDbFile->fileName()});
  1275. // Expecting no password prompt
  1276. QCOMPARE(m_stderr->readAll(), QByteArray());
  1277. QCOMPARE(m_stdout->readAll(),
  1278. QByteArray("entry1\n"
  1279. "entry2\n"));
  1280. // Should raise an error with no key file.
  1281. execCmd(listCmd, {"ls", "--no-password", m_keyFileProtectedNoPasswordDbFile->fileName()});
  1282. QCOMPARE(m_stdout->readAll(), QByteArray());
  1283. QVERIFY(m_stderr->readAll().contains("Invalid credentials were provided"));
  1284. }
  1285. void TestCli::testList()
  1286. {
  1287. List listCmd;
  1288. QVERIFY(!listCmd.name.isEmpty());
  1289. QVERIFY(listCmd.getDescriptionLine().contains(listCmd.name));
  1290. setInput("a");
  1291. execCmd(listCmd, {"ls", m_dbFile->fileName()});
  1292. m_stderr->readLine(); // Skip password prompt
  1293. QCOMPARE(m_stderr->readAll(), QByteArray());
  1294. QCOMPARE(m_stdout->readAll(),
  1295. QByteArray("Sample Entry\n"
  1296. "General/\n"
  1297. "Windows/\n"
  1298. "Network/\n"
  1299. "Internet/\n"
  1300. "eMail/\n"
  1301. "Homebanking/\n"));
  1302. // Quiet option
  1303. setInput("a");
  1304. execCmd(listCmd, {"ls", "-q", m_dbFile->fileName()});
  1305. QCOMPARE(m_stderr->readAll(), QByteArray());
  1306. QCOMPARE(m_stdout->readAll(),
  1307. QByteArray("Sample Entry\n"
  1308. "General/\n"
  1309. "Windows/\n"
  1310. "Network/\n"
  1311. "Internet/\n"
  1312. "eMail/\n"
  1313. "Homebanking/\n"));
  1314. setInput("a");
  1315. execCmd(listCmd, {"ls", "-R", m_dbFile->fileName()});
  1316. QCOMPARE(m_stdout->readAll(),
  1317. QByteArray("Sample Entry\n"
  1318. "General/\n"
  1319. " [empty]\n"
  1320. "Windows/\n"
  1321. " [empty]\n"
  1322. "Network/\n"
  1323. " [empty]\n"
  1324. "Internet/\n"
  1325. " [empty]\n"
  1326. "eMail/\n"
  1327. " [empty]\n"
  1328. "Homebanking/\n"
  1329. " Subgroup/\n"
  1330. " Subgroup Entry\n"));
  1331. setInput("a");
  1332. execCmd(listCmd, {"ls", "-R", "-f", m_dbFile->fileName()});
  1333. QCOMPARE(m_stdout->readAll(),
  1334. QByteArray("Sample Entry\n"
  1335. "General/\n"
  1336. "General/[empty]\n"
  1337. "Windows/\n"
  1338. "Windows/[empty]\n"
  1339. "Network/\n"
  1340. "Network/[empty]\n"
  1341. "Internet/\n"
  1342. "Internet/[empty]\n"
  1343. "eMail/\n"
  1344. "eMail/[empty]\n"
  1345. "Homebanking/\n"
  1346. "Homebanking/Subgroup/\n"
  1347. "Homebanking/Subgroup/Subgroup Entry\n"));
  1348. setInput("a");
  1349. execCmd(listCmd, {"ls", "-R", "-f", m_dbFile->fileName(), "/Homebanking"});
  1350. QCOMPARE(m_stdout->readAll(),
  1351. QByteArray("Subgroup/\n"
  1352. "Subgroup/Subgroup Entry\n"));
  1353. setInput("a");
  1354. execCmd(listCmd, {"ls", m_dbFile->fileName(), "/General/"});
  1355. QCOMPARE(m_stdout->readAll(), QByteArray("[empty]\n"));
  1356. setInput("a");
  1357. execCmd(listCmd, {"ls", m_dbFile->fileName(), "/DoesNotExist/"});
  1358. m_stderr->readLine(); // skip password prompt
  1359. QCOMPARE(m_stderr->readAll(), QByteArray("Cannot find group /DoesNotExist/.\n"));
  1360. QCOMPARE(m_stdout->readAll(), QByteArray());
  1361. }
  1362. void TestCli::testMerge()
  1363. {
  1364. Merge mergeCmd;
  1365. QVERIFY(!mergeCmd.name.isEmpty());
  1366. QVERIFY(mergeCmd.getDescriptionLine().contains(mergeCmd.name));
  1367. // load test database and save copies
  1368. auto db = readDatabase();
  1369. QVERIFY(db);
  1370. TemporaryFile targetFile1;
  1371. targetFile1.open();
  1372. targetFile1.close();
  1373. TemporaryFile targetFile2;
  1374. targetFile2.open();
  1375. targetFile2.close();
  1376. TemporaryFile targetFile3;
  1377. targetFile3.open();
  1378. targetFile3.close();
  1379. db->saveAs(targetFile1.fileName());
  1380. db->saveAs(targetFile2.fileName());
  1381. // save another copy with a different password
  1382. auto oldKey = db->key();
  1383. auto key = QSharedPointer<CompositeKey>::create();
  1384. key->addKey(QSharedPointer<PasswordKey>::create("b"));
  1385. db->setKey(key);
  1386. db->saveAs(targetFile3.fileName());
  1387. // Restore the original password
  1388. db->setKey(oldKey);
  1389. // then add a new entry to the in-memory database and save another copy
  1390. auto* entry = new Entry();
  1391. entry->setUuid(QUuid::createUuid());
  1392. entry->setTitle("Some Website");
  1393. entry->setPassword("secretsecretsecret");
  1394. auto* group = db->rootGroup()->findGroupByPath("/Internet/");
  1395. QVERIFY(group);
  1396. group->addEntry(entry);
  1397. TemporaryFile sourceFile;
  1398. sourceFile.open();
  1399. sourceFile.close();
  1400. db->saveAs(sourceFile.fileName());
  1401. setInput("a");
  1402. execCmd(mergeCmd, {"merge", "-s", targetFile1.fileName(), sourceFile.fileName()});
  1403. m_stderr->readLine(); // Skip password prompt
  1404. QCOMPARE(m_stderr->readAll(), QByteArray());
  1405. QList<QByteArray> outLines1 = m_stdout->readAll().split('\n');
  1406. QVERIFY(outLines1.at(0).contains("Overwriting Internet"));
  1407. QVERIFY(outLines1.at(1).contains("Creating missing Some Website"));
  1408. QCOMPARE(outLines1.at(2),
  1409. QString("Successfully merged %1 into %2.").arg(sourceFile.fileName(), targetFile1.fileName()).toUtf8());
  1410. auto mergedDb = QSharedPointer<Database>::create();
  1411. QVERIFY(mergedDb->open(targetFile1.fileName(), oldKey));
  1412. auto* entry1 = mergedDb->rootGroup()->findEntryByPath("/Internet/Some Website");
  1413. QVERIFY(entry1);
  1414. QCOMPARE(entry1->title(), QString("Some Website"));
  1415. QCOMPARE(entry1->password(), QString("secretsecretsecret"));
  1416. // the dry run option should not modify the target database.
  1417. setInput("a");
  1418. execCmd(mergeCmd, {"merge", "--dry-run", "-s", targetFile2.fileName(), sourceFile.fileName()});
  1419. QList<QByteArray> outLines2 = m_stdout->readAll().split('\n');
  1420. QVERIFY(outLines2.at(0).contains("Overwriting Internet"));
  1421. QVERIFY(outLines2.at(1).contains("Creating missing Some Website"));
  1422. QCOMPARE(outLines2.at(2), QByteArray("Database was not modified by merge operation."));
  1423. mergedDb = QSharedPointer<Database>::create();
  1424. QVERIFY(mergedDb->open(targetFile2.fileName(), oldKey));
  1425. entry1 = mergedDb->rootGroup()->findEntryByPath("/Internet/Some Website");
  1426. QVERIFY(!entry1);
  1427. // the dry run option can be used with the quiet option
  1428. setInput("a");
  1429. execCmd(mergeCmd, {"merge", "--dry-run", "-s", "-q", targetFile2.fileName(), sourceFile.fileName()});
  1430. QCOMPARE(m_stderr->readAll(), QByteArray());
  1431. QCOMPARE(m_stdout->readAll(), QByteArray());
  1432. mergedDb = QSharedPointer<Database>::create();
  1433. QVERIFY(mergedDb->open(targetFile2.fileName(), oldKey));
  1434. entry1 = mergedDb->rootGroup()->findEntryByPath("/Internet/Some Website");
  1435. QVERIFY(!entry1);
  1436. // try again with different passwords for both files
  1437. setInput({"b", "a"});
  1438. execCmd(mergeCmd, {"merge", targetFile3.fileName(), sourceFile.fileName()});
  1439. QList<QByteArray> outLines3 = m_stdout->readAll().split('\n');
  1440. QCOMPARE(outLines3.at(2),
  1441. QString("Successfully merged %1 into %2.").arg(sourceFile.fileName(), targetFile3.fileName()).toUtf8());
  1442. mergedDb = QSharedPointer<Database>::create();
  1443. QVERIFY(mergedDb->open(targetFile3.fileName(), key));
  1444. entry1 = mergedDb->rootGroup()->findEntryByPath("/Internet/Some Website");
  1445. QVERIFY(entry1);
  1446. QCOMPARE(entry1->title(), QString("Some Website"));
  1447. QCOMPARE(entry1->password(), QString("secretsecretsecret"));
  1448. // making sure that the message is different if the database was not
  1449. // modified by the merge operation.
  1450. setInput("a");
  1451. execCmd(mergeCmd, {"merge", "-s", sourceFile.fileName(), sourceFile.fileName()});
  1452. QCOMPARE(m_stdout->readAll(), QByteArray("Database was not modified by merge operation.\n"));
  1453. // Quiet option
  1454. setInput("a");
  1455. execCmd(mergeCmd, {"merge", "-q", "-s", sourceFile.fileName(), sourceFile.fileName()});
  1456. QCOMPARE(m_stderr->readAll(), QByteArray());
  1457. QCOMPARE(m_stdout->readAll(), QByteArray());
  1458. // Quiet option without the -s option
  1459. setInput({"a", "a"});
  1460. execCmd(mergeCmd, {"merge", "-q", sourceFile.fileName(), sourceFile.fileName()});
  1461. QCOMPARE(m_stderr->readAll(), QByteArray());
  1462. QCOMPARE(m_stdout->readAll(), QByteArray());
  1463. }
  1464. void TestCli::testMergeWithKeys()
  1465. {
  1466. DatabaseCreate createCmd;
  1467. QVERIFY(!createCmd.name.isEmpty());
  1468. QVERIFY(createCmd.getDescriptionLine().contains(createCmd.name));
  1469. Merge mergeCmd;
  1470. QVERIFY(!mergeCmd.name.isEmpty());
  1471. QVERIFY(mergeCmd.getDescriptionLine().contains(mergeCmd.name));
  1472. QScopedPointer<QTemporaryDir> testDir(new QTemporaryDir());
  1473. QString sourceDatabaseFilename = testDir->path() + "/testSourceDatabase.kdbx";
  1474. QString sourceKeyfilePath = testDir->path() + "/testSourceKeyfile.txt";
  1475. QString targetDatabaseFilename = testDir->path() + "/testTargetDatabase.kdbx";
  1476. QString targetKeyfilePath = testDir->path() + "/testTargetKeyfile.txt";
  1477. setInput({"a", "a"});
  1478. execCmd(createCmd, {"db-create", sourceDatabaseFilename, "-p", "-k", sourceKeyfilePath});
  1479. setInput({"b", "b"});
  1480. execCmd(createCmd, {"db-create", targetDatabaseFilename, "-p", "-k", targetKeyfilePath});
  1481. auto sourceDatabase = readDatabase(sourceDatabaseFilename, "a", sourceKeyfilePath);
  1482. QVERIFY(sourceDatabase);
  1483. auto targetDatabase = readDatabase(targetDatabaseFilename, "b", targetKeyfilePath);
  1484. QVERIFY(targetDatabase);
  1485. auto* rootGroup = new Group();
  1486. rootGroup->setName("root");
  1487. rootGroup->setUuid(QUuid::createUuid());
  1488. auto* group = new Group();
  1489. group->setUuid(QUuid::createUuid());
  1490. group->setParent(rootGroup);
  1491. group->setName("Internet");
  1492. auto* entry = new Entry();
  1493. entry->setUuid(QUuid::createUuid());
  1494. entry->setTitle("Some Website");
  1495. entry->setPassword("secretsecretsecret");
  1496. group->addEntry(entry);
  1497. auto oldGroup = sourceDatabase->setRootGroup(rootGroup);
  1498. delete oldGroup;
  1499. auto* otherRootGroup = new Group();
  1500. otherRootGroup->setName("root");
  1501. otherRootGroup->setUuid(QUuid::createUuid());
  1502. auto* otherGroup = new Group();
  1503. otherGroup->setUuid(QUuid::createUuid());
  1504. otherGroup->setParent(otherRootGroup);
  1505. otherGroup->setName("Internet");
  1506. auto* otherEntry = new Entry();
  1507. otherEntry->setUuid(QUuid::createUuid());
  1508. otherEntry->setTitle("Some Website 2");
  1509. otherEntry->setPassword("secretsecretsecret 2");
  1510. otherGroup->addEntry(otherEntry);
  1511. oldGroup = targetDatabase->setRootGroup(otherRootGroup);
  1512. delete oldGroup;
  1513. sourceDatabase->saveAs(sourceDatabaseFilename);
  1514. targetDatabase->saveAs(targetDatabaseFilename);
  1515. setInput({"b", "a"});
  1516. execCmd(mergeCmd,
  1517. {"merge",
  1518. "-k",
  1519. targetKeyfilePath,
  1520. "--key-file-from",
  1521. sourceKeyfilePath,
  1522. targetDatabaseFilename,
  1523. sourceDatabaseFilename});
  1524. QList<QByteArray> lines = m_stdout->readAll().split('\n');
  1525. QVERIFY(lines.contains(
  1526. QString("Successfully merged %1 into %2.").arg(sourceDatabaseFilename, targetDatabaseFilename).toUtf8()));
  1527. }
  1528. void TestCli::testMove()
  1529. {
  1530. Move moveCmd;
  1531. QVERIFY(!moveCmd.name.isEmpty());
  1532. QVERIFY(moveCmd.getDescriptionLine().contains(moveCmd.name));
  1533. setInput("a");
  1534. execCmd(moveCmd, {"mv", m_dbFile->fileName(), "invalid_entry_path", "invalid_group_path"});
  1535. m_stderr->readLine(); // skip password prompt
  1536. QCOMPARE(m_stderr->readLine(), QByteArray("Could not find entry with path invalid_entry_path.\n"));
  1537. QCOMPARE(m_stdout->readLine(), QByteArray());
  1538. setInput("a");
  1539. execCmd(moveCmd, {"mv", m_dbFile->fileName(), "Sample Entry", "invalid_group_path"});
  1540. m_stderr->readLine(); // skip password prompt
  1541. QCOMPARE(m_stderr->readLine(), QByteArray("Could not find group with path invalid_group_path.\n"));
  1542. QCOMPARE(m_stdout->readLine(), QByteArray());
  1543. setInput("a");
  1544. execCmd(moveCmd, {"mv", m_dbFile->fileName(), "Sample Entry", "General/"});
  1545. m_stderr->readLine(); // skip password prompt
  1546. QCOMPARE(m_stderr->readLine(), QByteArray());
  1547. QCOMPARE(m_stdout->readLine(), QByteArray("Successfully moved entry Sample Entry to group General/.\n"));
  1548. auto db = readDatabase();
  1549. auto* entry = db->rootGroup()->findEntryByPath("General/Sample Entry");
  1550. QVERIFY(entry);
  1551. // Test that not modified if the same group is destination.
  1552. setInput("a");
  1553. execCmd(moveCmd, {"mv", m_dbFile->fileName(), "General/Sample Entry", "General/"});
  1554. m_stderr->readLine(); // skip password prompt
  1555. QCOMPARE(m_stderr->readLine(), QByteArray("Entry is already in group General/.\n"));
  1556. QCOMPARE(m_stdout->readLine(), QByteArray());
  1557. // sanity check
  1558. db = readDatabase();
  1559. entry = db->rootGroup()->findEntryByPath("General/Sample Entry");
  1560. QVERIFY(entry);
  1561. }
  1562. void TestCli::testRemove()
  1563. {
  1564. Remove removeCmd;
  1565. QVERIFY(!removeCmd.name.isEmpty());
  1566. QVERIFY(removeCmd.getDescriptionLine().contains(removeCmd.name));
  1567. // load test database and save a copy with disabled recycle bin
  1568. auto db = readDatabase();
  1569. QVERIFY(db);
  1570. TemporaryFile fileCopy;
  1571. fileCopy.open();
  1572. fileCopy.close();
  1573. db->metadata()->setRecycleBinEnabled(false);
  1574. db->saveAs(fileCopy.fileName());
  1575. // delete entry and verify
  1576. setInput("a");
  1577. execCmd(removeCmd, {"rm", m_dbFile->fileName(), "/Sample Entry"});
  1578. m_stderr->readLine(); // skip password prompt
  1579. QCOMPARE(m_stderr->readAll(), QByteArray());
  1580. QCOMPARE(m_stdout->readAll(), QByteArray("Successfully recycled entry Sample Entry.\n"));
  1581. auto readBackDb = readDatabase();
  1582. QVERIFY(readBackDb);
  1583. QVERIFY(!readBackDb->rootGroup()->findEntryByPath("/Sample Entry"));
  1584. QVERIFY(readBackDb->rootGroup()->findEntryByPath(QString("/%1/Sample Entry").arg(Group::tr("Recycle Bin"))));
  1585. // try again, this time without recycle bin
  1586. setInput("a");
  1587. execCmd(removeCmd, {"rm", fileCopy.fileName(), "/Sample Entry"});
  1588. m_stderr->readLine(); // skip password prompt
  1589. QCOMPARE(m_stdout->readAll(), QByteArray("Successfully deleted entry Sample Entry.\n"));
  1590. readBackDb = readDatabase(fileCopy.fileName(), "a");
  1591. QVERIFY(readBackDb);
  1592. QVERIFY(!readBackDb->rootGroup()->findEntryByPath("/Sample Entry"));
  1593. QVERIFY(!readBackDb->rootGroup()->findEntryByPath(QString("/%1/Sample Entry").arg(Group::tr("Recycle Bin"))));
  1594. // finally, try deleting a non-existent entry
  1595. setInput("a");
  1596. execCmd(removeCmd, {"rm", fileCopy.fileName(), "/Sample Entry"});
  1597. m_stderr->readLine(); // skip password prompt
  1598. QCOMPARE(m_stderr->readAll(), QByteArray("Entry /Sample Entry not found.\n"));
  1599. QCOMPARE(m_stdout->readAll(), QByteArray());
  1600. // try deleting a directory, should fail
  1601. setInput("a");
  1602. execCmd(removeCmd, {"rm", fileCopy.fileName(), "/General"});
  1603. m_stderr->readLine(); // skip password prompt
  1604. QCOMPARE(m_stderr->readAll(), QByteArray("Entry /General not found.\n"));
  1605. QCOMPARE(m_stdout->readAll(), QByteArray());
  1606. }
  1607. void TestCli::testRemoveGroup()
  1608. {
  1609. RemoveGroup removeGroupCmd;
  1610. QVERIFY(!removeGroupCmd.name.isEmpty());
  1611. QVERIFY(removeGroupCmd.getDescriptionLine().contains(removeGroupCmd.name));
  1612. // try deleting a directory, should recycle it first.
  1613. setInput("a");
  1614. execCmd(removeGroupCmd, {"rmdir", m_dbFile->fileName(), "/General"});
  1615. m_stderr->readLine(); // skip password prompt
  1616. QCOMPARE(m_stderr->readAll(), QByteArray());
  1617. QCOMPARE(m_stdout->readAll(), QByteArray("Successfully recycled group /General.\n"));
  1618. auto db = readDatabase();
  1619. auto* group = db->rootGroup()->findGroupByPath("General");
  1620. QVERIFY(!group);
  1621. // try deleting a directory again, should delete it permanently.
  1622. setInput("a");
  1623. execCmd(removeGroupCmd, {"rmdir", m_dbFile->fileName(), "Recycle Bin/General"});
  1624. m_stderr->readLine(); // skip password prompt
  1625. QCOMPARE(m_stderr->readAll(), QByteArray());
  1626. QCOMPARE(m_stdout->readAll(), QByteArray("Successfully deleted group Recycle Bin/General.\n"));
  1627. db = readDatabase();
  1628. group = db->rootGroup()->findGroupByPath("Recycle Bin/General");
  1629. QVERIFY(!group);
  1630. // try deleting an invalid group, should fail.
  1631. setInput("a");
  1632. execCmd(removeGroupCmd, {"rmdir", m_dbFile->fileName(), "invalid"});
  1633. m_stderr->readLine(); // skip password prompt
  1634. QCOMPARE(m_stderr->readAll(), QByteArray("Group invalid not found.\n"));
  1635. QCOMPARE(m_stdout->readAll(), QByteArray());
  1636. // Should fail to remove the root group.
  1637. setInput("a");
  1638. execCmd(removeGroupCmd, {"rmdir", m_dbFile->fileName(), "/"});
  1639. m_stderr->readLine(); // skip password prompt
  1640. QCOMPARE(m_stderr->readAll(), QByteArray("Cannot remove root group from database.\n"));
  1641. QCOMPARE(m_stdout->readAll(), QByteArray());
  1642. }
  1643. void TestCli::testRemoveQuiet()
  1644. {
  1645. Remove removeCmd;
  1646. QVERIFY(!removeCmd.name.isEmpty());
  1647. QVERIFY(removeCmd.getDescriptionLine().contains(removeCmd.name));
  1648. // delete entry and verify
  1649. setInput("a");
  1650. execCmd(removeCmd, {"rm", "-q", m_dbFile->fileName(), "/Sample Entry"});
  1651. QCOMPARE(m_stderr->readAll(), QByteArray());
  1652. QCOMPARE(m_stdout->readAll(), QByteArray());
  1653. auto db = readDatabase();
  1654. QVERIFY(db);
  1655. QVERIFY(!db->rootGroup()->findEntryByPath("/Sample Entry"));
  1656. QVERIFY(db->rootGroup()->findEntryByPath(QString("/%1/Sample Entry").arg(Group::tr("Recycle Bin"))));
  1657. // remove the entry completely
  1658. setInput("a");
  1659. execCmd(removeCmd, {"rm", "-q", m_dbFile->fileName(), QString("/%1/Sample Entry").arg(Group::tr("Recycle Bin"))});
  1660. QCOMPARE(m_stderr->readAll(), QByteArray());
  1661. QCOMPARE(m_stdout->readAll(), QByteArray());
  1662. db = readDatabase();
  1663. QVERIFY(!db->rootGroup()->findEntryByPath("/Sample Entry"));
  1664. QVERIFY(!db->rootGroup()->findEntryByPath(QString("/%1/Sample Entry").arg(Group::tr("Recycle Bin"))));
  1665. }
  1666. void TestCli::testSearch()
  1667. {
  1668. Search searchCmd;
  1669. QVERIFY(!searchCmd.name.isEmpty());
  1670. QVERIFY(searchCmd.getDescriptionLine().contains(searchCmd.name));
  1671. setInput("a");
  1672. execCmd(searchCmd, {"search", m_dbFile->fileName(), "Sample"});
  1673. m_stderr->readLine(); // Skip password prompt
  1674. QCOMPARE(m_stderr->readAll(), QByteArray());
  1675. QCOMPARE(m_stdout->readAll(), QByteArray("/Sample Entry\n"));
  1676. // Quiet option
  1677. setInput("a");
  1678. execCmd(searchCmd, {"search", m_dbFile->fileName(), "-q", "Sample"});
  1679. QCOMPARE(m_stderr->readAll(), QByteArray());
  1680. QCOMPARE(m_stdout->readAll(), QByteArray("/Sample Entry\n"));
  1681. setInput("a");
  1682. execCmd(searchCmd, {"search", m_dbFile->fileName(), "Does Not Exist"});
  1683. m_stderr->readLine(); // skip password prompt
  1684. QCOMPARE(m_stderr->readAll(), QByteArray("No results for that search term.\n"));
  1685. QCOMPARE(m_stdout->readAll(), QByteArray());
  1686. // write a modified database
  1687. auto db = readDatabase();
  1688. QVERIFY(db);
  1689. auto* group = db->rootGroup()->findGroupByPath("/General/");
  1690. QVERIFY(group);
  1691. auto* entry = new Entry();
  1692. entry->setUuid(QUuid::createUuid());
  1693. entry->setTitle("New Entry");
  1694. group->addEntry(entry);
  1695. TemporaryFile tmpFile;
  1696. tmpFile.open();
  1697. tmpFile.close();
  1698. db->saveAs(tmpFile.fileName());
  1699. setInput("a");
  1700. execCmd(searchCmd, {"search", tmpFile.fileName(), "title:New"});
  1701. QCOMPARE(m_stdout->readAll(), QByteArray("/General/New Entry\n"));
  1702. setInput("a");
  1703. execCmd(searchCmd, {"search", tmpFile.fileName(), "title:Entry"});
  1704. QCOMPARE(m_stdout->readAll(),
  1705. QByteArray("/Sample Entry\n/General/New Entry\n/Homebanking/Subgroup/Subgroup Entry\n"));
  1706. setInput("a");
  1707. execCmd(searchCmd, {"search", tmpFile.fileName(), "group:General"});
  1708. QCOMPARE(m_stdout->readAll(), QByteArray("/General/New Entry\n"));
  1709. setInput("a");
  1710. execCmd(searchCmd, {"search", tmpFile.fileName(), "group:NewDatabase"});
  1711. QCOMPARE(m_stdout->readAll(), QByteArray("/Sample Entry\n"));
  1712. setInput("a");
  1713. execCmd(searchCmd, {"search", tmpFile.fileName(), "group:/NewDatabase"});
  1714. QCOMPARE(m_stdout->readAll(),
  1715. QByteArray("/Sample Entry\n/General/New Entry\n/Homebanking/Subgroup/Subgroup Entry\n"));
  1716. setInput("a");
  1717. execCmd(searchCmd, {"search", tmpFile.fileName(), "url:bank"});
  1718. QCOMPARE(m_stdout->readAll(), QByteArray("/Homebanking/Subgroup/Subgroup Entry\n"));
  1719. setInput("a");
  1720. execCmd(searchCmd, {"search", tmpFile.fileName(), "u:User Name"});
  1721. QCOMPARE(m_stdout->readAll(), QByteArray("/Sample Entry\n/Homebanking/Subgroup/Subgroup Entry\n"));
  1722. }
  1723. void TestCli::testShow()
  1724. {
  1725. Show showCmd;
  1726. QVERIFY(!showCmd.name.isEmpty());
  1727. QVERIFY(showCmd.getDescriptionLine().contains(showCmd.name));
  1728. setInput("a");
  1729. execCmd(showCmd, {"show", m_dbFile->fileName(), "/Sample Entry"});
  1730. m_stderr->readLine(); // Skip password prompt
  1731. QCOMPARE(m_stderr->readAll(), QByteArray());
  1732. QCOMPARE(m_stdout->readAll(),
  1733. QByteArray("Title: Sample Entry\n"
  1734. "UserName: User Name\n"
  1735. "Password: PROTECTED\n"
  1736. "URL: http://www.somesite.com/\n"
  1737. "Notes: Notes\n"
  1738. "Uuid: {9f4544c2-ab00-c74a-8a1a-6eaf26cf57e9}\n"
  1739. "Tags: \n"));
  1740. setInput("a");
  1741. execCmd(showCmd, {"show", "-s", m_dbFile->fileName(), "/Sample Entry"});
  1742. QCOMPARE(m_stdout->readAll(),
  1743. QByteArray("Title: Sample Entry\n"
  1744. "UserName: User Name\n"
  1745. "Password: Password\n"
  1746. "URL: http://www.somesite.com/\n"
  1747. "Notes: Notes\n"
  1748. "Uuid: {9f4544c2-ab00-c74a-8a1a-6eaf26cf57e9}\n"
  1749. "Tags: \n"));
  1750. setInput("a");
  1751. execCmd(showCmd, {"show", m_dbFile->fileName(), "-q", "/Sample Entry"});
  1752. QCOMPARE(m_stderr->readAll(), QByteArray());
  1753. QCOMPARE(m_stdout->readAll(),
  1754. QByteArray("Title: Sample Entry\n"
  1755. "UserName: User Name\n"
  1756. "Password: PROTECTED\n"
  1757. "URL: http://www.somesite.com/\n"
  1758. "Notes: Notes\n"
  1759. "Uuid: {9f4544c2-ab00-c74a-8a1a-6eaf26cf57e9}\n"
  1760. "Tags: \n"));
  1761. setInput("a");
  1762. execCmd(showCmd, {"show", m_dbFile->fileName(), "--show-attachments", "/Sample Entry"});
  1763. m_stderr->readLine(); // Skip password prompt
  1764. QCOMPARE(m_stderr->readAll(), QByteArray());
  1765. QCOMPARE(m_stdout->readAll(),
  1766. QByteArray("Title: Sample Entry\n"
  1767. "UserName: User Name\n"
  1768. "Password: PROTECTED\n"
  1769. "URL: http://www.somesite.com/\n"
  1770. "Notes: Notes\n"
  1771. "Uuid: {9f4544c2-ab00-c74a-8a1a-6eaf26cf57e9}\n"
  1772. "Tags: \n"
  1773. "\n"
  1774. "Attachments:\n"
  1775. " Sample attachment.txt (15 B)\n"));
  1776. setInput("a");
  1777. execCmd(showCmd, {"show", m_dbFile->fileName(), "--show-attachments", "/Homebanking/Subgroup/Subgroup Entry"});
  1778. m_stderr->readLine(); // Skip password prompt
  1779. QCOMPARE(m_stderr->readAll(), QByteArray());
  1780. QCOMPARE(m_stdout->readAll(),
  1781. QByteArray("Title: Subgroup Entry\n"
  1782. "UserName: Bank User Name\n"
  1783. "Password: PROTECTED\n"
  1784. "URL: https://www.bank.com\n"
  1785. "Notes: Important note\n"
  1786. "Uuid: {20b183fd-6878-4506-a50b-06d30792aa10}\n"
  1787. "Tags: \n"
  1788. "\n"
  1789. "No attachments present.\n"));
  1790. setInput("a");
  1791. execCmd(showCmd, {"show", "-a", "Title", m_dbFile->fileName(), "/Sample Entry"});
  1792. QCOMPARE(m_stdout->readAll(), QByteArray("Sample Entry\n"));
  1793. setInput("a");
  1794. execCmd(showCmd, {"show", "-a", "Password", m_dbFile->fileName(), "/Sample Entry"});
  1795. QCOMPARE(m_stdout->readAll(), QByteArray("Password\n"));
  1796. setInput("a");
  1797. execCmd(showCmd, {"show", "-a", "Uuid", m_dbFile->fileName(), "/Sample Entry"});
  1798. QCOMPARE(m_stdout->readAll(), QByteArray("{9f4544c2-ab00-c74a-8a1a-6eaf26cf57e9}\n"));
  1799. setInput("a");
  1800. execCmd(showCmd, {"show", "-a", "Title", "-a", "URL", m_dbFile->fileName(), "/Sample Entry"});
  1801. QCOMPARE(m_stdout->readAll(),
  1802. QByteArray("Sample Entry\n"
  1803. "http://www.somesite.com/\n"));
  1804. // Test case insensitivity
  1805. setInput("a");
  1806. execCmd(showCmd, {"show", "-a", "TITLE", "-a", "URL", m_dbFile->fileName(), "/Sample Entry"});
  1807. QCOMPARE(m_stdout->readAll(),
  1808. QByteArray("Sample Entry\n"
  1809. "http://www.somesite.com/\n"));
  1810. setInput("a");
  1811. execCmd(showCmd, {"show", "-a", "DoesNotExist", m_dbFile->fileName(), "/Sample Entry"});
  1812. QCOMPARE(m_stdout->readAll(), QByteArray());
  1813. QVERIFY(m_stderr->readAll().contains("ERROR: unknown attribute DoesNotExist.\n"));
  1814. setInput("a");
  1815. execCmd(showCmd, {"show", "-t", m_dbFile->fileName(), "/Sample Entry"});
  1816. QVERIFY(isTotp(m_stdout->readAll()));
  1817. setInput("a");
  1818. execCmd(showCmd, {"show", "-a", "Title", m_dbFile->fileName(), "--totp", "/Sample Entry"});
  1819. QCOMPARE(m_stdout->readLine(), QByteArray("Sample Entry\n"));
  1820. QVERIFY(isTotp(m_stdout->readAll()));
  1821. setInput("a");
  1822. execCmd(showCmd, {"show", m_dbFile2->fileName(), "--totp", "/Sample Entry"});
  1823. QCOMPARE(m_stdout->readAll(), QByteArray());
  1824. QVERIFY(m_stderr->readAll().contains("Entry with path /Sample Entry has no TOTP set up.\n"));
  1825. // Show with ambiguous attributes
  1826. setInput("a");
  1827. execCmd(showCmd, {"show", m_dbFile->fileName(), "-a", "Testattribute1", "/Sample Entry"});
  1828. QCOMPARE(m_stdout->readAll(), QByteArray());
  1829. QVERIFY(m_stderr->readAll().contains("ERROR: attribute Testattribute1 is ambiguous"));
  1830. setInput("a");
  1831. execCmd(showCmd, {"show", "--all", m_dbFile->fileName(), "/Sample Entry"});
  1832. QCOMPARE(m_stdout->readAll(),
  1833. QByteArray("Title: Sample Entry\n"
  1834. "UserName: User Name\n"
  1835. "Password: PROTECTED\n"
  1836. "URL: http://www.somesite.com/\n"
  1837. "Notes: Notes\n"
  1838. "Uuid: {9f4544c2-ab00-c74a-8a1a-6eaf26cf57e9}\n"
  1839. "Tags: \n"
  1840. "TOTP Seed: PROTECTED\n"
  1841. "TOTP Settings: 30;6\n"
  1842. "TestAttribute1: b\n"
  1843. "testattribute1: a\n"));
  1844. }
  1845. void TestCli::testInvalidDbFiles()
  1846. {
  1847. Show showCmd;
  1848. QString nonExistentDbPath("/foo/bar/baz");
  1849. QString directoryName("/");
  1850. execCmd(showCmd, {"show", nonExistentDbPath, "/Sample Entry"});
  1851. QCOMPARE(QString(m_stderr->readAll()),
  1852. QObject::tr("Failed to open database file %1: not found").arg(nonExistentDbPath) + "\n");
  1853. QCOMPARE(m_stdout->readAll(), QByteArray());
  1854. execCmd(showCmd, {"show", directoryName, "whatever"});
  1855. QCOMPARE(QString(m_stderr->readAll()),
  1856. QObject::tr("Failed to open database file %1: not a plain file").arg(directoryName) + "\n");
  1857. // Create a write-only file and try to open it.
  1858. // QFileInfo.isReadable returns 'true' on Windows, even after the call to
  1859. // setPermissions(WriteOwner) and with NTFS permissions enabled, so this
  1860. // check doesn't work.
  1861. #if !defined(Q_OS_WIN)
  1862. QTemporaryFile tempFile;
  1863. QVERIFY(tempFile.open());
  1864. QString path = QFileInfo(tempFile).absoluteFilePath();
  1865. QVERIFY(tempFile.setPermissions(QFileDevice::WriteOwner));
  1866. execCmd(showCmd, {"show", path, "some entry"});
  1867. QCOMPARE(QString(m_stderr->readAll()),
  1868. QObject::tr("Failed to open database file %1: not readable").arg(path) + "\n");
  1869. #endif // Q_OS_WIN
  1870. }
  1871. /**
  1872. * Secret key for the YubiKey slot used by the unit test is
  1873. * 1c e3 0f d7 8d 20 dc fa 40 b5 0c 18 77 9a fb 0f 02 28 8d b7
  1874. * This secret can be on either slot but must be passive.
  1875. */
  1876. void TestCli::testYubiKeyOption()
  1877. {
  1878. if (!YubiKey::instance()->isInitialized()) {
  1879. QSKIP("Unable to initialize YubiKey interface.");
  1880. }
  1881. YubiKey::instance()->findValidKeys();
  1882. const auto keys = YubiKey::instance()->foundKeys().keys();
  1883. if (keys.isEmpty()) {
  1884. QSKIP("No YubiKey devices were detected.");
  1885. }
  1886. bool wouldBlock = false;
  1887. QByteArray challenge("CLITest");
  1888. Botan::secure_vector<char> response;
  1889. QByteArray expected("\xA2\x3B\x94\x00\xBE\x47\x9A\x30\xA9\xEB\x50\x9B\x85\x56\x5B\x6B\x30\x25\xB4\x8E", 20);
  1890. // Find a key that as configured for this test
  1891. YubiKeySlot pKey(0, 0);
  1892. for (auto key : keys) {
  1893. if (YubiKey::instance()->testChallenge(key, &wouldBlock) && !wouldBlock) {
  1894. YubiKey::instance()->challenge(key, challenge, response);
  1895. if (std::memcmp(response.data(), expected.data(), expected.size()) == 0) {
  1896. pKey = key;
  1897. break;
  1898. }
  1899. Tools::wait(100);
  1900. }
  1901. }
  1902. if (pKey.first == 0 && pKey.second == 0) {
  1903. QSKIP("No YubiKey is properly configured to perform this test.");
  1904. }
  1905. List listCmd;
  1906. Add addCmd;
  1907. setInput("a");
  1908. execCmd(listCmd,
  1909. {"ls",
  1910. "-y",
  1911. QString("%1:%2").arg(QString::number(pKey.second), QString::number(pKey.first)),
  1912. m_yubiKeyProtectedDbFile->fileName()});
  1913. m_stderr->readLine(); // skip password prompt
  1914. QCOMPARE(m_stderr->readAll(), QByteArray());
  1915. QCOMPARE(m_stdout->readAll(),
  1916. QByteArray("entry1\n"
  1917. "entry2\n"));
  1918. // Should raise an error with no yubikey slot.
  1919. setInput("a");
  1920. execCmd(listCmd, {"ls", m_yubiKeyProtectedDbFile->fileName()});
  1921. m_stderr->readLine(); // skip password prompt
  1922. QCOMPARE(m_stderr->readLine(),
  1923. QByteArray("Error while reading the database: Invalid credentials were provided, please try again.\n"));
  1924. QCOMPARE(m_stderr->readLine(),
  1925. QByteArray("If this reoccurs, then your database file may be corrupt. (HMAC mismatch)\n"));
  1926. QCOMPARE(m_stdout->readAll(), QByteArray());
  1927. // Should raise an error if yubikey slot is not a string
  1928. setInput("a");
  1929. execCmd(listCmd, {"ls", "-y", "invalidslot", m_yubiKeyProtectedDbFile->fileName()});
  1930. m_stderr->readLine(); // skip password prompt
  1931. QCOMPARE(m_stderr->readAll().split(':').at(0), QByteArray("Invalid YubiKey slot invalidslot\n"));
  1932. QCOMPARE(m_stdout->readAll(), QByteArray());
  1933. // Should raise an error if yubikey slot is invalid.
  1934. setInput("a");
  1935. execCmd(listCmd, {"ls", "-y", "3", m_yubiKeyProtectedDbFile->fileName()});
  1936. m_stderr->readLine(); // skip password prompt
  1937. QCOMPARE(m_stderr->readAll().split(':').at(0), QByteArray("Invalid YubiKey slot 3\n"));
  1938. QCOMPARE(m_stdout->readAll(), QByteArray());
  1939. }
  1940. void TestCli::testNonAscii()
  1941. {
  1942. QProcess process;
  1943. process.setProcessChannelMode(QProcess::MergedChannels);
  1944. process.start(
  1945. KEEPASSX_CLI_PATH,
  1946. QStringList(
  1947. {"show", "-a", "password", m_nonAsciiDbFile->fileName(), QString::fromUtf8("\xe7\xa7\x98\xe5\xaf\x86")}));
  1948. process.waitForStarted();
  1949. QCOMPARE(process.state(), QProcess::ProcessState::Running);
  1950. // Write password.
  1951. process.write("\xce\x94\xc3\xb6\xd8\xb6\n");
  1952. process.closeWriteChannel();
  1953. process.waitForFinished();
  1954. process.readLine(); // skip password prompt
  1955. QByteArray password = process.readLine();
  1956. QCOMPARE(QString::fromUtf8(password).trimmed(),
  1957. QString::fromUtf8("\xf0\x9f\x9a\x97\xf0\x9f\x90\x8e\xf0\x9f\x94\x8b\xf0\x9f\x93\x8e"));
  1958. }
  1959. void TestCli::testCommandParsing_data()
  1960. {
  1961. QTest::addColumn<QString>("input");
  1962. QTest::addColumn<QStringList>("expectedOutput");
  1963. QTest::newRow("basic") << "hello world" << QStringList({"hello", "world"});
  1964. QTest::newRow("basic escaping") << "hello\\ world" << QStringList({"hello world"});
  1965. QTest::newRow("quoted string") << "\"hello world\"" << QStringList({"hello world"});
  1966. QTest::newRow("multiple params") << "show Passwords/Internet" << QStringList({"show", "Passwords/Internet"});
  1967. QTest::newRow("quoted string inside param")
  1968. << R"(ls foo\ bar\ baz"quoted")" << QStringList({"ls", "foo bar baz\"quoted\""});
  1969. QTest::newRow("multiple whitespace") << "hello world" << QStringList({"hello", "world"});
  1970. QTest::newRow("single slash char") << "\\" << QStringList({"\\"});
  1971. QTest::newRow("double backslash entry name") << "show foo\\\\\\\\bar" << QStringList({"show", "foo\\\\bar"});
  1972. }
  1973. void TestCli::testCommandParsing()
  1974. {
  1975. QFETCH(QString, input);
  1976. QFETCH(QStringList, expectedOutput);
  1977. QStringList result = Utils::splitCommandString(input);
  1978. QCOMPARE(result.size(), expectedOutput.size());
  1979. for (int i = 0; i < expectedOutput.size(); ++i) {
  1980. QCOMPARE(result[i], expectedOutput[i]);
  1981. }
  1982. }
  1983. void TestCli::testOpen()
  1984. {
  1985. Open openCmd;
  1986. setInput("a");
  1987. execCmd(openCmd, {"open", m_dbFile->fileName()});
  1988. QVERIFY(openCmd.currentDatabase);
  1989. List listCmd;
  1990. // Set a current database, simulating interactive mode.
  1991. listCmd.currentDatabase = openCmd.currentDatabase;
  1992. execCmd(listCmd, {"ls"});
  1993. QByteArray expectedOutput("Sample Entry\n"
  1994. "General/\n"
  1995. "Windows/\n"
  1996. "Network/\n"
  1997. "Internet/\n"
  1998. "eMail/\n"
  1999. "Homebanking/\n");
  2000. QByteArray actualOutput = m_stdout->readAll();
  2001. actualOutput.truncate(expectedOutput.length());
  2002. QCOMPARE(actualOutput, expectedOutput);
  2003. }
  2004. void TestCli::testHelp()
  2005. {
  2006. Help helpCmd;
  2007. Commands::setupCommands(false);
  2008. execCmd(helpCmd, {"help"});
  2009. QVERIFY(m_stdout->readAll().contains("Available commands"));
  2010. List listCmd;
  2011. execCmd(helpCmd, {"help", "ls"});
  2012. QVERIFY(m_stdout->readAll().contains(listCmd.description.toLatin1()));
  2013. }