diff --git a/src/fdosecrets/objects/Prompt.cpp b/src/fdosecrets/objects/Prompt.cpp index e89cd499b..3a59a45b8 100644 --- a/src/fdosecrets/objects/Prompt.cpp +++ b/src/fdosecrets/objects/Prompt.cpp @@ -71,6 +71,13 @@ namespace FdoSecrets return ret; } + // the prompt is already being processed, do not schedule another run. + // the ongoing one will emit the completed signal. + if (m_signalSent || m_scheduled) { + return {}; + } + m_scheduled = true; + QWeakPointer weak = client; // execute the actual prompt method in event loop to avoid block this method QTimer::singleShot(0, this, [this, weak, windowId]() { @@ -113,6 +120,12 @@ namespace FdoSecrets : PromptBase(parent) , m_collection(coll) { + // The QPointer alone is not enough: after Collection::removeFromDBus the + // collection lingers until its deleteLater is delivered, with m_backend + // already reset. Clear our reference as soon as the collection retires so + // that a non-null m_collection always implies a usable backend, which + // Collection::doDelete asserts on. + connect(coll, &Collection::collectionAboutToDelete, this, [this]() { m_collection = nullptr; }); } PromptResult DeleteCollectionPrompt::promptSync(const DBusClientPtr&, const QString& windowId) @@ -182,6 +195,16 @@ namespace FdoSecrets m_collections.reserve(colls.size()); for (const auto& c : asConst(colls)) { m_collections << c; + // clear the reference as soon as the collection retires, so promptSync + // never calls into a collection whose backend is already gone. + // A retired collection is skipped just like a destroyed one. + connect(c, &Collection::collectionAboutToDelete, this, [this, c]() { + for (auto& p : m_collections) { + if (p == c) { + p = nullptr; + } + } + }); } } @@ -211,6 +234,9 @@ namespace FdoSecrets m_collections.reserve(colls.size()); for (const auto& coll : asConst(colls)) { m_collections << coll; + // a collection may retire while we are waiting for its unlock outcome, + // in which case doneUnlockCollection will never fire for it. + connect(coll, &Collection::collectionAboutToDelete, this, [this, coll]() { collectionRetired(coll); }); } for (const auto& item : asConst(items)) { m_items[item->collection()] << item; @@ -230,21 +256,32 @@ namespace FdoSecrets m_windowId = windowId; m_client = client; - // first unlock any collections - bool waitingForCollections = false; + // first unlock any collections. + // register everything we will wait for upfront: doUnlock may complete + // synchronously (already unlocked database), and the completion handler + // must not conclude that all collections are done while some have not + // even been issued yet. for (const auto& c : asConst(m_collections)) { if (c) { + m_pendingCollections << c.data(); + } else { + // the collection retired or was destroyed since the prompt was created + m_numRejected += 1; + } + } + for (const auto& c : asConst(m_collections)) { + // skip entries that already resolved synchronously or retired mid-loop + if (c && m_pendingCollections.contains(c.data())) { connect(c, &Collection::doneUnlockCollection, this, &UnlockPrompt::collectionUnlockFinished); // doUnlock is nonblocking, execution will continue in collectionUnlockFinished // it is ok to call doUnlock multiple times before it's actually unlocked by the user c->doUnlock(); - waitingForCollections = true; } } // unlock items directly if no collection unlocking pending - // o.w. doing it in collectionUnlockFinished - if (!waitingForCollections) { + // o.w. doing it in collectionUnlockFinished or collectionRetired + if (m_pendingCollections.isEmpty()) { unlockItems(); } @@ -261,8 +298,8 @@ namespace FdoSecrets // one shot coll->disconnect(this); - if (!m_collections.contains(coll)) { - // should not happen + if (!m_pendingCollections.remove(coll)) { + // not awaiting this collection (already resolved or retired) return; } @@ -275,14 +312,44 @@ namespace FdoSecrets } // if we got response for all collections - if (m_numRejected + m_unlocked.size() == m_collections.size()) { + if (m_pendingCollections.isEmpty()) { // next step is to unlock items unlockItems(); } } + void UnlockPrompt::collectionRetired(Collection* coll) + { + // the collection is going away (already removed from DBus, backend reset); + // stop referencing it so no doUnlock/doneUnlockCollection is attempted on it + for (auto& p : m_collections) { + if (p == coll) { + p = nullptr; + } + } + m_items.remove(coll); + + if (!m_pendingCollections.remove(coll)) { + // nothing was issued for it yet (promptSync not run) or it already resolved; + // promptSync accounts for cleared entries itself + return; + } + + // treat as if the collection rejected the unlock + m_numRejected += 1; + if (m_pendingCollections.isEmpty()) { + unlockItems(); + } + } + void UnlockPrompt::unlockItems() { + // may be reached from multiple paths (last collection resolving vs retiring) + if (m_unlockItemsStarted) { + return; + } + m_unlockItemsStarted = true; + auto client = m_client.lock(); if (!client) { // client already gone diff --git a/src/fdosecrets/objects/Prompt.h b/src/fdosecrets/objects/Prompt.h index 078e4ce86..eb7517f11 100644 --- a/src/fdosecrets/objects/Prompt.h +++ b/src/fdosecrets/objects/Prompt.h @@ -22,6 +22,8 @@ #include "fdosecrets/dbus/DBusClient.h" #include "fdosecrets/dbus/DBusObject.h" +#include + class QWindow; class DatabaseWidget; @@ -112,6 +114,7 @@ namespace FdoSecrets private: bool m_signalSent = false; + bool m_scheduled = false; }; class Collection; @@ -169,6 +172,7 @@ namespace FdoSecrets QVariant currentResult() const override; void collectionUnlockFinished(bool accepted); + void collectionRetired(Collection* coll); void itemUnlockFinished(const QHash& results, AuthDecision forFutureEntries); void unlockItems(); @@ -176,6 +180,10 @@ namespace FdoSecrets QHash>> m_items; QHash m_entryToItems; + // collections whose doUnlock was issued and whose outcome is still awaited + QSet m_pendingCollections; + bool m_unlockItemsStarted = false; + QList m_unlocked; int m_numRejected = 0; diff --git a/src/fdosecrets/objects/Service.cpp b/src/fdosecrets/objects/Service.cpp index e3fcefeb5..60ad9a756 100644 --- a/src/fdosecrets/objects/Service.cpp +++ b/src/fdosecrets/objects/Service.cpp @@ -580,9 +580,12 @@ namespace FdoSecrets return; } - // insert a dummy one here, just to prevent multiple dialogs - // the real one will be inserted in onDatabaseUnlockDialogFinished - m_unlockingDb[dbWidget] = {}; + // insert the entry here already, just to prevent multiple dialogs. + // the connection on databaseUnlocked will be added in onDatabaseUnlockDialogFinished. + // if the widget is destroyed while its dialog is open, dialogFinished may never + // fire for it, so clean up on destruction as well. + m_unlockingDb[dbWidget].destroyedConn = + connect(dbWidget, &QObject::destroyed, this, [this, dbWidget]() { m_unlockingDb.remove(dbWidget); }); // actually show the dialog m_databases->unlockDatabaseInDialog(dbWidget, DatabaseOpenDialog::Intent::None); @@ -608,16 +611,25 @@ namespace FdoSecrets if (!accepted) { emit doneUnlockDatabaseInDialog(false, dbWidget); m_unlockingAnyDatabase = false; - m_unlockingDb.remove(dbWidget); + disconnect(m_unlockingDb.take(dbWidget).destroyedConn); } else { // delay the done signal to when the database is actually done with unlocking // this is a oneshot connection to prevent superfluous signals auto conn = connect(dbWidget, &DatabaseWidget::databaseUnlocked, this, [dbWidget, this]() { emit doneUnlockDatabaseInDialog(true, dbWidget); m_unlockingAnyDatabase = false; - disconnect(m_unlockingDb.take(dbWidget)); + auto entry = m_unlockingDb.take(dbWidget); + disconnect(entry.unlockedConn); + disconnect(entry.destroyedConn); }); - m_unlockingDb[dbWidget] = conn; + auto& entry = m_unlockingDb[dbWidget]; + entry.unlockedConn = conn; + // the unlock-any-database flow arrives here without a prior entry, + // make sure widget destruction cleans it up in that case too + if (!entry.destroyedConn) { + entry.destroyedConn = connect( + dbWidget, &QObject::destroyed, this, [this, dbWidget]() { m_unlockingDb.remove(dbWidget); }); + } } } } // namespace FdoSecrets diff --git a/src/fdosecrets/objects/Service.h b/src/fdosecrets/objects/Service.h index 5ec7499b1..3f4245fb5 100644 --- a/src/fdosecrets/objects/Service.h +++ b/src/fdosecrets/objects/Service.h @@ -175,7 +175,16 @@ namespace FdoSecrets bool m_insideEnsureDefaultAlias{false}; bool m_unlockingAnyDatabase{false}; // list of db currently has unlock dialog shown - QHash m_unlockingDb{}; + struct UnlockingDbEntry + { + // oneshot connection on databaseUnlocked, delaying the done signal + // until the database has actually finished unlocking + QMetaObject::Connection unlockedConn; + // cleanup in case the widget is destroyed while its dialog is open, + // otherwise the stale entry would block unlock dialogs forever + QMetaObject::Connection destroyedConn; + }; + QHash m_unlockingDb{}; QSet m_lockingDb{}; // list of db being locking }; diff --git a/src/gui/DatabaseTabWidget.cpp b/src/gui/DatabaseTabWidget.cpp index 82a146821..64ba17abb 100644 --- a/src/gui/DatabaseTabWidget.cpp +++ b/src/gui/DatabaseTabWidget.cpp @@ -385,8 +385,27 @@ bool DatabaseTabWidget::closeDatabaseTab(DatabaseWidget* dbWidget) return false; } + // Closing may spin a nested event loop (e.g. save-on-close waits for the worker + // thread in AsyncTask), from which this method can be re-entered for the same + // widget. QWidget::close() would then report success right away without + // delivering another close event, and deleting the widget here would leave the + // outer invocation operating on a destroyed widget. Let only the outermost + // invocation remove the tab and schedule deletion. + if (m_widgetsPendingClose.contains(dbWidget)) { + return false; + } + QString filePath = dbWidget->database()->filePath(); - if (!dbWidget->close()) { + m_widgetsPendingClose.insert(dbWidget); + bool closed = dbWidget->close(); + m_widgetsPendingClose.remove(dbWidget); + if (!closed) { + return false; + } + + // the tab layout may have shifted while nested event loops ran during close + tabIndex = indexOf(dbWidget); + if (tabIndex < 0) { return false; } diff --git a/src/gui/DatabaseTabWidget.h b/src/gui/DatabaseTabWidget.h index 5f71fb4d7..fba8a58db 100644 --- a/src/gui/DatabaseTabWidget.h +++ b/src/gui/DatabaseTabWidget.h @@ -23,6 +23,7 @@ #include "gui/MessageWidget.h" #include "wizard/ImportWizard.h" +#include #include #include @@ -127,6 +128,7 @@ private: QPointer m_importWizard; QTimer m_lockDelayTimer; bool m_databaseOpenInProgress; + QSet m_widgetsPendingClose; }; #endif // KEEPASSXC_DATABASETABWIDGET_H diff --git a/tests/gui/TestGuiFdoSecrets.cpp b/tests/gui/TestGuiFdoSecrets.cpp index 80d0d4eb9..b75e30c64 100644 --- a/tests/gui/TestGuiFdoSecrets.cpp +++ b/tests/gui/TestGuiFdoSecrets.cpp @@ -586,6 +586,84 @@ void TestGuiFdoSecrets::testServiceUnlockDatabaseConcurrent() DBUS_COMPARE(coll->locked(), false); } +void TestGuiFdoSecrets::testServiceUnlockConcurrentDelete() +{ + lockDatabaseInBackend(); + + auto service = enableService(); + VERIFY(service); + auto coll = getDefaultCollection(service); + VERIFY(coll); + + DBUS_GET2(unlocked, promptPath, service->Unlock({QDBusObjectPath(coll->path())})); + COMPARE(unlocked, {}); + + auto prompt = getProxy(promptPath); + VERIFY(prompt); + QSignalSpy spyPromptCompleted(prompt.data(), SIGNAL(Completed(bool, QDBusVariant))); + VERIFY(spyPromptCompleted.isValid()); + + // show the unlock dialog, but do not interact with it + DBUS_VERIFY(prompt->Prompt("")); + VERIFY(waitForSignal(spyPromptCompleted, 0)); + + // while the unlock prompt is waiting for the user, the collection gets deleted + DBUS_GET(deletePromptPath, coll->Delete()); + auto deletePrompt = getProxy(deletePromptPath); + VERIFY(deletePrompt); + QSignalSpy spyDeletePromptCompleted(deletePrompt.data(), SIGNAL(Completed(bool, QDBusVariant))); + VERIFY(spyDeletePromptCompleted.isValid()); + DBUS_VERIFY(deletePrompt->Prompt("")); + + // the deletion completes + VERIFY(waitForSignal(spyDeletePromptCompleted, 1)); + { + auto args = spyDeletePromptCompleted.takeFirst(); + COMPARE(args.count(), 2); + COMPARE(args.at(0).toBool(), false); + } + + // the unlock prompt completes as dismissed with nothing unlocked, instead of + // waiting forever for a collection that no longer exists + VERIFY(waitForSignal(spyPromptCompleted, 1)); + { + auto args = spyPromptCompleted.takeFirst(); + COMPARE(args.count(), 2); + COMPARE(args.at(0).toBool(), true); + auto unlockedResult = getSignalVariantArgument>(args.at(1)); + VERIFY(unlockedResult.isEmpty()); + } + + // dismiss the leftover unlock dialog so it does not interfere with other tests + auto dbOpenDlg = m_tabWidget->findChild(); + if (dbOpenDlg && dbOpenDlg->isVisible()) { + dbOpenDlg->reject(); + processEvents(); + } + + // reopen the database; the service must still be able to show unlock dialogs. + // A stale Service::m_unlockingDb entry keyed by the destroyed widget used to + // block the unlock-any-database dialog forever. + m_tabWidget->addDatabaseTab(m_dbFile->fileName(), false, "a"); + m_dbWidget = m_tabWidget->currentDatabaseWidget(); + m_db = m_dbWidget->database(); + processEvents(); + + auto entries = m_db->rootGroup()->entriesRecursive(); + VERIFY(!entries.isEmpty()); + auto title = entries.first()->title(); + + lockDatabaseInBackend(); + + FdoSecrets::settings()->setUnlockBeforeSearch(true); + bool unlockDialogWorks = false; + QTimer::singleShot(50, [&]() { unlockDialogWorks = driveUnlockDialog(); }); + DBUS_GET2(unlockedItems, lockedItems, service->SearchItems({{"Title", title}})); + VERIFY(unlockDialogWorks); + COMPARE(lockedItems, {}); + COMPARE(unlockedItems.size(), 1); +} + void TestGuiFdoSecrets::testServiceUnlockItems() { FdoSecrets::settings()->setConfirmAccessItem(true); @@ -1003,7 +1081,7 @@ void TestGuiFdoSecrets::testCollectionDeleteConcurrent() // before interacting with the prompt, another request come in DBUS_GET(promptPath2, coll->Delete()); - auto prompt2 = getProxy(promptPath); + auto prompt2 = getProxy(promptPath2); VERIFY(prompt2); QSignalSpy spyPromptCompleted2(prompt2.data(), SIGNAL(Completed(bool, QDBusVariant))); VERIFY(spyPromptCompleted2.isValid()); @@ -1015,6 +1093,7 @@ void TestGuiFdoSecrets::testCollectionDeleteConcurrent() // there should be no prompt DBUS_VERIFY(prompt2->Prompt("")); + // the first prompt completes the deletion VERIFY(waitForSignal(spyPromptCompleted, 1)); { auto args = spyPromptCompleted.takeFirst(); @@ -1023,11 +1102,13 @@ void TestGuiFdoSecrets::testCollectionDeleteConcurrent() COMPARE(args.at(1).value().variant().toString(), QStringLiteral("")); } + // the second prompt fails fast as the deletion is still in progress, + // and is reported as dismissed VERIFY(waitForSignal(spyPromptCompleted2, 1)); { auto args = spyPromptCompleted2.takeFirst(); COMPARE(args.count(), 2); - COMPARE(args.at(0).toBool(), false); + COMPARE(args.at(0).toBool(), true); COMPARE(args.at(1).value().variant().toString(), QStringLiteral("")); } diff --git a/tests/gui/TestGuiFdoSecrets.h b/tests/gui/TestGuiFdoSecrets.h index c6809f38b..470833f69 100644 --- a/tests/gui/TestGuiFdoSecrets.h +++ b/tests/gui/TestGuiFdoSecrets.h @@ -72,6 +72,7 @@ private slots: void testServiceSearchForce(); void testServiceUnlock(); void testServiceUnlockDatabaseConcurrent(); + void testServiceUnlockConcurrentDelete(); void testServiceUnlockItems(); void testServiceUnlockItemsIncludeFutureEntries(); void testServiceLock();