Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TestGuiFdoSecrets.cpp « gui « tests - github.com/keepassxreboot/keepassxc.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c869aac4fb3a033962818e75868b5cbb19c36da1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
/*
 *  Copyright (C) 2019 Aetf <aetf@unlimitedcodeworks.xyz>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 or (at your option)
 *  version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "TestGuiFdoSecrets.h"

#include "fdosecrets/FdoSecretsPlugin.h"
#include "fdosecrets/FdoSecretsSettings.h"
#include "fdosecrets/objects/Collection.h"
#include "fdosecrets/objects/Item.h"
#include "fdosecrets/objects/Prompt.h"
#include "fdosecrets/objects/Service.h"
#include "fdosecrets/objects/Session.h"
#include "fdosecrets/objects/SessionCipher.h"

#include "TestGlobal.h"
#include "config-keepassx-tests.h"

#include "core/Bootstrap.h"
#include "core/Config.h"
#include "core/Tools.h"
#include "crypto/Crypto.h"
#include "gui/DatabaseTabWidget.h"
#include "gui/DatabaseWidget.h"
#include "gui/FileDialog.h"
#include "gui/MessageBox.h"
#include "gui/wizard/NewDatabaseWizard.h"
#include "util/TemporaryFile.h"

#include <QAbstractItemView>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDBusInterface>
#include <QLineEdit>
#include <QPointer>
#include <QSignalSpy>
#include <QXmlStreamReader>

#include <memory>
#include <type_traits>

int main(int argc, char* argv[])
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
    QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif
    Application app(argc, argv);
    app.setApplicationName("KeePassXC");
    app.setApplicationVersion(KEEPASSXC_VERSION);
    app.setQuitOnLastWindowClosed(false);
    app.setAttribute(Qt::AA_Use96Dpi, true);
    app.applyTheme();
    QTEST_DISABLE_KEYPAD_NAVIGATION
    TestGuiFdoSecrets tc;
    QTEST_SET_MAIN_SOURCE_PATH
    return QTest::qExec(&tc, argc, argv);
}

#define DBUS_PATH_DEFAULT_ALIAS "/org/freedesktop/secrets/aliases/default"

#define VERIFY(statement)                                                                                              \
    do {                                                                                                               \
        if (!QTest::qVerify(static_cast<bool>(statement), #statement, "", __FILE__, __LINE__))                         \
            return {};                                                                                                 \
    } while (false)

#define COMPARE(actual, expected)                                                                                      \
    do {                                                                                                               \
        if (!QTest::qCompare(actual, expected, #actual, #expected, __FILE__, __LINE__))                                \
            return {};                                                                                                 \
    } while (false)

#define FAIL(message)                                                                                                  \
    do {                                                                                                               \
        QTest::qFail(static_cast<const char*>(message), __FILE__, __LINE__);                                           \
        return {};                                                                                                     \
    } while (false)

#define COMPARE_DBUS_LOCAL_CALL(actual, expected)                                                                      \
    do {                                                                                                               \
        const auto a = (actual);                                                                                       \
        QVERIFY(!a.isError());                                                                                         \
        QCOMPARE(a.value(), (expected));                                                                               \
    } while (false)

#define CHECKED_DBUS_LOCAL_CALL(name, stmt)                                                                            \
    std::remove_cv<decltype(stmt)::value_type>::type name;                                                             \
    do {                                                                                                               \
        const auto rep = stmt;                                                                                         \
        QVERIFY(!rep.isError());                                                                                       \
        name = rep.value();                                                                                            \
    } while (false)

namespace
{
    std::unique_ptr<QDBusInterface> interfaceOf(const QDBusObjectPath& objPath, const QString& interface)
    {
        std::unique_ptr<QDBusInterface> iface(new QDBusInterface(DBUS_SERVICE_SECRET, objPath.path(), interface));
        iface->setTimeout(5);
        VERIFY(iface->isValid());
        return iface;
    }

    std::unique_ptr<QDBusInterface> interfaceOf(FdoSecrets::DBusObject* obj)
    {
        VERIFY(obj);
        auto metaAdaptor = obj->dbusAdaptor().metaObject();
        auto ifaceName = metaAdaptor->classInfo(metaAdaptor->indexOfClassInfo("D-Bus Interface")).value();

        return interfaceOf(obj->objectPath(), ifaceName);
    }

    template <typename T> QString extractElement(const QString& doc, T cond)
    {
        QXmlStreamReader reader(doc);
        while (!reader.atEnd()) {
            int st = reader.characterOffset();

            if (reader.readNext() != QXmlStreamReader::StartElement || !cond(reader)) {
                continue;
            }

            reader.skipCurrentElement();
            if (reader.hasError()) {
                break;
            }

            // remove whitespaces between elements to be a little bit flexible
            int ed = reader.characterOffset();
            return doc.mid(st - 1, ed - st + 1).replace(QRegularExpression(R"(>[\s\n]+<)"), "><");
        }
        VERIFY(!reader.hasError());
        return {};
    }

    bool checkDBusSpec(const QString& path, const QString& interface)
    {
        QFile f(QStringLiteral(KEEPASSX_TEST_DATA_DIR "/dbus/interfaces/%1.xml").arg(interface));
        VERIFY(f.open(QFile::ReadOnly | QFile::Text));
        QTextStream in(&f);
        auto spec = in.readAll().replace(QRegularExpression(R"(>[\s\n]+<)"), "><").trimmed();

        auto bus = QDBusConnection::sessionBus();
        auto msg = QDBusMessage::createMethodCall(
            DBUS_SERVICE_SECRET, path, "org.freedesktop.DBus.Introspectable", "Introspect");

        // BlockWithGui enters event loop
        auto reply = QDBusPendingReply<QString>(bus.call(msg, QDBus::BlockWithGui, 5));
        VERIFY(reply.isValid());
        auto actual = extractElement(reply.argumentAt<0>(), [&](const QXmlStreamReader& reader) {
            return reader.name() == "interface" && reader.attributes().value("name") == interface;
        });

        COMPARE(actual, spec);
        return true;
    }
} // namespace

using namespace FdoSecrets;

// for use in QSignalSpy
Q_DECLARE_METATYPE(Collection*);
Q_DECLARE_METATYPE(Item*);

TestGuiFdoSecrets::~TestGuiFdoSecrets() = default;

void TestGuiFdoSecrets::initTestCase()
{
    // for use in QSignalSpy
    qRegisterMetaType<Collection*>();
    qRegisterMetaType<Item*>();

    QVERIFY(Crypto::init());
    Config::createTempFileInstance();
    config()->set(Config::AutoSaveAfterEveryChange, false);
    config()->set(Config::AutoSaveOnExit, false);
    config()->set(Config::GUI_ShowTrayIcon, true);
    config()->set(Config::UpdateCheckMessageShown, true);
    // Disable secret service integration (activate within individual tests to test the plugin)
    FdoSecrets::settings()->setEnabled(false);
    // activate within individual tests
    FdoSecrets::settings()->setShowNotification(false);

    Bootstrap::bootstrapApplication();

    m_mainWindow.reset(new MainWindow());
    m_tabWidget = m_mainWindow->findChild<DatabaseTabWidget*>("tabWidget");
    QVERIFY(m_tabWidget);
    m_plugin = m_mainWindow->findChild<FdoSecretsPlugin*>();
    QVERIFY(m_plugin);
    m_mainWindow->show();

    // Load the NewDatabase.kdbx file into temporary storage
    QFile sourceDbFile(QStringLiteral(KEEPASSX_TEST_DATA_DIR "/NewDatabase.kdbx"));
    QVERIFY(sourceDbFile.open(QIODevice::ReadOnly));
    QVERIFY(Tools::readAllFromDevice(&sourceDbFile, m_dbData));
    sourceDbFile.close();

    // set keys for session encryption
    m_serverPublic = MpiFromHex("e407997e8b918419cf851cf3345358fdf"
                                "ffb9564a220ac9c3934efd277cea20d17"
                                "467ecdc56e817f75ac39501f38a4a04ff"
                                "64d627e16c09981c7ad876da255b61c8e"
                                "6a8408236c2a4523cfe6961c26dbdfc77"
                                "c1a27a5b425ca71a019e829fae32c0b42"
                                "0e1b3096b48bc2ce9ccab1d1ff13a5eb4"
                                "b263cee30bdb1a57af9bfa93f");
    m_serverPrivate = MpiFromHex("013f4f3381ef0ca11c4c7363079577b56"
                                 "99b238644e0aba47e24bdba6173590216"
                                 "4f1e12dd0944800a373e090e63192f53b"
                                 "93583e9a9e50bb9d792aafaa3a0f5ae77"
                                 "de0c3423f5820848d88ee3bdd01c889f2"
                                 "7af58a02f5b6693d422b9d189b300d7b1"
                                 "be5076b5795cf8808c31e2e2898368d18"
                                 "ab5c26b0ea3480c9aba8154cf");
    // use the same cipher to do the client side encryption, but exchange the position of client/server keys
    m_cipher.reset(new DhIetf1024Sha256Aes128CbcPkcs7);
    QVERIFY(m_cipher->initialize(MpiFromBytes(MpiToBytes(m_serverPublic)),
                                 MpiFromHex("30d18c6b328bac970c05bda6af2e708b9"
                                            "d6bbbb6dc136c1a2d96e870fabc86ad74"
                                            "1846a26a4197f32f65ea2e7580ad2afe3"
                                            "dd5d6c1224b8368b0df2cd75d520a9ff9"
                                            "7fe894cc7da71b7bd285b4633359c16c8"
                                            "d341f822fa4f0fdf59b5d3448658c46a2"
                                            "a86dbb14ff85823873f8a259ccc52bbb8"
                                            "2b5a4c2a75447982553b42221"),
                                 MpiFromHex("84aafe9c9f356f7762307f4d791acb59e"
                                            "8e3fd562abdbb481d0587f8400ad6c51d"
                                            "af561a1beb9a22c8cd4d2807367c5787b"
                                            "2e06d631ccbb5194b6bb32211583ce688"
                                            "f9c2cebc22a9e4d494d12ebdd570c61a1"
                                            "62a94e88561d25ccd0415339d1f59e1b0"
                                            "6bc6b6b5fde46e23b2410eb034be390d3"
                                            "2407ec7ae90f0831f24afd5ac")));
}

// Every test starts with opening the temp database
void TestGuiFdoSecrets::init()
{
    m_dbFile.reset(new TemporaryFile());
    // Write the temp storage to a temp database file for use in our tests
    QVERIFY(m_dbFile->open());
    QCOMPARE(m_dbFile->write(m_dbData), static_cast<qint64>((m_dbData.size())));
    m_dbFile->close();

    // make sure window is activated or focus tests may fail
    m_mainWindow->activateWindow();
    QApplication::processEvents();

    // open and unlock the database
    m_tabWidget->addDatabaseTab(m_dbFile->fileName(), false, "a");
    m_dbWidget = m_tabWidget->currentDatabaseWidget();
    m_db = m_dbWidget->database();

    // by default expsoe the root group
    FdoSecrets::settings()->setExposedGroup(m_db, m_db->rootGroup()->uuid());
    QVERIFY(m_dbWidget->save());
}

// Every test ends with closing the temp database without saving
void TestGuiFdoSecrets::cleanup()
{
    // restore to default settings
    FdoSecrets::settings()->setShowNotification(false);
    FdoSecrets::settings()->setEnabled(false);
    if (m_plugin) {
        m_plugin->updateServiceState();
    }

    // DO NOT save the database
    for (int i = 0; i != m_tabWidget->count(); ++i) {
        m_tabWidget->databaseWidgetFromIndex(i)->database()->markAsClean();
    }
    QVERIFY(m_tabWidget->closeAllDatabaseTabs());
    QApplication::processEvents();

    if (m_dbFile) {
        m_dbFile->remove();
    }
}

void TestGuiFdoSecrets::cleanupTestCase()
{
    if (m_dbFile) {
        m_dbFile->remove();
    }
}

void TestGuiFdoSecrets::testDBusSpec()
{
    auto service = enableService();
    QVERIFY(service);

    // service
    QCOMPARE(service->objectPath().path(), QStringLiteral(DBUS_PATH_SECRETS));
    QVERIFY(checkDBusSpec(service->objectPath().path(), DBUS_INTERFACE_SECRET_SERVICE));

    // default alias
    QVERIFY(checkDBusSpec(DBUS_PATH_DEFAULT_ALIAS, DBUS_INTERFACE_SECRET_COLLECTION));

    // collection
    auto coll = getDefaultCollection(service);
    QVERIFY(coll);
    QVERIFY(checkDBusSpec(coll->objectPath().path(), DBUS_INTERFACE_SECRET_COLLECTION));

    // item
    auto item = getFirstItem(coll);
    QVERIFY(item);
    QVERIFY(checkDBusSpec(item->objectPath().path(), DBUS_INTERFACE_SECRET_ITEM));

    // session
    auto sess = openSession(service, PlainCipher::Algorithm);
    QVERIFY(sess);
    QVERIFY(checkDBusSpec(sess->objectPath().path(), DBUS_INTERFACE_SECRET_SESSION));

    // prompt
    FdoSecrets::settings()->setNoConfirmDeleteItem(true);
    PromptBase* prompt = nullptr;
    {
        auto rep = item->deleteItem();
        QVERIFY(!rep.isError());
        prompt = rep.value();
    }
    QVERIFY(prompt);
    QVERIFY(checkDBusSpec(prompt->objectPath().path(), DBUS_INTERFACE_SECRET_PROMPT));
}

void TestGuiFdoSecrets::testServiceEnable()
{
    QSignalSpy sigError(m_plugin, SIGNAL(error(QString)));
    QVERIFY(sigError.isValid());

    QSignalSpy sigStarted(m_plugin, SIGNAL(secretServiceStarted()));
    QVERIFY(sigStarted.isValid());

    // make sure no one else is holding the service
    QVERIFY(!QDBusConnection::sessionBus().interface()->isServiceRegistered(DBUS_SERVICE_SECRET));

    // enable the service
    auto service = enableService();
    QVERIFY(service);

    // service started without error
    QVERIFY(sigError.isEmpty());
    QCOMPARE(sigStarted.size(), 1);

    QApplication::processEvents();

    QVERIFY(QDBusConnection::sessionBus().interface()->isServiceRegistered(DBUS_SERVICE_SECRET));

    // there will be one default collection
    auto coll = getDefaultCollection(service);
    QVERIFY(coll);

    COMPARE_DBUS_LOCAL_CALL(coll->locked(), false);
    COMPARE_DBUS_LOCAL_CALL(coll->label(), m_db->metadata()->name());
    COMPARE_DBUS_LOCAL_CALL(
        coll->created(),
        static_cast<qulonglong>(m_db->rootGroup()->timeInfo().creationTime().toMSecsSinceEpoch() / 1000));
    COMPARE_DBUS_LOCAL_CALL(
        coll->modified(),
        static_cast<qulonglong>(m_db->rootGroup()->timeInfo().lastModificationTime().toMSecsSinceEpoch() / 1000));
}

void TestGuiFdoSecrets::testServiceEnableNoExposedDatabase()
{
    // reset the exposed group and then enable the service
    FdoSecrets::settings()->setExposedGroup(m_db, {});
    auto service = enableService();
    QVERIFY(service);

    // no collections
    COMPARE_DBUS_LOCAL_CALL(service->collections(), QList<Collection*>{});
}

void TestGuiFdoSecrets::testServiceSearch()
{
    auto service = enableService();
    QVERIFY(service);
    auto coll = getDefaultCollection(service);
    QVERIFY(coll);
    auto item = getFirstItem(coll);
    QVERIFY(item);

    item->backend()->attributes()->set("fdosecrets-test", "1");
    item->backend()->attributes()->set("fdosecrets-test-protected", "2", true);
    const QString crazyKey = "_a:bc&-+'-e%12df_d";
    const QString crazyValue = "[v]al@-ue";
    item->backend()->attributes()->set(crazyKey, crazyValue);

    // search by title
    {
        QList<Item*> locked;
        CHECKED_DBUS_LOCAL_CALL(unlocked, service->searchItems({{"Title", item->backend()->title()}}, locked));
        QCOMPARE(locked.size(), 0);
        QCOMPARE(unlocked, {item});
    }

    // search by attribute
    {
        QList<Item*> locked;
        CHECKED_DBUS_LOCAL_CALL(unlocked, service->searchItems({{"fdosecrets-test", "1"}}, locked));
        QCOMPARE(locked.size(), 0);
        QCOMPARE(unlocked, {item});
    }
    {
        QList<Item*> locked;
        CHECKED_DBUS_LOCAL_CALL(unlocked, service->searchItems({{crazyKey, crazyValue}}, locked));
        QCOMPARE(locked.size(), 0);
        QCOMPARE(unlocked, {item});
    }

    // searching using empty terms returns nothing
    {
        QList<Item*> locked;
        CHECKED_DBUS_LOCAL_CALL(unlocked, service->searchItems({}, locked));
        QCOMPARE(locked.size(), 0);
        QCOMPARE(unlocked.size(), 0);
    }

    // searching using protected attributes or password returns nothing
    {
        QList<Item*> locked;
        CHECKED_DBUS_LOCAL_CALL(unlocked, service->searchItems({{"Password", item->backend()->password()}}, locked));
        QCOMPARE(locked.size(), 0);
        QCOMPARE(unlocked.size(), 0);
    }
    {
        QList<Item*> locked;
        CHECKED_DBUS_LOCAL_CALL(unlocked, service->searchItems({{"fdosecrets-test-protected", "2"}}, locked));
        QCOMPARE(locked.size(), 0);
        QCOMPARE(unlocked.size(), 0);
    }
}

void TestGuiFdoSecrets::testServiceUnlock()
{
    lockDatabaseInBackend();

    auto service = enableService();
    QVERIFY(service);
    auto coll = getDefaultCollection(service);
    QVERIFY(coll);

    QSignalSpy spyCollectionCreated(service, SIGNAL(collectionCreated(Collection*)));
    QVERIFY(spyCollectionCreated.isValid());
    QSignalSpy spyCollectionDeleted(service, SIGNAL(collectionDeleted(Collection*)));
    QVERIFY(spyCollectionDeleted.isValid());
    QSignalSpy spyCollectionChanged(service, SIGNAL(collectionChanged(Collection*)));
    QVERIFY(spyCollectionChanged.isValid());

    PromptBase* prompt = nullptr;
    {
        CHECKED_DBUS_LOCAL_CALL(unlocked, service->unlock({coll.data()}, prompt));
        // nothing is unlocked immediately without user's action
        QVERIFY(unlocked.isEmpty());
    }
    QVERIFY(prompt);
    QSignalSpy spyPromptCompleted(prompt, SIGNAL(completed(bool, QVariant)));
    QVERIFY(spyPromptCompleted.isValid());

    // nothing is unlocked yet
    QCOMPARE(spyPromptCompleted.count(), 0);
    QVERIFY(coll);
    QVERIFY(coll->backend()->isLocked());

    // drive the prompt
    QVERIFY(!prompt->prompt("").isError());

    // still not unlocked before user action
    QCOMPARE(spyPromptCompleted.count(), 0);
    QVERIFY(coll);
    QVERIFY(coll->backend()->isLocked());

    // interact with the dialog
    QApplication::processEvents();
    {
        auto dbOpenDlg = m_tabWidget->findChild<DatabaseOpenDialog*>();
        QVERIFY(dbOpenDlg);
        auto editPassword = dbOpenDlg->findChild<QLineEdit*>("editPassword");
        QVERIFY(editPassword);
        editPassword->setFocus();
        QTest::keyClicks(editPassword, "a");
        QTest::keyClick(editPassword, Qt::Key_Enter);
    }
    QApplication::processEvents();

    // unlocked
    QVERIFY(coll);
    QVERIFY(!coll->backend()->isLocked());

    QCOMPARE(spyPromptCompleted.count(), 1);
    {
        auto args = spyPromptCompleted.takeFirst();
        QCOMPARE(args.size(), 2);
        QCOMPARE(args.at(0).toBool(), false);
        QCOMPARE(args.at(1).value<QList<QDBusObjectPath>>(), {coll->objectPath()});
    }
    QCOMPARE(spyCollectionCreated.count(), 0);
    QCOMPARE(spyCollectionChanged.count(), 1);
    {
        auto args = spyCollectionChanged.takeFirst();
        QCOMPARE(args.size(), 1);
        QCOMPARE(args.at(0).value<Collection*>(), coll.data());
    }
    QCOMPARE(spyCollectionDeleted.count(), 0);
}

void TestGuiFdoSecrets::testServiceLock()
{
    auto service = enableService();
    QVERIFY(service);
    auto coll = getDefaultCollection(service);
    QVERIFY(coll);

    QSignalSpy spyCollectionCreated(service, SIGNAL(collectionCreated(Collection*)));
    QVERIFY(spyCollectionCreated.isValid());
    QSignalSpy spyCollectionDeleted(service, SIGNAL(collectionDeleted(Collection*)));
    QVERIFY(spyCollectionDeleted.isValid());
    QSignalSpy spyCollectionChanged(service, SIGNAL(collectionChanged(Collection*)));
    QVERIFY(spyCollectionChanged.isValid());

    // if the db is modified, prompt user
    m_db->markAsModified();
    {
        PromptBase* prompt = nullptr;
        CHECKED_DBUS_LOCAL_CALL(locked, service->lock({coll}, prompt));
        QCOMPARE(locked.size(), 0);
        QVERIFY(prompt);
        QSignalSpy spyPromptCompleted(prompt, SIGNAL(completed(bool, QVariant)));
        QVERIFY(spyPromptCompleted.isValid());

        // prompt and click cancel
        MessageBox::setNextAnswer(MessageBox::Cancel);
        QVERIFY(!prompt->prompt("").isError());
        QApplication::processEvents();

        QVERIFY(!coll->backend()->isLocked());

        QCOMPARE(spyPromptCompleted.count(), 1);
        auto args = spyPromptCompleted.takeFirst();
        QCOMPARE(args.count(), 2);
        QCOMPARE(args.at(0).toBool(), true);
        QCOMPARE(args.at(1).value<QList<QDBusObjectPath>>(), {});
    }
    {
        PromptBase* prompt = nullptr;
        CHECKED_DBUS_LOCAL_CALL(locked, service->lock({coll}, prompt));
        QCOMPARE(locked.size(), 0);
        QVERIFY(prompt);
        QSignalSpy spyPromptCompleted(prompt, SIGNAL(completed(bool, QVariant)));
        QVERIFY(spyPromptCompleted.isValid());

        // prompt and click save
        MessageBox::setNextAnswer(MessageBox::Save);
        QVERIFY(!prompt->prompt("").isError());
        QApplication::processEvents();

        QVERIFY(coll->backend()->isLocked());

        QCOMPARE(spyPromptCompleted.count(), 1);
        auto args = spyPromptCompleted.takeFirst();
        QCOMPARE(args.count(), 2);
        QCOMPARE(args.at(0).toBool(), false);
        QCOMPARE(args.at(1).value<QList<QDBusObjectPath>>(), {coll->objectPath()});
    }

    QCOMPARE(spyCollectionCreated.count(), 0);
    QCOMPARE(spyCollectionChanged.count(), 1);
    {
        auto args = spyCollectionChanged.takeFirst();
        QCOMPARE(args.size(), 1);
        QCOMPARE(args.at(0).value<Collection*>(), coll.data());
    }
    QCOMPARE(spyCollectionDeleted.count(), 0);

    // locking item locks the whole db
    unlockDatabaseInBackend();
    {
        auto item = getFirstItem(coll);
        PromptBase* prompt = nullptr;
        CHECKED_DBUS_LOCAL_CALL(locked, service->lock({item}, prompt));
        QCOMPARE(locked.size(), 0);
        QVERIFY(prompt);

        MessageBox::setNextAnswer(MessageBox::Save);
        QVERIFY(!prompt->prompt("").isError());
        QApplication::processEvents();

        QVERIFY(coll->backend()->isLocked());
    }
}

void TestGuiFdoSecrets::testSessionOpen()
{
    auto service = enableService();
    QVERIFY(service);

    auto sess = openSession(service, PlainCipher::Algorithm);
    QVERIFY(sess);
    QCOMPARE(service->sessions().size(), 1);

    sess = openSession(service, DhIetf1024Sha256Aes128CbcPkcs7::Algorithm);
    QVERIFY(sess);
    QCOMPARE(service->sessions().size(), 2);
}

void TestGuiFdoSecrets::testSessionClose()
{
    auto service = enableService();
    QVERIFY(service);

    auto sess = openSession(service, PlainCipher::Algorithm);
    QVERIFY(sess);

    QCOMPARE(service->sessions().size(), 1);

    auto rep = sess->close();
    QVERIFY(!rep.isError());

    QCOMPARE(service->sessions().size(), 0);
}

void TestGuiFdoSecrets::testCollectionCreate()
{
    auto service = enableService();
    QVERIFY(service);

    QSignalSpy spyCollectionCreated(service, SIGNAL(collectionCreated(Collection*)));
    QVERIFY(spyCollectionCreated.isValid());

    // returns existing if alias is nonempty and exists
    {
        PromptBase* prompt = nullptr;
        CHECKED_DBUS_LOCAL_CALL(
            coll, service->createCollection({{DBUS_INTERFACE_SECRET_COLLECTION ".Label", "NewDB"}}, "default", prompt));
        QVERIFY(!prompt);
        QCOMPARE(coll, getDefaultCollection(service).data());
    }
    QCOMPARE(spyCollectionCreated.count(), 0);

    // create new one and set properties
    {
        PromptBase* prompt = nullptr;
        CHECKED_DBUS_LOCAL_CALL(
            created,
            service->createCollection({{DBUS_INTERFACE_SECRET_COLLECTION ".Label", "Test NewDB"}}, "mydatadb", prompt));
        QVERIFY(!created);
        QVERIFY(prompt);

        QSignalSpy spyPromptCompleted(prompt, SIGNAL(completed(bool, QVariant)));
        QVERIFY(spyPromptCompleted.isValid());

        QTimer::singleShot(50, this, SLOT(createDatabaseCallback()));
        QVERIFY(!prompt->prompt("").isError());
        QApplication::processEvents();

        QCOMPARE(spyPromptCompleted.count(), 1);
        auto args = spyPromptCompleted.takeFirst();
        QCOMPARE(args.size(), 2);
        QCOMPARE(args.at(0).toBool(), false);
        auto coll = FdoSecrets::pathToObject<Collection>(args.at(1).value<QDBusObjectPath>());
        QVERIFY(coll);

        QCOMPARE(coll->backend()->database()->metadata()->name(), QStringLiteral("Test NewDB"));

        QCOMPARE(spyCollectionCreated.count(), 1);
        {
            auto args = spyCollectionCreated.takeFirst();
            QCOMPARE(args.size(), 1);
            QCOMPARE(args.at(0).value<Collection*>(), coll);
        }
    }
}

void TestGuiFdoSecrets::createDatabaseCallback()
{
    auto wizard = m_tabWidget->findChild<NewDatabaseWizard*>();
    QVERIFY(wizard);

    QCOMPARE(wizard->currentId(), 0);
    wizard->next();
    wizard->next();
    QCOMPARE(wizard->currentId(), 2);

    // enter password
    auto* passwordEdit = wizard->findChild<QLineEdit*>("enterPasswordEdit");
    auto* passwordRepeatEdit = wizard->findChild<QLineEdit*>("repeatPasswordEdit");
    QTest::keyClicks(passwordEdit, "test");
    QTest::keyClick(passwordEdit, Qt::Key::Key_Tab);
    QTest::keyClicks(passwordRepeatEdit, "test");

    // save database to temporary file
    TemporaryFile tmpFile;
    QVERIFY(tmpFile.open());
    tmpFile.close();
    fileDialog()->setNextFileName(tmpFile.fileName());

    wizard->accept();

    tmpFile.remove();
}

void TestGuiFdoSecrets::testCollectionDelete()
{
    auto service = enableService();
    QVERIFY(service);
    auto coll = getDefaultCollection(service);
    QVERIFY(coll);
    // closing the tab calls coll->deleteLater()
    // but deleteLater is not processed in QApplication::processEvent
    // see https://doc.qt.io/qt-5/qcoreapplication.html#processEvents
    auto rawColl = coll.data();

    QSignalSpy spyCollectionDeleted(service, SIGNAL(collectionDeleted(Collection*)));
    QVERIFY(spyCollectionDeleted.isValid());

    m_db->markAsModified();
    CHECKED_DBUS_LOCAL_CALL(prompt, coll->deleteCollection());
    QVERIFY(prompt);
    QSignalSpy spyPromptCompleted(prompt, SIGNAL(completed(bool, QVariant)));
    QVERIFY(spyPromptCompleted.isValid());

    // prompt and click save
    MessageBox::setNextAnswer(MessageBox::Save);
    QVERIFY(!prompt->prompt("").isError());

    QApplication::processEvents();

    // closing the tab should have deleted coll if not in testing
    // but deleteLater is not processed in QApplication::processEvent
    // see https://doc.qt.io/qt-5/qcoreapplication.html#processEvents
    // QVERIFY(!coll);

    QCOMPARE(spyPromptCompleted.count(), 1);
    auto args = spyPromptCompleted.takeFirst();
    QCOMPARE(args.count(), 2);
    QCOMPARE(args.at(0).toBool(), false);
    QCOMPARE(args.at(1).toString(), QStringLiteral(""));

    QCOMPARE(spyCollectionDeleted.count(), 1);
    {
        auto args = spyCollectionDeleted.takeFirst();
        QCOMPARE(args.size(), 1);
        QCOMPARE(args.at(0).value<Collection*>(), rawColl);
    }
}

void TestGuiFdoSecrets::testItemCreate()
{
    auto service = enableService();
    QVERIFY(service);
    auto coll = getDefaultCollection(service);
    QVERIFY(coll);
    auto sess = openSession(service, DhIetf1024Sha256Aes128CbcPkcs7::Algorithm);
    QVERIFY(sess);

    // create item
    StringStringMap attributes{
        {"application", "fdosecrets-test"},
        {"attr-i[bute]", "![some] -value*"},
    };

    auto item = createItem(sess, coll, "abc", "Password", attributes, false);
    QVERIFY(item);

    // attributes
    {
        CHECKED_DBUS_LOCAL_CALL(actual, item->attributes());
        for (const auto& key : attributes.keys()) {
            QVERIFY(actual.contains(key));
            QCOMPARE(actual[key], attributes[key]);
        }
    }

    // label
    COMPARE_DBUS_LOCAL_CALL(item->label(), QStringLiteral("abc"));

    // secrets
    {
        CHECKED_DBUS_LOCAL_CALL(ss, item->getSecret(sess));
        ss = m_cipher->decrypt(ss);
        QCOMPARE(ss.value, QByteArray("Password"));
    }

    // searchable
    {
        QList<Item*> locked;
        CHECKED_DBUS_LOCAL_CALL(unlocked, service->searchItems(attributes, locked));
        QCOMPARE(locked, QList<Item*>{});
        QCOMPARE(unlocked, QList<Item*>{item});
    }
    {
        CHECKED_DBUS_LOCAL_CALL(unlocked, coll->searchItems(attributes));
        QVERIFY(unlocked.contains(item));
    }
}

void TestGuiFdoSecrets::testItemReplace()
{
    auto service = enableService();
    QVERIFY(service);
    auto coll = getDefaultCollection(service);
    QVERIFY(coll);
    auto sess = openSession(service, DhIetf1024Sha256Aes128CbcPkcs7::Algorithm);
    QVERIFY(sess);

    // create item
    StringStringMap attr1{
        {"application", "fdosecrets-test"},
        {"attr-i[bute]", "![some] -value*"},
        {"fdosecrets-attr", "1"},
    };
    StringStringMap attr2{
        {"application", "fdosecrets-test"},
        {"attr-i[bute]", "![some] -value*"},
        {"fdosecrets-attr", "2"},
    };

    auto item1 = createItem(sess, coll, "abc1", "Password", attr1, false);
    QVERIFY(item1);
    auto item2 = createItem(sess, coll, "abc2", "Password", attr2, false);
    QVERIFY(item2);

    {
        QList<Item*> locked;
        CHECKED_DBUS_LOCAL_CALL(unlocked, service->searchItems({{"application", "fdosecrets-test"}}, locked));
        QCOMPARE(unlocked.size(), 2);
    }

    {
        // when replace, existing item with matching attr is updated
        auto item3 = createItem(sess, coll, "abc3", "Password", attr2, true);
        QVERIFY(item3);
        QCOMPARE(item2, item3);
        COMPARE_DBUS_LOCAL_CALL(item3->label(), QStringLiteral("abc3"));
        // there is still 2 entries
        QList<Item*> locked;
        CHECKED_DBUS_LOCAL_CALL(unlocked, service->searchItems({{"application", "fdosecrets-test"}}, locked));
        QCOMPARE(unlocked.size(), 2);
    }

    {
        // when NOT replace, another entry is created
        auto item4 = createItem(sess, coll, "abc4", "Password", attr2, false);
        QVERIFY(item4);
        COMPARE_DBUS_LOCAL_CALL(item2->label(), QStringLiteral("abc3"));
        COMPARE_DBUS_LOCAL_CALL(item4->label(), QStringLiteral("abc4"));
        // there is 3 entries
        QList<Item*> locked;
        CHECKED_DBUS_LOCAL_CALL(unlocked, service->searchItems({{"application", "fdosecrets-test"}}, locked));
        QCOMPARE(unlocked.size(), 3);
    }
}

void TestGuiFdoSecrets::testItemSecret()
{
    const QString TEXT_PLAIN = "text/plain";
    const QString APPLICATION_OCTET_STREAM = "application/octet-stream";

    auto service = enableService();
    QVERIFY(service);
    auto coll = getDefaultCollection(service);
    QVERIFY(coll);
    auto item = getFirstItem(coll);
    QVERIFY(item);
    auto sess = openSession(service, DhIetf1024Sha256Aes128CbcPkcs7::Algorithm);
    QVERIFY(sess);

    // plain text secret
    {
        CHECKED_DBUS_LOCAL_CALL(encrypted, item->getSecret(sess));
        auto ss = m_cipher->decrypt(encrypted);
        QCOMPARE(ss.contentType, TEXT_PLAIN);
        QCOMPARE(ss.value, item->backend()->password().toUtf8());
    }

    // get secret with notification (only works when called from DBUS)
    FdoSecrets::settings()->setShowNotification(true);
    {
        QSignalSpy spyShowNotification(m_plugin, SIGNAL(requestShowNotification(QString, QString, int)));
        QVERIFY(spyShowNotification.isValid());

        auto iitem = interfaceOf(item);
        QVERIFY(static_cast<bool>(iitem));

        auto replyMsg = iitem->call(QDBus::BlockWithGui, "GetSecret", QVariant::fromValue(sess->objectPath()));
        auto reply = QDBusPendingReply<SecretStruct>(replyMsg);
        QVERIFY(reply.isValid());
        auto ss = m_cipher->decrypt(reply.argumentAt<0>());

        QCOMPARE(ss.contentType, TEXT_PLAIN);
        QCOMPARE(ss.value, item->backend()->password().toUtf8());

        QCOMPARE(spyShowNotification.count(), 1);
    }
    FdoSecrets::settings()->setShowNotification(false);

    // set secret with plain text
    {
        SecretStruct ss;
        ss.contentType = TEXT_PLAIN;
        ss.value = "NewPassword";
        ss.session = sess->objectPath();
        QVERIFY(!item->setSecret(m_cipher->encrypt(ss)).isError());

        QCOMPARE(item->backend()->password().toUtf8(), ss.value);
    }

    // set secret with something else is saved as attachment
    {
        SecretStruct expected;
        expected.contentType = APPLICATION_OCTET_STREAM;
        expected.value = "NewPasswordBinary";
        expected.session = sess->objectPath();
        QVERIFY(!item->setSecret(m_cipher->encrypt(expected)).isError());

        QCOMPARE(item->backend()->password(), QStringLiteral(""));

        CHECKED_DBUS_LOCAL_CALL(encrypted, item->getSecret(sess));
        auto ss = m_cipher->decrypt(encrypted);
        QCOMPARE(ss.contentType, expected.contentType);
        QCOMPARE(ss.value, expected.value);
    }
}

void TestGuiFdoSecrets::testItemDelete()
{
    FdoSecrets::settings()->setNoConfirmDeleteItem(false);

    auto service = enableService();
    QVERIFY(service);
    auto coll = getDefaultCollection(service);
    QVERIFY(coll);
    auto item = getFirstItem(coll);
    QVERIFY(item);
    auto rawItem = item.data();

    QSignalSpy spyItemDeleted(coll, SIGNAL(itemDeleted(Item*)));
    QVERIFY(spyItemDeleted.isValid());

    CHECKED_DBUS_LOCAL_CALL(prompt, item->deleteItem());
    QVERIFY(prompt);

    QSignalSpy spyPromptCompleted(prompt, SIGNAL(completed(bool, QVariant)));
    QVERIFY(spyPromptCompleted.isValid());

    // prompt and click save
    if (item->isDeletePermanent()) {
        MessageBox::setNextAnswer(MessageBox::Delete);
    } else {
        MessageBox::setNextAnswer(MessageBox::Move);
    }
    QVERIFY(!prompt->prompt("").isError());

    QApplication::processEvents();

    QCOMPARE(spyPromptCompleted.count(), 1);
    auto args = spyPromptCompleted.takeFirst();
    QCOMPARE(args.count(), 2);
    QCOMPARE(args.at(0).toBool(), false);
    QCOMPARE(args.at(1).toString(), QStringLiteral(""));

    QCOMPARE(spyItemDeleted.count(), 1);
    {
        auto args = spyItemDeleted.takeFirst();
        QCOMPARE(args.size(), 1);
        QCOMPARE(args.at(0).value<Item*>(), rawItem);
    }
}

void TestGuiFdoSecrets::testAlias()
{
    auto service = enableService();
    QVERIFY(service);

    // read default alias
    CHECKED_DBUS_LOCAL_CALL(coll, service->readAlias("default"));
    QVERIFY(coll);

    // set extra alias
    QVERIFY(!service->setAlias("another", coll).isError());

    // get using extra alias
    CHECKED_DBUS_LOCAL_CALL(coll2, service->readAlias("another"));
    QVERIFY(coll2);
    QCOMPARE(coll, coll2);
}

void TestGuiFdoSecrets::testDefaultAliasAlwaysPresent()
{
    auto service = enableService();
    QVERIFY(service);

    // one collection, which is default alias
    auto coll = getDefaultCollection(service);
    QVERIFY(coll);

    // after locking, the collection is still there, but locked
    lockDatabaseInBackend();

    coll = getDefaultCollection(service);
    QVERIFY(coll);
    COMPARE_DBUS_LOCAL_CALL(coll->locked(), true);

    // unlock the database, the alias and collection is present
    unlockDatabaseInBackend();

    coll = getDefaultCollection(service);
    QVERIFY(coll);
    COMPARE_DBUS_LOCAL_CALL(coll->locked(), false);
}

void TestGuiFdoSecrets::testExposeSubgroup()
{
    auto subgroup = m_db->rootGroup()->findGroupByPath("/Homebanking/Subgroup");
    QVERIFY(subgroup);
    FdoSecrets::settings()->setExposedGroup(m_db, subgroup->uuid());
    auto service = enableService();
    QVERIFY(service);

    auto coll = getDefaultCollection(service);
    QVERIFY(coll);

    // exposing subgroup does not expose entries in other groups
    auto items = coll->items();
    QVERIFY(!items.isError());
    QList<Entry*> exposedEntries;
    for (const auto& item : items.value()) {
        exposedEntries << item->backend();
    }
    QCOMPARE(exposedEntries, subgroup->entries());
}

void TestGuiFdoSecrets::testModifiyingExposedGroup()
{
    // test when exposed group is removed the collection is not exposed anymore
    auto subgroup = m_db->rootGroup()->findGroupByPath("/Homebanking");
    QVERIFY(subgroup);
    FdoSecrets::settings()->setExposedGroup(m_db, subgroup->uuid());
    auto service = enableService();
    QVERIFY(service);

    {
        CHECKED_DBUS_LOCAL_CALL(colls, service->collections());
        QCOMPARE(colls.size(), 1);
    }

    m_db->metadata()->setRecycleBinEnabled(true);
    m_db->recycleGroup(subgroup);
    QApplication::processEvents();

    {
        CHECKED_DBUS_LOCAL_CALL(colls, service->collections());
        QCOMPARE(colls.size(), 0);
    }

    // test setting another exposed group, the collection will be exposed again
    FdoSecrets::settings()->setExposedGroup(m_db, m_db->rootGroup()->uuid());
    QApplication::processEvents();
    {
        CHECKED_DBUS_LOCAL_CALL(colls, service->collections());
        QCOMPARE(colls.size(), 1);
    }
}

QPointer<Service> TestGuiFdoSecrets::enableService()
{
    FdoSecrets::settings()->setEnabled(true);
    VERIFY(m_plugin);
    m_plugin->updateServiceState();
    return m_plugin->serviceInstance();
}

QPointer<Session> TestGuiFdoSecrets::openSession(Service* service, const QString& algo)
{
    // open session has to be called actually over DBUS to get peer info

    VERIFY(service);
    auto iservice = interfaceOf(service);
    VERIFY(iservice);

    if (algo == PlainCipher::Algorithm) {
        auto replyMsg = iservice->call(QDBus::BlockWithGui, "OpenSession", algo, QVariant::fromValue(QDBusVariant("")));
        auto reply = QDBusPendingReply<QDBusVariant, QDBusObjectPath>(replyMsg);

        VERIFY(reply.isValid());
        return FdoSecrets::pathToObject<Session>(reply.argumentAt<1>());
    } else if (algo == DhIetf1024Sha256Aes128CbcPkcs7::Algorithm) {

        DhIetf1024Sha256Aes128CbcPkcs7::fixNextServerKeys(MpiFromBytes(MpiToBytes(m_serverPrivate)),
                                                          MpiFromBytes(MpiToBytes(m_serverPublic)));

        auto replyMsg = iservice->call(
            QDBus::BlockWithGui, "OpenSession", algo, QVariant::fromValue(QDBusVariant(m_cipher->m_publicKey)));
        auto reply = QDBusPendingReply<QDBusVariant, QDBusObjectPath>(replyMsg);
        VERIFY(reply.isValid());
        COMPARE(qvariant_cast<QByteArray>(reply.argumentAt<0>().variant()), MpiToBytes(m_serverPublic));
        return FdoSecrets::pathToObject<Session>(reply.argumentAt<1>());
    }
    FAIL("Unsupported algorithm");
}

QPointer<Collection> TestGuiFdoSecrets::getDefaultCollection(Service* service)
{
    VERIFY(service);
    auto coll = service->readAlias("default");
    VERIFY(!coll.isError());
    return coll.value();
}

QPointer<Item> TestGuiFdoSecrets::getFirstItem(Collection* coll)
{
    VERIFY(coll);
    auto items = coll->items();
    VERIFY(!items.isError());
    VERIFY(!items.value().isEmpty());
    return items.value().at(0);
}

QPointer<Item> TestGuiFdoSecrets::createItem(Session* sess,
                                             Collection* coll,
                                             const QString& label,
                                             const QString& pass,
                                             const StringStringMap& attr,
                                             bool replace)
{
    VERIFY(sess);
    VERIFY(coll);

    QVariantMap properties{
        {DBUS_INTERFACE_SECRET_ITEM ".Label", QVariant::fromValue(label)},
        {DBUS_INTERFACE_SECRET_ITEM ".Attributes", QVariant::fromValue(attr)},
    };

    SecretStruct ss;
    ss.session = sess->objectPath();
    ss.value = pass.toLocal8Bit();
    ss.contentType = "plain/text";
    ss = m_cipher->encrypt(ss);

    PromptBase* prompt = nullptr;
    auto item = coll->createItem(properties, ss, replace, prompt);
    VERIFY(!item.isError());
    // creating item does not have a prompt to show
    VERIFY(!prompt);
    return item.value();
}

void TestGuiFdoSecrets::lockDatabaseInBackend()
{
    m_dbWidget->lock();
    m_db.reset();
    QApplication::processEvents();
}

void TestGuiFdoSecrets::unlockDatabaseInBackend()
{
    m_dbWidget->performUnlockDatabase("a");
    m_db = m_dbWidget->database();
    QApplication::processEvents();
}