diff options
author | Charles Kerr <charles.kerr@canonical.com> | 2016-03-08 22:04:56 -0600 |
---|---|---|
committer | Charles Kerr <charles.kerr@canonical.com> | 2016-03-08 22:04:56 -0600 |
commit | 68b671ce04b8b5d6b37025ad093c73a3e14d4d64 (patch) | |
tree | 1b9d1dca5587219915115c8ccd702cfa6f5fd045 | |
parent | 40f48471fe531ba5b9f1e1c4371f252fca4c2d52 (diff) | |
download | ayatana-indicator-display-68b671ce04b8b5d6b37025ad093c73a3e14d4d64.tar.gz ayatana-indicator-display-68b671ce04b8b5d6b37025ad093c73a3e14d4d64.tar.bz2 ayatana-indicator-display-68b671ce04b8b5d6b37025ad093c73a3e14d4d64.zip |
add fingerprint snap decisions; test with notification dbusmock
-rw-r--r-- | CMakeLists.txt | 13 | ||||
-rw-r--r-- | cmake/FindGMock.cmake | 10 | ||||
-rw-r--r-- | debian/control | 5 | ||||
-rw-r--r-- | src/main.cpp | 9 | ||||
-rw-r--r-- | src/usb-snap.cpp | 254 | ||||
-rw-r--r-- | src/usb-snap.h | 39 | ||||
-rw-r--r-- | tests/CMakeLists.txt | 56 | ||||
-rw-r--r-- | tests/dbus-types.h | 47 | ||||
-rw-r--r-- | tests/usb-snap-test.cpp | 216 |
9 files changed, 611 insertions, 38 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt index 9fa4d10..8b8ef65 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ -project (indicator-display) -cmake_minimum_required (VERSION 2.8.9) +project(indicator-display LANGUAGES C CXX) +cmake_minimum_required(VERSION 2.8.9) list (APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake) @@ -15,9 +15,6 @@ set (SERVICE_EXEC "${PACKAGE}-service") option (enable_tests "Build the package's automatic tests." ON) option (enable_lcov "Generate lcov code coverage reports." ON) -set(THREADS_PREFER_PTHREAD_FLAG ON) -find_package(Threads REQUIRED) - ## ## GNU standard paths ## @@ -33,9 +30,10 @@ set (CMAKE_INSTALL_FULL_PKGLIBEXECDIR "${CMAKE_INSTALL_FULL_LIBEXECDIR}/${CMAKE_ ## Check for prerequisites ## +set(THREADS_PREFER_PTHREAD_FLAG ON) +find_package(Threads REQUIRED) find_package (PkgConfig REQUIRED) -include (FindPkgConfig) pkg_check_modules (SERVICE_DEPS REQUIRED gio-unix-2.0>=2.36 glib-2.0>=2.36) @@ -58,9 +56,6 @@ set (CXX_WARNING_ARGS "${CXX_WARNING_ARGS} -Wno-missing-field-initializers") # G # testing & coverage if (${enable_tests}) - set (GTEST_SOURCE_DIR /usr/src/gtest/src) - set (GTEST_INCLUDE_DIR ${GTEST_SOURCE_DIR}/..) - set (GTEST_LIBS -lpthread) enable_testing () if (${enable_lcov}) include(GCov) diff --git a/cmake/FindGMock.cmake b/cmake/FindGMock.cmake deleted file mode 100644 index 74a1c15..0000000 --- a/cmake/FindGMock.cmake +++ /dev/null @@ -1,10 +0,0 @@ -# Build with system gmock and embedded gtest -set (GMOCK_INCLUDE_DIRS "/usr/include/gmock/include" CACHE PATH "gmock source include directory") -set (GMOCK_SOURCE_DIR "/usr/src/gmock" CACHE PATH "gmock source directory") -set (GTEST_INCLUDE_DIRS "${GMOCK_SOURCE_DIR}/gtest/include" CACHE PATH "gtest source include directory") - -add_subdirectory(${GMOCK_SOURCE_DIR} "${CMAKE_CURRENT_BINARY_DIR}/gmock") - -set(GTEST_LIBRARIES gtest) -set(GTEST_MAIN_LIBRARIES gtest_main) -set(GMOCK_LIBRARIES gmock gmock_main) diff --git a/debian/control b/debian/control index 4f05f74..5088af5 100644 --- a/debian/control +++ b/debian/control @@ -3,12 +3,17 @@ Section: misc Priority: optional Maintainer: Charles Kerr <charles.kerr@canonical.com> Build-Depends: cmake, + cmake-extras (>= 0.4), dbus, libglib2.0-dev (>= 2.36), libproperties-cpp-dev, # for coverage reports lcov, # for tests + qt5-default, + qtbase5-dev, + libqtdbusmock1-dev (>= 0.4), + libqtdbustest1-dev, cppcheck, libgtest-dev, google-mock (>= 1.6.0+svn437), diff --git a/src/main.cpp b/src/main.cpp index 0c56bd6..62eca62 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -20,6 +20,7 @@ #include <src/adbd-client.h> #include <src/exporter.h> #include <src/rotation-lock.h> +#include <src/usb-snap.h> #include <glib/gi18n.h> // bindtextdomain() #include <gio/gio.h> @@ -60,9 +61,11 @@ main(int /*argc*/, char** /*argv*/) static constexpr char const * ADB_SOCKET_PATH {"/dev/socket/adb"}; GAdbdClient adbd_client{ADB_SOCKET_PATH}; adbd_client.on_pk_request().connect([](const AdbdClient::PKRequest& req){ - g_debug("%s got pk_request [%s]", G_STRLOC, req.public_key.c_str()); - // FIXME: actually decide what response to send back - req.respond(AdbdClient::PKResponse::ALLOW); + auto snap = new UsbSnap(req.public_key); + snap->on_user_response().connect([req,snap](AdbdClient::PKResponse response, bool /*FIXME: remember_choice*/){ + req.respond(response); + g_idle_add([](gpointer gsnap){delete static_cast<UsbSnap*>(gsnap); return G_SOURCE_REMOVE;}, snap); // delete-later + }); }); g_main_loop_run(loop); diff --git a/src/usb-snap.cpp b/src/usb-snap.cpp new file mode 100644 index 0000000..40f02a2 --- /dev/null +++ b/src/usb-snap.cpp @@ -0,0 +1,254 @@ +/* + * Copyright 2016 Canonical Ltd. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3, as published + * by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranties of + * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. + * + * Authors: + * Charles Kerr <charles.kerr@canonical.com> + */ + +#include <src/usb-snap.h> + +#include <glib/gi18n.h> +#include <gio/gio.h> + +/*** +**** +***/ + +class UsbSnap::Impl +{ +public: + + explicit Impl(const std::string& fingerprint): + m_fingerprint{fingerprint}, + m_cancellable{g_cancellable_new()} + { + g_bus_get (G_BUS_TYPE_SESSION, m_cancellable, on_bus_ready_static, this); + } + + ~Impl() + { + g_cancellable_cancel(m_cancellable); + g_clear_object(&m_cancellable); + + if (m_subscription_id != 0) + g_dbus_connection_signal_unsubscribe (m_bus, m_subscription_id); + + if (m_notification_id != 0) { + GError* error {}; + g_dbus_connection_call_sync(m_bus, + BUS_NAME, + OBJECT_PATH, + IFACE_NAME, + "CloseNotification", + g_variant_new("(u)", m_notification_id), + nullptr, + G_DBUS_CALL_FLAGS_NONE, + -1, + nullptr, + &error); + if (error != nullptr) { + g_warning("Error closing notification: %s", error->message); + g_clear_error(&error); + } + } + + g_clear_object(&m_bus); + } + + core::Signal<AdbdClient::PKResponse,bool>& on_user_response() + { + return m_on_user_response; + } + +private: + + static void on_bus_ready_static(GObject* /*source*/, GAsyncResult* res, gpointer gself) + { + GError* error {}; + auto bus = g_bus_get_finish (res, &error); + if (error != nullptr) { + if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) + g_warning("UsbSnap: Error getting session bus: %s", error->message); + g_clear_error(&error); + } else { + static_cast<Impl*>(gself)->on_bus_ready(bus); + } + g_clear_object(&bus); + } + + void on_bus_ready(GDBusConnection* bus) + { + m_bus = G_DBUS_CONNECTION(g_object_ref(G_OBJECT(bus))); + + auto body = g_strdup_printf(_("The computer's RSA key fingerprint is: %s"), m_fingerprint.c_str()); + + GVariantBuilder actions_builder; + g_variant_builder_init(&actions_builder, G_VARIANT_TYPE_STRING_ARRAY); + g_variant_builder_add(&actions_builder, "s", ACTION_ALLOW); + g_variant_builder_add(&actions_builder, "s", _("Allow")); + g_variant_builder_add(&actions_builder, "s", ACTION_DENY); + g_variant_builder_add(&actions_builder, "s", _("Deny")); + + GVariantBuilder hints_builder; + g_variant_builder_init(&hints_builder, G_VARIANT_TYPE_VARDICT); + g_variant_builder_add(&hints_builder, "{sv}", "x-canonical-non-shaped-icon", g_variant_new_string("true")); + g_variant_builder_add(&hints_builder, "{sv}", "x-canonical-snap-decisions", g_variant_new_string("true")); + g_variant_builder_add(&hints_builder, "{sv}", "x-canonical-private-affirmative-tint", g_variant_new_string("true")); + + auto args = g_variant_new("(susssasa{sv}i)", + "", + uint32_t(0), + "computer-symbolic", + _("Allow USB Debugging?"), + body, + &actions_builder, + &hints_builder, + -1); + g_dbus_connection_call(m_bus, + BUS_NAME, + OBJECT_PATH, + IFACE_NAME, + "Notify", + args, + G_VARIANT_TYPE("(u)"), + G_DBUS_CALL_FLAGS_NONE, + -1, // timeout + m_cancellable, + on_notify_reply_static, + this); + + g_clear_pointer(&body, g_free); + } + + static void on_notify_reply_static(GObject* obus, GAsyncResult* res, gpointer gself) + { + GError* error {}; + auto reply = g_dbus_connection_call_finish (G_DBUS_CONNECTION(obus), res, &error); + if (error != nullptr) { + if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) + g_warning("UsbSnap: Error calling Notify: %s", error->message); + g_clear_error(&error); + } else { + uint32_t id {}; + g_variant_get(reply, "(u)", &id); + static_cast<Impl*>(gself)->on_notify_reply(id); + } + g_clear_pointer(&reply, g_variant_unref); + } + + void on_notify_reply(uint32_t id) + { + m_notification_id = id; + + m_subscription_id = g_dbus_connection_signal_subscribe(m_bus, + BUS_NAME, + IFACE_NAME, + nullptr, + OBJECT_PATH, + nullptr, + G_DBUS_SIGNAL_FLAGS_NONE, + on_notification_signal_static, + this, + nullptr); + } + + static void on_notification_signal_static(GDBusConnection* /*connection*/, + const gchar* /*sender_name*/, + const gchar* object_path, + const gchar* interface_name, + const gchar* signal_name, + GVariant* parameters, + gpointer gself) + { + g_return_if_fail(!g_strcmp0(object_path, OBJECT_PATH)); + g_return_if_fail(!g_strcmp0(interface_name, IFACE_NAME)); + + auto self = static_cast<Impl*>(gself); + + if (!g_strcmp0(signal_name, "ActionInvoked")) + { + uint32_t id {}; + const char* action_name {}; + g_variant_get(parameters, "(u&s)", &id, &action_name); + if (id == self->m_notification_id) + self->on_action_invoked(action_name); + } + else if (!g_strcmp0(signal_name, "NotificationClosed")) + { + uint32_t id {}; + uint32_t close_reason {}; + g_variant_get(parameters, "(uu)", &id, &close_reason); + if (id == self->m_notification_id) + self->on_notification_closed(close_reason); + } + } + + void on_action_invoked(const char* action_name) + { + const auto response = !g_strcmp0(action_name, ACTION_ALLOW) + ? AdbdClient::PKResponse::ALLOW + : AdbdClient::PKResponse::DENY; + + // FIXME: the current default is to cover the most common use case. + // We need to get the notification ui's checkbox working ASAP so + // that the user can provide this flag + const bool remember_this_choice = response == AdbdClient::PKResponse::ALLOW; + + m_on_user_response(response, remember_this_choice); + } + + void on_notification_closed(uint32_t close_reason) + { + if (close_reason == CloseReason::EXPIRED) + m_on_user_response(AdbdClient::PKResponse::DENY, false); + + m_notification_id = 0; + } + + static constexpr char const * ACTION_ALLOW{"allow"}; + static constexpr char const * ACTION_DENY{"deny"}; + + static constexpr char const * BUS_NAME {"org.freedesktop.Notifications" }; + static constexpr char const * IFACE_NAME {"org.freedesktop.Notifications" }; + static constexpr char const * OBJECT_PATH {"/org/freedesktop/Notifications" }; + enum CloseReason { EXPIRED=1, DISMISSED=2, API=3, UNDEFINED=4 }; + + const std::string m_fingerprint; + core::Signal<AdbdClient::PKResponse,bool> m_on_user_response; + GCancellable* m_cancellable {}; + GDBusConnection* m_bus {}; + uint32_t m_notification_id {}; + unsigned int m_subscription_id {}; +}; + +/*** +**** +***/ + +UsbSnap::UsbSnap(const std::string& public_key): + impl{new Impl{public_key}} +{ +} + +UsbSnap::~UsbSnap() +{ +} + +core::Signal<AdbdClient::PKResponse,bool>& +UsbSnap::on_user_response() +{ + return impl->on_user_response(); +} + diff --git a/src/usb-snap.h b/src/usb-snap.h new file mode 100644 index 0000000..6ad3a4c --- /dev/null +++ b/src/usb-snap.h @@ -0,0 +1,39 @@ +/* + * Copyright 2016 Canonical Ltd. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3, as published + * by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranties of + * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. + * + * Authors: + * Charles Kerr <charles.kerr@canonical.com> + */ + +#pragma once + +#include <src/adbd-client.h> // AdbdClient::PKResponse + +#include <core/signal.h> + +#include <memory> +#include <string> + +class UsbSnap +{ +public: + explicit UsbSnap(const std::string& public_key); + ~UsbSnap(); + core::Signal<AdbdClient::PKResponse,bool>& on_user_response(); + +protected: + class Impl; + std::unique_ptr<Impl> impl; +}; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 706e35b..1fbe407 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,33 +1,57 @@ -include(FindGMock) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}) -include_directories(${GMOCK_INCLUDE_DIRS}) -include_directories(${GTEST_INCLUDE_DIRS}) + +set(CMAKE_AUTOMOC ON) + +find_package(GMock REQUIRED) +find_package(Qt5Core REQUIRED) +find_package(Qt5Test REQUIRED) +find_package(Qt5DBus COMPONENTS Qt5DBusMacros REQUIRED) + +pkg_check_modules(TEST_DEPS + libqtdbustest-1 REQUIRED + libqtdbusmock-1 REQUIRED +) + +include_directories( + ${CMAKE_SOURCE_DIR} + ${CMAKE_CURRENT_BINARY_DIR} + ${CMAKE_CURRENT_SOURCE_DIR} +) +include_directories(SYSTEM + ${DBUSTEST_INCLUDE_DIRS} + ${TEST_DEPS_INCLUDE_DIRS} + ${GTEST_INCLUDE_DIRS} + ${GMOCK_INCLUDE_DIRS} +) set(CTEST_ENVIRONMENT "${CTEST_ENVIRONMENT};G_MESSAGES_DEBUG=all") if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") # turn off the warnings that break Google Test - set (CXX_WARNING_ARGS "${CXX_WARNING_ARGS} -Wno-global-constructors -Wno-weak-vtables -Wno-undef -Wno-c++98-compat-pedantic -Wno-missing-noreturn -Wno-used-but-marked-unused -Wno-padded -Wno-deprecated -Wno-sign-compare -Wno-shift-sign-overflow") + set (CXX_WARNING_ARGS "${CXX_WARNING_ARGS} -Wno-global-constructors -Wno-weak-vtables") endif() -SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -g -pthread ${CXX_WARNING_ARGS}") - -# look for headers in our src dir, and also in the directories where we autogenerate files... -include_directories (${CMAKE_SOURCE_DIR}/src) -include_directories (${CMAKE_CURRENT_BINARY_DIR}) -include_directories (${DBUSTEST_INCLUDE_DIRS}) +SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -std=c++11 -g ${CXX_WARNING_ARGS}") function(add_test_by_name name) set (TEST_NAME ${name}) add_executable (${TEST_NAME} ${TEST_NAME}.cpp) add_test (${TEST_NAME} ${TEST_NAME}) - set_property(TEST ${TEST_NAME} PROPERTY ENVIRONMENT "${CTEST_ENVIRONMENT}") - - add_dependencies (${TEST_NAME} libindicatordisplayservice) - target_link_libraries (${TEST_NAME} indicatordisplayservice ${SERVICE_DEPS_LIBRARIES} ${GTEST_LIBRARIES} ${GMOCK_LIBRARIES}) + set_property(TEST ${TEST_NAME} PROPERTY ENVIRONMENT "${CTEST_ENVIRONMENT}") + add_dependencies (${TEST_NAME} indicatordisplayservice) + target_link_libraries (${TEST_NAME} indicatordisplayservice ${SERVICE_DEPS_LIBRARIES} ${TEST_DEPS_LIBRARIES} ${GTEST_LIBRARIES} ${GMOCK_LIBRARIES}) endfunction() add_test_by_name(rotation-lock-test) add_test_by_name(adbd-client-test) -add_test (cppcheck cppcheck --enable=all -USCHEMA_DIR --error-exitcode=2 --inline-suppr -I${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/tests) +function(add_qt_test_by_name name) + set (TEST_NAME ${name}) + add_executable (${TEST_NAME} ${TEST_NAME}.cpp qmain.cpp) + add_test (${TEST_NAME} ${TEST_NAME}) + set_property(TEST ${TEST_NAME} PROPERTY ENVIRONMENT "${CTEST_ENVIRONMENT}") + add_dependencies (${TEST_NAME} indicatordisplayservice) + target_link_libraries (${TEST_NAME} indicatordisplayservice ${SERVICE_DEPS_LIBRARIES} Qt5::Core Qt5::Test Qt5::DBus ${TEST_DEPS_LIBRARIES} ${GTEST_LIBRARIES} ${GMOCK_LIBRARIES}) +endfunction() +add_qt_test_by_name(usb-snap-test) + +add_test(cppcheck cppcheck --enable=all -USCHEMA_DIR --error-exitcode=2 --inline-suppr -I${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/tests) diff --git a/tests/dbus-types.h b/tests/dbus-types.h new file mode 100644 index 0000000..c2dfb81 --- /dev/null +++ b/tests/dbus-types.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2013-2016 Canonical, Ltd. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3, as published + * by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranties of + * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. + * + * Author: Pete Woods <pete.woods@canonical.com> + */ + +#pragma once + +#include <QDBusMetaType> +#include <QtCore> +#include <QString> +#include <QVariantMap> + +typedef QMap<QString, QVariantMap> QVariantDictMap; +Q_DECLARE_METATYPE(QVariantDictMap) + +typedef QMap<QString, QString> QStringMap; +Q_DECLARE_METATYPE(QStringMap) + +namespace DBusTypes +{ + inline void registerMetaTypes() + { + qRegisterMetaType<QVariantDictMap>("QVariantDictMap"); + qRegisterMetaType<QStringMap>("QStringMap"); + + qDBusRegisterMetaType<QVariantDictMap>(); + qDBusRegisterMetaType<QStringMap>(); + } + static constexpr char const* NOTIFY_DBUS_NAME = "org.freedesktop.Notifications"; + + static constexpr char const* NOTIFY_DBUS_INTERFACE = "org.freedesktop.Notifications"; + + static constexpr char const* NOTIFY_DBUS_PATH = "/org/freedesktop/Notifications"; +} diff --git a/tests/usb-snap-test.cpp b/tests/usb-snap-test.cpp new file mode 100644 index 0000000..309980a --- /dev/null +++ b/tests/usb-snap-test.cpp @@ -0,0 +1,216 @@ +/* + * Copyright 2016 Canonical Ltd. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3, as published + * by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranties of + * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. + * + * Authors: + * Charles Kerr <charles.kerr@canonical.com> + */ + +#define QT_NO_KEYWORDS +#include <tests/dbus-types.h> +#include <tests/glib-fixture.h> + +#include <src/usb-snap.h> + +#include <glib.h> + +#include <libqtdbustest/DBusTestRunner.h> +#include <libqtdbustest/QProcessDBusService.h> +#include <libqtdbusmock/DBusMock.h> + +#include <QSignalSpy> + +#include <gtest/gtest.h> + +using namespace QtDBusTest; +using namespace QtDBusMock; + +inline QString qVariantToString(const QVariant& variant) { + QString output; + QDebug dbg(&output); + dbg << variant; + return output; +} + +inline void PrintTo(const QVariant& variant, std::ostream* os) { + QString output; + QDebug dbg(&output); + dbg << variant; + + *os << "QVariant(" << output.toStdString() << ")"; +} + +inline void PrintTo(const QString& s, std::ostream* os) { + *os << "\"" << s.toStdString() << "\""; +} + +inline void PrintTo(const QStringList& list, std::ostream* os) { + QString output; + QDebug dbg(&output); + dbg << list; + + *os << "QStringList(" << output.toStdString() << ")"; +} + +inline void PrintTo(const QList<QDBusObjectPath>& list, std::ostream* os) { + QString output; + for (const auto& path: list) + { + output.append("\"" + path.path() + "\","); + } + + *os << "QList<QDBusObjectPath>(" << output.toStdString() << ")"; +} + +#define WAIT_FOR_SIGNALS(signalSpy, signalsExpected)\ +{\ + while (signalSpy.size() < signalsExpected)\ + {\ + ASSERT_TRUE(signalSpy.wait());\ + }\ + ASSERT_EQ(signalsExpected, signalSpy.size());\ +} + +class UsbSnapFixture: public GlibFixture +{ + using super = GlibFixture; + +public: + + UsbSnapFixture(): + dbusMock{dbusTestRunner} + { + DBusTypes::registerMetaTypes(); + + dbusTestRunner.startServices(); + } + + ~UsbSnapFixture() =default; + +protected: + + bool qDBusArgumentToMap(QVariant const& variant, QVariantMap& map) + { + if (variant.canConvert<QDBusArgument>()) + { + QDBusArgument value(variant.value<QDBusArgument>()); + if (value.currentType() == QDBusArgument::MapType) + { + value >> map; + return true; + } + } + return false; + } + + void SetUp() override + { + super::SetUp(); + + dbusMock.registerNotificationDaemon(); + dbusTestRunner.startServices(); + } + + OrgFreedesktopDBusMockInterface& notificationsMockInterface() + { + return dbusMock.mockInterface("org.freedesktop.Notifications", + "/org/freedesktop/Notifications", + "org.freedesktop.Notifications", + QDBusConnection::SessionBus); + } + + QtDBusTest::DBusTestRunner dbusTestRunner; + QtDBusMock::DBusMock dbusMock; + QtDBusTest::DBusServicePtr indicator; +}; + +TEST_F(UsbSnapFixture, TestRoundTrip) +{ + struct { + const char* fingerprint; + const char* action_to_invoke; + const AdbdClient::PKResponse expected_response; + } tests[] = { + { "Fingerprint", "allow", AdbdClient::PKResponse::ALLOW }, + { "Fingerprint", "deny", AdbdClient::PKResponse::DENY } + }; + + uint32_t next_id = 1; + for(const auto& test : tests) + { + // Minor wart: we don't have a way of getting the fdo notification id + // from dbusmock so instead we copy its (simple) id generation here + const auto id = next_id++; + + QSignalSpy notificationsSpy( + ¬ificationsMockInterface(), + SIGNAL(MethodCalled(const QString &, const QVariantList &))); + + // start up a UsbSnap to ask about a fingerprint + auto snap = std::make_shared<UsbSnap>(test.fingerprint); + AdbdClient::PKResponse user_response {}; + bool user_response_set = false; + snap->on_user_response().connect([&user_response,&user_response_set](AdbdClient::PKResponse response, bool /*remember*/){ + user_response = response; + user_response_set = true; + }); + + // test that UsbSnap creates a fdo notification + WAIT_FOR_SIGNALS(notificationsSpy, 1); + { + QVariantList const& call(notificationsSpy.at(0)); + EXPECT_EQ("Notify", call.at(0)); + + QVariantList const& args(call.at(1).toList()); + ASSERT_EQ(8, args.size()); + EXPECT_EQ("", args.at(0)); // app name + EXPECT_EQ(0, args.at(1)); // replaces-id + EXPECT_EQ("computer-symbolic", args.at(2)); // icon name + EXPECT_EQ("Allow USB Debugging?", args.at(3)); // summary + EXPECT_EQ(QString::fromUtf8("The computer's RSA key fingerprint is: ") + test.fingerprint, args.at(4)); // body + EXPECT_EQ(QStringList({"allow", "Allow", "deny", "Deny"}), args.at(5)); // actions + EXPECT_EQ(-1, args.at(7)); + + QVariantMap hints; + ASSERT_TRUE(qDBusArgumentToMap(args.at(6), hints)); + ASSERT_EQ(3, hints.size()); + ASSERT_TRUE(hints.contains("x-canonical-private-affirmative-tint")); + ASSERT_TRUE(hints.contains("x-canonical-non-shaped-icon")); + ASSERT_TRUE(hints.contains("x-canonical-snap-decisions")); + } + notificationsSpy.clear(); + + // fake a user interaction with the fdo notification + notificationsMockInterface().EmitSignal( + DBusTypes::NOTIFY_DBUS_INTERFACE, + "ActionInvoked", + "us", + QVariantList() << id << test.action_to_invoke); + + // test that UsbSnap emits on_user_response() as a result + wait_for([&user_response_set](){return user_response_set;}); + EXPECT_TRUE(user_response_set); + ASSERT_EQ(test.expected_response, user_response); + + // confirm that the snap dtor cleans up the notification + snap.reset(); + WAIT_FOR_SIGNALS(notificationsSpy, 1); + { + QVariantList const& call(notificationsSpy.at(0)); + EXPECT_EQ("CloseNotification", call.at(0)); + QVariantList const& args(call.at(1).toList()); + EXPECT_EQ(id, args.at(0)); + } + } +} |