diff --git a/autotests/BackendsManager.cpp b/autotests/BackendsManager.cpp index 9b1b002..0d9d835 100644 --- a/autotests/BackendsManager.cpp +++ b/autotests/BackendsManager.cpp @@ -1,82 +1,69 @@ /* -* Copyright (C) 2012 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2012 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include "BackendsManager.h" #include "BackendsConfig.h" // Include backends directly #include "TestBackend.h" #include "backends/dbus/DBusHelperProxy.h" #include #include #include #include namespace KAuth { AuthBackend *BackendsManager::auth = nullptr; QHash< QThread *, HelperProxy * > proxiesForThreads = QHash< QThread *, HelperProxy * >(); BackendsManager::BackendsManager() { } void BackendsManager::init() { if (!auth) { // Load the test backend auth = new TestBackend; } if (!proxiesForThreads.contains(QThread::currentThread())) { // Load the test helper backend proxiesForThreads.insert(QThread::currentThread(), new DBusHelperProxy(QDBusConnection::sessionBus())); } } AuthBackend *BackendsManager::authBackend() { if (!auth) { init(); } return auth; } HelperProxy *BackendsManager::helperProxy() { if (!proxiesForThreads.contains(QThread::currentThread())) { qDebug() << "Creating new proxy for thread" << QThread::currentThread(); init(); } return proxiesForThreads[QThread::currentThread()]; } void BackendsManager::setProxyForThread(QThread *thread, HelperProxy *proxy) { qDebug() << "Adding proxy for thread" << thread; proxiesForThreads.insert(thread, proxy); } } // namespace Auth diff --git a/autotests/BackendsManager.h b/autotests/BackendsManager.h index 8af772e..95329f9 100644 --- a/autotests/BackendsManager.h +++ b/autotests/BackendsManager.h @@ -1,46 +1,33 @@ /* -* Copyright (C) 2012 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2012 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef BACKENDS_MANAGER_H #define BACKENDS_MANAGER_H #include "AuthBackend.h" #include "HelperProxy.h" namespace KAuth { class BackendsManager { static AuthBackend *auth; static HelperProxy *helper; BackendsManager(); public: static AuthBackend *authBackend(); static HelperProxy *helperProxy(); static void setProxyForThread(QThread *thread, HelperProxy *proxy); private: static void init(); }; } // namespace Auth #endif diff --git a/autotests/HelperTest.cpp b/autotests/HelperTest.cpp index 0102ba0..8b77106 100644 --- a/autotests/HelperTest.cpp +++ b/autotests/HelperTest.cpp @@ -1,244 +1,231 @@ /* -* Copyright (C) 2012 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2012 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include #include #include #include #include #include #include #include #include "BackendsManager.h" #include "TestHelper.h" #include "../src/backends/dbus/DBusHelperProxy.h" Q_DECLARE_METATYPE(KAuth::Action::AuthStatus) class HelperHandler : public QObject { Q_OBJECT public: HelperHandler(); private Q_SLOTS: void init(); Q_SIGNALS: void ready(); private: DBusHelperProxy *m_helperProxy; TestHelper *m_helper; QThread *m_thread; }; class HelperTest : public QObject { Q_OBJECT public: HelperTest(QObject *parent = nullptr) : QObject(parent) { } private Q_SLOTS: void initTestCase(); void init() {} void testBasicActionExecution(); void testExecuteJobSignals(); void testTwoCalls(); void testActionData(); void testHelperFailure(); void cleanup() {} void cleanupTestCase() {} Q_SIGNALS: void changeCapabilities(KAuth::AuthBackend::Capabilities capabilities); private: HelperHandler *m_handler; }; HelperHandler::HelperHandler() : QObject(nullptr) { /* Hello adventurer. What you see here might hurt your eyes, but let me explain why you don't want to touch this code. We are dealing with same-process async DBus requests, and if this seems obscure to you already please give up and forget about this function. Qt's local loop optimizations at the moment make it impossible to stream an async request to a process living on the same thread. So that's what we do: we instantiate a separate helperProxy and move it to a different thread - afterwards we can do everything as if we were in a separate process. If you are wondering if this means we'll have two helper proxies, you are right my friend. But please remember that helperProxy acts both as a client and as a server, so it makes total sense. tl;dr: Don't touch this and forget the weird questions in your head: it actually works. */ m_thread = new QThread(this); moveToThread(m_thread); connect(m_thread, SIGNAL(started()), this, SLOT(init())); m_thread->start(); } void HelperHandler::init() { qDebug() << "Initializing helper handler"; // Set up our Helper - of course, it is not in a separate process here so we need to copy what // HelperProxy::helperMain() does m_helperProxy = new DBusHelperProxy(QDBusConnection::sessionBus()); m_helper = new TestHelper; // The timer is here just to prevent the app from crashing. QTimer *timer = new QTimer(nullptr); QVERIFY(m_helperProxy->initHelper(QLatin1String("org.kde.kf5auth.autotest"))); m_helperProxy->setHelperResponder(m_helper); m_helper->setProperty("__KAuth_Helper_Shutdown_Timer", QVariant::fromValue(timer)); timer->setInterval(10000); timer->start(); // Make BackendsManager aware BackendsManager::setProxyForThread(m_thread, m_helperProxy); emit ready(); } void HelperTest::initTestCase() { connect(this, SIGNAL(changeCapabilities(KAuth::AuthBackend::Capabilities)), KAuth::BackendsManager::authBackend(), SLOT(setNewCapabilities(KAuth::AuthBackend::Capabilities))); qRegisterMetaType(); qRegisterMetaType(); // Set up our HelperHandler m_handler = new HelperHandler; QEventLoop e; connect(m_handler, SIGNAL(ready()), &e, SLOT(quit())); qDebug() << "Waiting for HelperHandler to be initialized"; e.exec(); } void HelperTest::testBasicActionExecution() { emit changeCapabilities(KAuth::AuthBackend::AuthorizeFromHelperCapability | KAuth::AuthBackend::CheckActionExistenceCapability); KAuth::Action action(QLatin1String("org.kde.kf5auth.autotest.standardaction")); action.setHelperId(QLatin1String("org.kde.kf5auth.autotest")); QVERIFY(action.isValid()); QCOMPARE(action.status(), KAuth::Action::AuthRequiredStatus); KAuth::ExecuteJob *job = action.execute(); QVERIFY(job->exec()); QVERIFY(!job->error()); QVERIFY(job->data().isEmpty()); } void HelperTest::testExecuteJobSignals() { KAuth::Action action(QLatin1String("org.kde.kf5auth.autotest.longaction")); action.setHelperId(QLatin1String("org.kde.kf5auth.autotest")); QVERIFY(action.isValid()); QCOMPARE(action.status(), KAuth::Action::AuthRequiredStatus); KAuth::ExecuteJob *job = action.execute(); QSignalSpy finishedSpy(job, SIGNAL(result(KJob*))); QSignalSpy newDataSpy(job, SIGNAL(newData(QVariantMap))); QSignalSpy percentSpy(job, SIGNAL(percent(KJob*,ulong))); QSignalSpy statusChangedSpy(job, SIGNAL(statusChanged(KAuth::Action::AuthStatus))); QVERIFY(job->exec()); QCOMPARE(finishedSpy.size(), 1); QCOMPARE(qobject_cast(finishedSpy.first().first().value()), job); QCOMPARE(statusChangedSpy.size(), 1); QCOMPARE(statusChangedSpy.first().first().value(), KAuth::Action::AuthorizedStatus); QCOMPARE(percentSpy.size(), 100); for (ulong i = 1; i <= 100; ++i) { QCOMPARE((unsigned long)percentSpy.at(i - 1).last().toLongLong(), i); QCOMPARE(qobject_cast(percentSpy.at(i - 1).first().value()), job); } QCOMPARE(newDataSpy.size(), 1); QCOMPARE(newDataSpy.first().first().value().value(QLatin1String("Answer")).toInt(), 42); QVERIFY(!job->error()); QVERIFY(job->data().isEmpty()); } void HelperTest::testTwoCalls() { KAuth::Action action(QLatin1String("org.kde.kf5auth.autotest.standardaction")); action.setHelperId(QLatin1String("org.kde.kf5auth.autotest")); QVERIFY(action.isValid()); QCOMPARE(action.status(), KAuth::Action::AuthRequiredStatus); KAuth::ExecuteJob *job = action.execute(); QVERIFY(job->exec()); job = action.execute(); QVERIFY(job->exec()); } void HelperTest::testActionData() { KAuth::Action action(QLatin1String("org.kde.kf5auth.autotest.echoaction")); action.setHelperId(QLatin1String("org.kde.kf5auth.autotest")); QVariantMap args; // Fill with random data (and test heavy structures while we're at it) auto *generator = QRandomGenerator::global(); for (int i = 0; i < 150; ++i) { args.insert(QUuid::createUuid().toString(), generator->generate()); } action.setArguments(args); QVERIFY(action.isValid()); QCOMPARE(action.status(), KAuth::Action::AuthRequiredStatus); KAuth::ExecuteJob *job = action.execute(); QVERIFY(job->exec()); QVERIFY(!job->error()); QCOMPARE(job->data(), args); } void HelperTest::testHelperFailure() { KAuth::Action action(QLatin1String("org.kde.kf5auth.autotest.failingaction")); action.setHelperId(QLatin1String("org.kde.kf5auth.autotest")); QVERIFY(action.isValid()); QCOMPARE(action.status(), KAuth::Action::AuthRequiredStatus); KAuth::ExecuteJob *job = action.execute(); QVERIFY(!job->exec()); QVERIFY(job->error()); } QTEST_MAIN(HelperTest) #include "HelperTest.moc" diff --git a/autotests/SetupActionTest.cpp b/autotests/SetupActionTest.cpp index 5dd6530..f2bc778 100644 --- a/autotests/SetupActionTest.cpp +++ b/autotests/SetupActionTest.cpp @@ -1,202 +1,189 @@ /* -* Copyright (C) 2012 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2012 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include #include #include #include #include "BackendsManager.h" class SetupActionTest : public QObject { Q_OBJECT public: SetupActionTest(QObject *parent = nullptr) : QObject(parent) { } private Q_SLOTS: void initTestCase(); void init() {} void testNonExistentAction(); #if KAUTHCORE_BUILD_DEPRECATED_SINCE(5, 71) void testBasicActionPropertiesDeprecated(); #endif void testBasicActionProperties(); void testUserAuthorization(); void testAuthorizationFail(); void cleanup() {} void cleanupTestCase() {} Q_SIGNALS: void changeCapabilities(KAuth::AuthBackend::Capabilities capabilities); private: }; void SetupActionTest::initTestCase() { connect(this, SIGNAL(changeCapabilities(KAuth::AuthBackend::Capabilities)), KAuth::BackendsManager::authBackend(), SLOT(setNewCapabilities(KAuth::AuthBackend::Capabilities))); } void SetupActionTest::testNonExistentAction() { emit changeCapabilities(KAuth::AuthBackend::AuthorizeFromHelperCapability | KAuth::AuthBackend::CheckActionExistenceCapability); KAuth::Action action(QLatin1String("i.do.not.exist")); QVERIFY(!action.isValid()); action = KAuth::Action(QLatin1String("/safinvalid124%$&")); QVERIFY(action.isValid()); // Now with regexp check emit changeCapabilities(KAuth::AuthBackend::NoCapability); action = KAuth::Action(QLatin1String("/safinvalid124%$&")); QVERIFY(!action.isValid()); } #if KAUTHCORE_BUILD_DEPRECATED_SINCE(5, 71) void SetupActionTest::testBasicActionPropertiesDeprecated() { emit changeCapabilities(KAuth::AuthBackend::AuthorizeFromHelperCapability | KAuth::AuthBackend::CheckActionExistenceCapability); KAuth::Action::DetailsMap detailsMap{{KAuth::Action::AuthDetail::DetailOther, QLatin1String("details")}}; KAuth::Action action(QLatin1String("always.authorized"), QLatin1String("details")); QVERIFY(action.isValid()); QCOMPARE(action.name(), QLatin1String("always.authorized")); QCOMPARE(action.details(), QLatin1String("details")); QCOMPARE(action.detailsV2(), detailsMap); QVERIFY(!action.hasHelper()); QVERIFY(action.helperId().isEmpty()); QCOMPARE(action.status(), KAuth::Action::AuthorizedStatus); QVERIFY(action.arguments().isEmpty()); QVariantMap args; args.insert(QLatin1String("akey"), QVariant::fromValue(42)); action.setArguments(args); QCOMPARE(action.arguments(), args); action.setName(QLatin1String("i.do.not.exist")); QVERIFY(!action.isValid()); emit changeCapabilities(KAuth::AuthBackend::NoCapability); action = KAuth::Action(QLatin1String("i.do.not.exist"), QLatin1String("details")); QVERIFY(action.isValid()); QCOMPARE(action.name(), QLatin1String("i.do.not.exist")); QCOMPARE(action.details(), QLatin1String("details")); QCOMPARE(action.detailsV2(), detailsMap); QVERIFY(!action.hasHelper()); QVERIFY(action.helperId().isEmpty()); QCOMPARE(action.status(), KAuth::Action::InvalidStatus); } #endif void SetupActionTest::testBasicActionProperties() { emit changeCapabilities(KAuth::AuthBackend::AuthorizeFromHelperCapability | KAuth::AuthBackend::CheckActionExistenceCapability); KAuth::Action::DetailsMap detailsMap{{KAuth::Action::AuthDetail::DetailOther, QLatin1String("details")}}; KAuth::Action action(QLatin1String("always.authorized"), detailsMap); QVERIFY(action.isValid()); QCOMPARE(action.name(), QLatin1String("always.authorized")); #if KAUTHCORE_BUILD_DEPRECATED_SINCE(5, 71) QCOMPARE(action.details(), QLatin1String("details")); #endif QCOMPARE(action.detailsV2(), detailsMap); QVERIFY(!action.hasHelper()); QVERIFY(action.helperId().isEmpty()); QCOMPARE(action.status(), KAuth::Action::AuthorizedStatus); QVERIFY(action.arguments().isEmpty()); QVariantMap args; args.insert(QLatin1String("akey"), QVariant::fromValue(42)); action.setArguments(args); QCOMPARE(action.arguments(), args); action.setName(QLatin1String("i.do.not.exist")); QVERIFY(!action.isValid()); emit changeCapabilities(KAuth::AuthBackend::NoCapability); action = KAuth::Action(QLatin1String("i.do.not.exist"), detailsMap); QVERIFY(action.isValid()); QCOMPARE(action.name(), QLatin1String("i.do.not.exist")); #if KAUTHCORE_BUILD_DEPRECATED_SINCE(5, 71) QCOMPARE(action.details(), QLatin1String("details")); #endif QCOMPARE(action.detailsV2(), detailsMap); QVERIFY(!action.hasHelper()); QVERIFY(action.helperId().isEmpty()); QCOMPARE(action.status(), KAuth::Action::InvalidStatus); } void SetupActionTest::testUserAuthorization() { emit changeCapabilities(KAuth::AuthBackend::CheckActionExistenceCapability); KAuth::Action::DetailsMap detailsMap{{KAuth::Action::AuthDetail::DetailOther, QLatin1String("details")}}; KAuth::Action action(QLatin1String("requires.auth"), detailsMap); QVERIFY(action.isValid()); QCOMPARE(action.status(), KAuth::Action::AuthRequiredStatus); KAuth::ExecuteJob *job = action.execute(); QVERIFY(!job->exec()); QCOMPARE(job->error(), (int)KAuth::ActionReply::BackendError); emit changeCapabilities(KAuth::AuthBackend::CheckActionExistenceCapability | KAuth::AuthBackend::AuthorizeFromClientCapability); QVERIFY(action.isValid()); QCOMPARE(action.status(), KAuth::Action::AuthRequiredStatus); job = action.execute(); QVERIFY(job->exec()); QVERIFY(!job->error()); QVERIFY(job->data().isEmpty()); } void SetupActionTest::testAuthorizationFail() { emit changeCapabilities(KAuth::AuthBackend::CheckActionExistenceCapability | KAuth::AuthBackend::AuthorizeFromClientCapability); KAuth::Action::DetailsMap detailsMap{{KAuth::Action::AuthDetail::DetailOther, QLatin1String("details")}}; KAuth::Action action(QLatin1String("doomed.to.fail"), detailsMap); QVERIFY(action.isValid()); QCOMPARE(action.status(), KAuth::Action::DeniedStatus); KAuth::ExecuteJob *job = action.execute(); QVERIFY(!job->exec()); QCOMPARE(job->error(), (int)KAuth::ActionReply::AuthorizationDeniedError); QVERIFY(job->data().isEmpty()); } QTEST_MAIN(SetupActionTest) #include "SetupActionTest.moc" diff --git a/autotests/TestBackend.cpp b/autotests/TestBackend.cpp index 85a14ec..c424c9e 100644 --- a/autotests/TestBackend.cpp +++ b/autotests/TestBackend.cpp @@ -1,122 +1,109 @@ /* -* Copyright (C) 2012 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2012 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include "TestBackend.h" #include namespace KAuth { TestBackend::TestBackend() : AuthBackend() { qDebug() << "Test backend loaded"; setCapabilities(AuthorizeFromHelperCapability | CheckActionExistenceCapability); } void TestBackend::setNewCapabilities(AuthBackend::Capabilities capabilities) { qDebug() << "Capabilities changing"; setCapabilities(capabilities); } Action::AuthStatus TestBackend::authorizeAction(const QString &action) { if (action == QLatin1String("doomed.to.fail")) { return Action::DeniedStatus; } return Action::AuthorizedStatus; } void TestBackend::setupAction(const QString &action) { if (action == QLatin1String("doomed.to.fail")) { m_actionStatuses.insert(action, Action::DeniedStatus); } else if (action == QLatin1String("requires.auth") || action == QLatin1String("generates.error")) { m_actionStatuses.insert(action, Action::AuthRequiredStatus); } else if (action == QLatin1String("always.authorized")) { m_actionStatuses.insert(action, Action::AuthorizedStatus); } else if (action.startsWith(QLatin1String("org.kde.kf5auth.autotest"))) { m_actionStatuses.insert(action, Action::AuthRequiredStatus); } } Action::AuthStatus TestBackend::actionStatus(const QString &action) { if (m_actionStatuses.contains(action)) { return m_actionStatuses.value(action); } return Action::InvalidStatus; } QByteArray TestBackend::callerID() const { return QByteArray("a random caller Id"); } bool TestBackend::isCallerAuthorized(const QString &action, const QByteArray &callerId, const QVariantMap &details) { Q_UNUSED(details); if (action == QLatin1String("doomed.to.fail")) { return false; } else if (action == QLatin1String("requires.auth")) { m_actionStatuses.insert(action, Action::AuthorizedStatus); emit actionStatusChanged(action, Action::AuthorizedStatus); return true; } else if (action == QLatin1String("generates.error")) { m_actionStatuses.insert(action, Action::ErrorStatus); emit actionStatusChanged(action, Action::ErrorStatus); return false; } else if (action == QLatin1String("always.authorized")) { return true; } else if (action.startsWith(QLatin1String("org.kde.kf5auth.autotest"))) { qDebug() << "Caller ID:" << callerId; if (callerId == callerID()) { m_actionStatuses.insert(action, Action::AuthorizedStatus); emit actionStatusChanged(action, Action::AuthorizedStatus); return true; } else { m_actionStatuses.insert(action, Action::DeniedStatus); emit actionStatusChanged(action, Action::DeniedStatus); } } return false; } bool TestBackend::actionExists(const QString &action) { qDebug() << "Checking if action " << action << "exists"; if (action != QLatin1String("doomed.to.fail") && action != QLatin1String("requires.auth") && action != QLatin1String("generates.error") && action != QLatin1String("always.authorized") && action != QLatin1String("/safinvalid124%$&") && !action.startsWith(QLatin1String("org.kde.kf5auth.autotest"))) { return false; } return true; } } // namespace Auth diff --git a/autotests/TestBackend.h b/autotests/TestBackend.h index e590c34..47185f0 100644 --- a/autotests/TestBackend.h +++ b/autotests/TestBackend.h @@ -1,54 +1,41 @@ /* -* Copyright (C) 2012 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2012 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef TEST_BACKEND_H #define TEST_BACKEND_H #include "AuthBackend.h" #include class QByteArray; namespace KAuth { class TestBackend : public AuthBackend { Q_OBJECT Q_INTERFACES(KAuth::AuthBackend) public: TestBackend(); void setupAction(const QString &) override; Action::AuthStatus authorizeAction(const QString &) override; Action::AuthStatus actionStatus(const QString &) override; QByteArray callerID() const override; bool isCallerAuthorized(const QString &action, const QByteArray &callerID, const QVariantMap &details) override; bool actionExists(const QString &action) override; public Q_SLOTS: void setNewCapabilities(KAuth::AuthBackend::Capabilities capabilities); private: QHash m_actionStatuses; }; } // namespace Auth #endif diff --git a/autotests/TestHelper.cpp b/autotests/TestHelper.cpp index f62cfeb..9efe704 100644 --- a/autotests/TestHelper.cpp +++ b/autotests/TestHelper.cpp @@ -1,73 +1,60 @@ /* -* Copyright (C) 2012 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2012 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include "TestHelper.h" #include #include #include #include #include #include ActionReply TestHelper::echoaction(QVariantMap args) { qDebug() << "Echo action running"; ActionReply reply = ActionReply::SuccessReply(); reply.setData(args); return reply; } ActionReply TestHelper::standardaction(QVariantMap args) { qDebug() << "Standard action running"; if (args.contains(QLatin1String("fail")) && args[QLatin1String("fail")].toBool()) { return ActionReply::HelperErrorReply(); } return ActionReply::SuccessReply(); } ActionReply TestHelper::longaction(QVariantMap args) { Q_UNUSED(args); qDebug() << "Long action running. Don't be scared, this action takes 2 seconds to complete"; for (int i = 1; i <= 100; i++) { if (HelperSupport::isStopped()) { break; } if (i == 50) { QVariantMap map; map.insert(QLatin1String("Answer"), 42); HelperSupport::progressStep(map); } HelperSupport::progressStep(i); QThread::usleep(20000); } return ActionReply::SuccessReply(); } ActionReply TestHelper::failingaction(QVariantMap args) { Q_UNUSED(args) return ActionReply::HelperErrorReply(); } diff --git a/autotests/TestHelper.h b/autotests/TestHelper.h index 81a1349..41ab0fd 100644 --- a/autotests/TestHelper.h +++ b/autotests/TestHelper.h @@ -1,40 +1,27 @@ /* -* Copyright (C) 2012 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2012 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef TEST_HELPER_H #define TEST_HELPER_H #include #include using namespace KAuth; class TestHelper : public QObject { Q_OBJECT public Q_SLOTS: ActionReply echoaction(QVariantMap args); ActionReply standardaction(QVariantMap args); ActionReply longaction(QVariantMap args); ActionReply failingaction(QVariantMap args); }; #endif diff --git a/cmake/COPYING-CMAKE-SCRIPTS b/cmake/COPYING-CMAKE-SCRIPTS deleted file mode 100644 index 53b6b71..0000000 --- a/cmake/COPYING-CMAKE-SCRIPTS +++ /dev/null @@ -1,22 +0,0 @@ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -1. Redistributions of source code must retain the copyright - notice, this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. -3. The name of the author may not be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR -IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/cmake/FindPolkitQt-1.cmake b/cmake/FindPolkitQt-1.cmake index e398bd0..14eef81 100644 --- a/cmake/FindPolkitQt-1.cmake +++ b/cmake/FindPolkitQt-1.cmake @@ -1,58 +1,35 @@ # - Try to find PolkitQt-1 # Once done this will define # # POLKITQT-1_FOUND - system has Polkit-qt # POLKITQT-1_INCLUDE_DIR - the Polkit-qt include directory # POLKITQT-1_LIBRARIES - Link these to use all Polkit-qt libs # POLKITQT-1_CORE_LIBRARY - Link this to use the polkit-qt-core library only # POLKITQT-1_GUI_LIBRARY - Link this to use GUI elements in polkit-qt (polkit-qt-gui) # POLKITQT-1_AGENT_LIBRARY - Link this to use the agent wrapper in polkit-qt # POLKITQT-1_DEFINITIONS - Compiler switches required for using Polkit-qt # # The minimum required version of PolkitQt-1 can be specified using the # standard syntax, e.g. find_package(PolkitQt-1 1.0) -# Copyright (c) 2009, Dario Freddi, -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. Neither the name of the University nor the names of its contributors -# may be used to endorse or promote products derived from this software -# without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE -# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -# SUCH DAMAGE. +# SPDX-FileCopyrightText: 2009 Dario Freddi +# SPDX-License-Identifier: BSD-3-Clause # Support POLKITQT-1_MIN_VERSION for compatibility: if ( NOT PolkitQt-1_FIND_VERSION AND POLKITQT-1_MIN_VERSION ) set ( PolkitQt-1_FIND_VERSION ${POLKITQT-1_MIN_VERSION} ) endif ( NOT PolkitQt-1_FIND_VERSION AND POLKITQT-1_MIN_VERSION ) set( _PolkitQt-1_FIND_QUIETLY ${PolkitQt-1_FIND_QUIETLY} ) find_package( PolkitQt-1 ${PolkitQt-1_FIND_VERSION} QUIET NO_MODULE PATHS ${LIB_INSTALL_DIR}/PolkitQt-1/cmake ) set( PolkitQt-1_FIND_QUIETLY ${_PolkitQt-1_FIND_QUIETLY} ) include( FindPackageHandleStandardArgs ) find_package_handle_standard_args( PolkitQt-1 DEFAULT_MSG PolkitQt-1_CONFIG ) if (POLKITQT-1_FOUND) if (NOT POLKITQT-1_INSTALL_DIR STREQUAL CMAKE_INSTALL_PREFIX) message("WARNING: Installation prefix does not match PolicyKit install prefixes. You probably will need to move files installed " "in POLICY_FILES_INSTALL_DIR and by dbus_add_activation_system_service to the ${PC_POLKITQT-1_PREFIX} prefix") endif (NOT POLKITQT-1_INSTALL_DIR STREQUAL CMAKE_INSTALL_PREFIX) endif (POLKITQT-1_FOUND) diff --git a/cmake/FindPolkitQt.cmake b/cmake/FindPolkitQt.cmake index 2fb6866..c89704a 100644 --- a/cmake/FindPolkitQt.cmake +++ b/cmake/FindPolkitQt.cmake @@ -1,115 +1,91 @@ # - Try to find Polkit-qt # Once done this will define # # POLKITQT_FOUND - system has Polkit-qt # POLKITQT_INCLUDE_DIR - the Polkit-qt include directory # POLKITQT_LIBRARIES - Link these to use all Polkit-qt libs # POLKITQT_CORE_LIBRARY - Link this to use the polkit-qt-core library only # POLKITQT_GUI_LIBRARY - Link this to use GUI elements in polkit-qt (polkit-qt-gui) # POLKITQT_DEFINITIONS - Compiler switches required for using Polkit-qt # POLKITQT_POLICY_FILES_INSTALL_DIR - The directory where policy files should be installed to. # # The minimum required version of PolkitQt can be specified using the # standard syntax, e.g. find_package(PolkitQt 1.0) # For compatibility, this can also be done by setting the POLKITQT_MIN_VERSION variable. -# Copyright (c) 2009, Daniel Nicoletti, -# Copyright (c) 2009, Dario Freddi, -# Copyright (c) 2009, Michal Malek, -# Copyright (c) 2009, Alexander Neundorf, -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. Neither the name of the University nor the names of its contributors -# may be used to endorse or promote products derived from this software -# without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE -# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -# SUCH DAMAGE. - +# SPDX-FileCopyrightText: 2009 Daniel Nicoletti +# SPDX-FileCopyrightText: 2009 Dario Freddi +# SPDX-FileCopyrightText: 2009 Michal Malek +# SPDX-FileCopyrightText: 2009 Alexander Neundorf +# SPDX-License-Identifier: BSD-3-Clause # Support POLKITQT_MIN_VERSION for compatibility: if(NOT PolkitQt_FIND_VERSION) set(PolkitQt_FIND_VERSION "${POLKITQT_MIN_VERSION}") endif(NOT PolkitQt_FIND_VERSION) # the minimum version of PolkitQt we require if(NOT PolkitQt_FIND_VERSION) set(PolkitQt_FIND_VERSION "0.9.3") endif(NOT PolkitQt_FIND_VERSION) if (NOT WIN32) # use pkg-config to get the directories and then use these values # in the FIND_PATH() and FIND_LIBRARY() calls find_package(PkgConfig) pkg_check_modules(PC_POLKITQT QUIET polkit-qt) set(POLKITQT_DEFINITIONS ${PC_POLKITQT_CFLAGS_OTHER}) endif (NOT WIN32) find_path( POLKITQT_INCLUDE_DIR NAMES polkit-qt/auth.h PATH_SUFFIXES PolicyKit ) find_file( POLKITQT_VERSION_FILE polkit-qt/polkitqtversion.h HINTS ${POLKITQT_INCLUDE_DIR} ) if(POLKITQT_VERSION_FILE AND NOT POLKITQT_VERSION) file(READ ${POLKITQT_VERSION_FILE} POLKITQT_VERSION_CONTENT) string (REGEX MATCH "POLKITQT_VERSION_STRING \".*\"\n" POLKITQT_VERSION_MATCH "${POLKITQT_VERSION_CONTENT}") if(POLKITQT_VERSION_MATCH) string(REGEX REPLACE "POLKITQT_VERSION_STRING \"(.*)\"\n" "\\1" _POLKITQT_VERSION ${POLKITQT_VERSION_MATCH}) endif(POLKITQT_VERSION_MATCH) set(POLKITQT_VERSION "${_POLKITQT_VERSION}" CACHE STRING "Version number of PolkitQt" FORCE) endif(POLKITQT_VERSION_FILE AND NOT POLKITQT_VERSION) find_library( POLKITQT_CORE_LIBRARY NAMES polkit-qt-core HINTS ${PC_POLKITQT_LIBDIR} ) find_library( POLKITQT_GUI_LIBRARY NAMES polkit-qt-gui HINTS ${PC_POLKITQT_LIBDIR} ) set(POLKITQT_LIBRARIES ${POLKITQT_GUI_LIBRARY} ${POLKITQT_CORE_LIBRARY}) include(FindPackageHandleStandardArgs) # Use the extended (new) syntax for FPHSA(): find_package_handle_standard_args(PolkitQt REQUIRED_VARS POLKITQT_GUI_LIBRARY POLKITQT_CORE_LIBRARY POLKITQT_INCLUDE_DIR VERSION_VAR POLKITQT_VERSION) mark_as_advanced(POLKITQT_INCLUDE_DIR POLKITQT_CORE_LIBRARY POLKITQT_GUI_LIBRARY POLKITQT_VERSION_FILE ) set(POLKITQT_POLICY_FILES_INSTALL_DIR share/PolicyKit/policy/) if(POLKITQT_FOUND) get_filename_component(_POLKITQT_INSTALL_PREFIX "${POLKITQT_CORE_LIBRARY}" PATH) get_filename_component(_POLKITQT_INSTALL_PREFIX "${_POLKITQT_INSTALL_PREFIX}" PATH) if ( NOT _POLKITQT_INSTALL_PREFIX STREQUAL CMAKE_INSTALL_PREFIX ) message("WARNING: Installation prefix does not match PolicyKit install prefixes. You probably will need to move files installed " "in ${CMAKE_INSTALL_PREFIX}/${POLKITQT_POLICY_FILES_INSTALL_DIR} and by dbus_add_activation_system_service to the ${_POLKITQT_INSTALL_PREFIX}/${POLKITQT_POLICY_FILES_INSTALL_DIR} prefix") endif (NOT _POLKITQT_INSTALL_PREFIX STREQUAL CMAKE_INSTALL_PREFIX) endif(POLKITQT_FOUND) diff --git a/cmake/KF5AuthMacros.cmake b/cmake/KF5AuthMacros.cmake index 46dad1c..d2d7b65 100644 --- a/cmake/KF5AuthMacros.cmake +++ b/cmake/KF5AuthMacros.cmake @@ -1,77 +1,54 @@ -# Copyright (c) 2006-2009 Alexander Neundorf, -# Copyright (c) 2006, 2007, Laurent Montel, -# Copyright (c) 2007 Matthias Kretz -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. Neither the name of the University nor the names of its contributors -# may be used to endorse or promote products derived from this software -# without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE -# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -# SUCH DAMAGE. +# SPDX-FileCopyrightText: 2006-2009 Alexander Neundorf +# SPDX-FileCopyrightText: 2006, 2007 Laurent Montel +# SPDX-FileCopyrightText: 2007 Matthias Kretz +# SPDX-License-Identifier: BSD-3-Clause # This macro adds the needed files for an helper executable meant to be used by applications using KAuth. # It accepts the helper target, the helper ID (the DBUS name) and the user under which the helper will run on. # This macro takes care of generate the needed files, and install them in the right location. This boils down # to a DBus policy to let the helper register on the system bus, and a service file for letting the helper # being automatically activated by the system bus. # *WARNING* You have to install the helper in ${KAUTH_HELPER_INSTALL_DIR} to make sure everything will work. function(KAUTH_INSTALL_HELPER_FILES HELPER_TARGET HELPER_ID HELPER_USER) if(KAUTH_HELPER_BACKEND_NAME STREQUAL "DBUS") configure_file(${KAUTH_STUB_FILES_DIR}/dbus_policy.stub ${CMAKE_CURRENT_BINARY_DIR}/${HELPER_ID}.conf) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${HELPER_ID}.conf DESTINATION ${KDE_INSTALL_DBUSDIR}/system.d/) configure_file(${KAUTH_STUB_FILES_DIR}/dbus_service.stub ${CMAKE_CURRENT_BINARY_DIR}/${HELPER_ID}.service) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${HELPER_ID}.service DESTINATION ${DBUS_SYSTEM_SERVICES_INSTALL_DIR}) endif() endfunction() # This macro generates an action file, depending on the backend used, for applications using KAuth. # It accepts the helper id (the DBUS name) and a file containing the actions (check kdelibs/kdecore/auth/example # for file format). The macro will take care of generating the file according to the backend specified, # and to install it in the right location. This (at the moment) means that on Linux (PolicyKit) a .policy # file will be generated and installed into the policykit action directory (usually /usr/share/PolicyKit/policy/), # and on Mac (Authorization Services) will be added to the system action registry using the native MacOS API during # the install phase function(KAUTH_INSTALL_ACTIONS HELPER_ID ACTIONS_FILE) if(KAUTH_BACKEND_NAME STREQUAL "APPLE" OR KAUTH_BACKEND_NAME STREQUAL "OSX") get_target_property(kauth_policy_gen KF5::kauth-policy-gen LOCATION) install(CODE "execute_process(COMMAND ${kauth_policy_gen} ${ACTIONS_FILE} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})") message(STATUS "installation will execute ${kauth_policy_gen} ${ACTIONS_FILE} in ${CMAKE_CURRENT_SOURCE_DIR}") elseif(KAUTH_BACKEND_NAME STREQUAL "POLKITQT" OR KAUTH_BACKEND_NAME STREQUAL "POLKITQT5-1") set(_output ${CMAKE_CURRENT_BINARY_DIR}/${HELPER_ID}.policy) get_filename_component(_input ${ACTIONS_FILE} ABSOLUTE) add_custom_command(OUTPUT ${_output} COMMAND KF5::kauth-policy-gen ${_input} ${_output} MAIN_DEPENDENCY ${_input} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMENT "Generating ${HELPER_ID}.policy" DEPENDS KF5::kauth-policy-gen) add_custom_target(${HELPER_ID}.policy-customtarget ALL COMMENT "actions for ${HELPER_ID}" DEPENDS ${_output}) install(FILES ${_output} DESTINATION ${KAUTH_POLICY_FILES_INSTALL_DIR}) endif() endfunction() diff --git a/cmake/rules_PyKF5.py b/cmake/rules_PyKF5.py index b34c3c9..71822eb 100644 --- a/cmake/rules_PyKF5.py +++ b/cmake/rules_PyKF5.py @@ -1,41 +1,18 @@ -# -# Copyright 2016 Stephen Kelly -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# 1. Redistributions of source code must retain the copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. The name of the author may not be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR -# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# SPDX-FileCopyrightText: 2016 Stephen Kelly +# SPDX-License-Identifier: BSD-3-Clause import os, sys import rules_engine sys.path.append(os.path.dirname(os.path.dirname(rules_engine.__file__))) import Qt5Ruleset def local_function_rules(): return [ ["KAuth::ActionReply", "ActionReply", ".*", ".*", ".*int.*", rules_engine.function_discard], ] class RuleSet(Qt5Ruleset.RuleSet): def __init__(self): Qt5Ruleset.RuleSet.__init__(self) self._fn_db = rules_engine.FunctionRuleDb(lambda: local_function_rules() + Qt5Ruleset.function_rules()) diff --git a/examples/client.cpp b/examples/client.cpp index fe7e88a..28f5f1e 100644 --- a/examples/client.cpp +++ b/examples/client.cpp @@ -1,51 +1,38 @@ /* - * Copyright (C) 2017 Elvis Angelaccio - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation; either version 2.1 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License - * along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . - */ + SPDX-FileCopyrightText: 2017 Elvis Angelaccio + + SPDX-License-Identifier: LGPL-2.1-or-later +*/ #undef QT_NO_CAST_FROM_ASCII #include #include #include using namespace KAuth; int main(int argc, char **argv) { QCoreApplication app(argc, argv); QString filename = "foo.txt"; //! [client_how_to_call_helper] QVariantMap args; args["filename"] = filename; Action readAction("org.kde.kf5auth.example.read"); readAction.setHelperId("org.kde.kf5auth.example"); readAction.setArguments(args); ExecuteJob *job = readAction.execute(); if (!job->exec()) { qDebug() << "KAuth returned an error code:" << job->error(); } else { QString contents = job->data()["contents"].toString(); } //! [client_how_to_call_helper] return app.exec(); } diff --git a/examples/helper.cpp b/examples/helper.cpp index 041b19a..6839c8b 100644 --- a/examples/helper.cpp +++ b/examples/helper.cpp @@ -1,84 +1,71 @@ /* - * Copyright (C) 2017 Elvis Angelaccio - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation; either version 2.1 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License - * along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . - */ + SPDX-FileCopyrightText: 2017 Elvis Angelaccio + + SPDX-License-Identifier: LGPL-2.1-or-later +*/ #undef QT_NO_CAST_FROM_ASCII #include #include #include //! [helper_declaration] #include using namespace KAuth; class MyHelper : public QObject { Q_OBJECT public Q_SLOTS: ActionReply read(const QVariantMap& args); ActionReply write(const QVariantMap& args); ActionReply longaction(const QVariantMap& args); }; //! [helper_declaration] //! [helper_read_action] ActionReply MyHelper::read(const QVariantMap& args) { ActionReply reply; QString filename = args["filename"].toString(); QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { reply = ActionReply::HelperErrorReply(); reply.setErrorDescription(file.errorString()); return reply; } QTextStream stream(&file); QString contents; stream >> contents; reply.addData("contents", contents); return reply; } //! [helper_read_action] ActionReply MyHelper::write(const QVariantMap &args) { Q_UNUSED(args) return ActionReply::SuccessReply(); } //! [helper_longaction] ActionReply MyHelper::longaction(const QVariantMap&) { for (int i = 1; i <= 100; i++) { if (HelperSupport::isStopped()) break; HelperSupport::progressStep(i); QThread::usleep(250000); } return ActionReply::SuccessReply(); } //! [helper_longaction] //! [helper_main] KAUTH_HELPER_MAIN("org.kde.kf5auth.example", MyHelper) //! [helper_main] #include "helper.moc" diff --git a/src/AuthBackend.cpp b/src/AuthBackend.cpp index c9edab5..aa63017 100644 --- a/src/AuthBackend.cpp +++ b/src/AuthBackend.cpp @@ -1,81 +1,68 @@ /* -* Copyright (C) 2008 Nicola Gigante -* Copyright (C) 2010 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + SPDX-FileCopyrightText: 2010 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include "AuthBackend.h" namespace KAuth { class AuthBackend::Private { public: Private() {} virtual ~Private() {} Capabilities capabilities; }; AuthBackend::AuthBackend() : QObject(nullptr) , d(new Private) { } AuthBackend::~AuthBackend() { delete d; } AuthBackend::Capabilities AuthBackend::capabilities() const { return d->capabilities; } void AuthBackend::setCapabilities(AuthBackend::Capabilities capabilities) { d->capabilities = capabilities; } AuthBackend::ExtraCallerIDVerificationMethod AuthBackend::extraCallerIDVerificationMethod() const { return NoExtraCallerIDVerificationMethod; } bool AuthBackend::actionExists(const QString &action) { Q_UNUSED(action); return false; } void AuthBackend::preAuthAction(const QString &action, QWidget *parent) { Q_UNUSED(action) Q_UNUSED(parent) } QVariantMap AuthBackend::backendDetails(const DetailsMap &details) { Q_UNUSED(details); return QVariantMap(); } } //namespace KAuth diff --git a/src/AuthBackend.h b/src/AuthBackend.h index 139786e..28c955e 100644 --- a/src/AuthBackend.h +++ b/src/AuthBackend.h @@ -1,84 +1,71 @@ /* -* Copyright (C) 2008 Nicola Gigante -* Copyright (C) 2009-2010 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + SPDX-FileCopyrightText: 2009-2010 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef AUTH_BACKEND_H #define AUTH_BACKEND_H #include #include "kauthaction.h" namespace KAuth { typedef Action::DetailsMap DetailsMap; class AuthBackend : public QObject { Q_OBJECT Q_DISABLE_COPY(AuthBackend) public: enum Capability { NoCapability = 0, AuthorizeFromClientCapability = 1, AuthorizeFromHelperCapability = 2, CheckActionExistenceCapability = 4, PreAuthActionCapability = 8 }; Q_DECLARE_FLAGS(Capabilities, Capability) enum ExtraCallerIDVerificationMethod { NoExtraCallerIDVerificationMethod, VerifyAgainstDBusServiceName, VerifyAgainstDBusServicePid, }; AuthBackend(); virtual ~AuthBackend(); virtual void setupAction(const QString &action) = 0; virtual void preAuthAction(const QString &action, QWidget *parent); virtual Action::AuthStatus authorizeAction(const QString &action) = 0; virtual Action::AuthStatus actionStatus(const QString &action) = 0; virtual QByteArray callerID() const = 0; virtual ExtraCallerIDVerificationMethod extraCallerIDVerificationMethod() const; virtual bool isCallerAuthorized(const QString &action, const QByteArray &callerID, const QVariantMap &details) = 0; virtual bool actionExists(const QString &action); virtual QVariantMap backendDetails(const DetailsMap &details); Capabilities capabilities() const; protected: void setCapabilities(Capabilities capabilities); Q_SIGNALS: void actionStatusChanged(const QString &action, KAuth::Action::AuthStatus status); private: class Private; Private *const d; }; } // namespace Auth Q_DECLARE_INTERFACE(KAuth::AuthBackend, "org.kde.kf5auth.AuthBackend/0.1") Q_DECLARE_OPERATORS_FOR_FLAGS(KAuth::AuthBackend::Capabilities) #endif diff --git a/src/BackendsManager.cpp b/src/BackendsManager.cpp index 447c584..84de2c1 100644 --- a/src/BackendsManager.cpp +++ b/src/BackendsManager.cpp @@ -1,132 +1,119 @@ /* -* Copyright (C) 2009 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2009 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include "BackendsManager.h" #include "BackendsConfig.h" // Include fake backends #include "backends/fake/FakeBackend.h" #include "backends/fakehelper/FakeHelperProxy.h" #include "kauthdebug.h" #include #include #include namespace KAuth { AuthBackend *BackendsManager::auth = nullptr; HelperProxy *BackendsManager::helper = nullptr; BackendsManager::BackendsManager() { } QList< QObject * > BackendsManager::retrieveInstancesIn(const QString &path) { QList retlist; QDir pluginPath(path); if (!pluginPath.exists() || path.isEmpty()) { return retlist; } const QFileInfoList entryList = pluginPath.entryInfoList(QDir::NoDotAndDotDot | QDir::Files); for (const QFileInfo &fi : entryList) { const QString filePath = fi.filePath(); // file name with path //QString fileName = fi.fileName(); // just file name if (!QLibrary::isLibrary(filePath)) { continue; } QPluginLoader loader(filePath); QObject *instance = loader.instance(); if (instance) { retlist.append(instance); } else { qCWarning(KAUTH) << "Couldn't load" << filePath << "error:" << loader.errorString(); } } return retlist; } void BackendsManager::init() { // Backend plugin const QList< QObject * > backends = retrieveInstancesIn(QFile::decodeName(KAUTH_BACKEND_PLUGIN_DIR)); for (QObject *instance : backends) { auth = qobject_cast< KAuth::AuthBackend * >(instance); if (auth) { break; } } // Helper plugin const QList< QObject * > helpers = retrieveInstancesIn(QFile::decodeName(KAUTH_HELPER_PLUGIN_DIR)); for (QObject *instance : helpers) { helper = qobject_cast< KAuth::HelperProxy * >(instance); if (helper) { break; } } if (!auth) { // Load the fake auth backend then auth = new FakeBackend; #if !KAUTH_COMPILING_FAKE_BACKEND // Spit a fat warning qCWarning(KAUTH) << "WARNING: KAuth was compiled with a working backend, but was unable to load it! Check your installation!"; #endif } if (!helper) { // Load the fake helper backend then helper = new FakeHelperProxy; #if !KAUTH_COMPILING_FAKE_BACKEND // Spit a fat warning qCWarning(KAUTH) << "WARNING: KAuth was compiled with a working helper backend, but was unable to load it! " "Check your installation!"; #endif } } AuthBackend *BackendsManager::authBackend() { if (!auth) { init(); } return auth; } HelperProxy *BackendsManager::helperProxy() { if (!helper) { init(); } return helper; } } // namespace Auth diff --git a/src/BackendsManager.h b/src/BackendsManager.h index 164daf2..e077831 100644 --- a/src/BackendsManager.h +++ b/src/BackendsManager.h @@ -1,48 +1,35 @@ /* -* Copyright (C) 2008 Nicola Gigante -* Copyright (C) 2009 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + SPDX-FileCopyrightText: 2009 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef BACKENDS_MANAGER_H #define BACKENDS_MANAGER_H #include "AuthBackend.h" #include "HelperProxy.h" #include namespace KAuth { class KAUTHCORE_EXPORT BackendsManager { static AuthBackend *auth; static HelperProxy *helper; BackendsManager(); public: static AuthBackend *authBackend(); static HelperProxy *helperProxy(); private: static void init(); static QList retrieveInstancesIn(const QString &path); }; } // namespace Auth #endif diff --git a/src/HelperProxy.cpp b/src/HelperProxy.cpp index 2e7f364..8813a13 100644 --- a/src/HelperProxy.cpp +++ b/src/HelperProxy.cpp @@ -1,30 +1,17 @@ /* -* Copyright (C) 2008 Nicola Gigante -* Copyright (C) 2009 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + SPDX-FileCopyrightText: 2009 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include "HelperProxy.h" namespace KAuth { HelperProxy::~HelperProxy() {} } // namespace KAuth #include "moc_HelperProxy.cpp" diff --git a/src/HelperProxy.h b/src/HelperProxy.h index 06b0c29..00327aa 100644 --- a/src/HelperProxy.h +++ b/src/HelperProxy.h @@ -1,68 +1,55 @@ /* -* Copyright (C) 2008 Nicola Gigante -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + + SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef HELPER_PROXY_H #define HELPER_PROXY_H #include #include #include #include #include "kauthaction.h" #include "kauthactionreply.h" namespace KAuth { typedef Action::DetailsMap DetailsMap; class HelperProxy : public QObject { Q_OBJECT public: virtual ~HelperProxy(); // Application-side methods virtual void executeAction(const QString &action, const QString &helperID, const DetailsMap &details, const QVariantMap &arguments, int timeout) = 0; virtual void stopAction(const QString &action, const QString &helperID) = 0; // Helper-side methods virtual bool initHelper(const QString &name) = 0; virtual void setHelperResponder(QObject *o) = 0; virtual bool hasToStopAction() = 0; virtual void sendDebugMessage(int level, const char *msg) = 0; virtual void sendProgressStep(int step) = 0; virtual void sendProgressStep(const QVariantMap &step) = 0; Q_SIGNALS: void actionStarted(const QString &action); void actionPerformed(const QString &action, const KAuth::ActionReply &reply); void progressStep(const QString &action, int progress); void progressStep(const QString &action, const QVariantMap &data); }; } // namespace KAuth Q_DECLARE_INTERFACE(KAuth::HelperProxy, "org.kde.kf5auth.HelperProxy/0.1") #endif diff --git a/src/backends/dbus/DBusHelperProxy.cpp b/src/backends/dbus/DBusHelperProxy.cpp index d7007bb..8439b0d 100644 --- a/src/backends/dbus/DBusHelperProxy.cpp +++ b/src/backends/dbus/DBusHelperProxy.cpp @@ -1,365 +1,352 @@ /* -* Copyright (C) 2008 Nicola Gigante -* Copyright (C) 2009-2010 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + SPDX-FileCopyrightText: 2009-2010 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include "DBusHelperProxy.h" #include #include #include #include #include #include #include #include "BackendsManager.h" #include "kf5authadaptor.h" #include "kauthdebug.h" extern Q_CORE_EXPORT const QMetaTypeInterface *qMetaTypeGuiHelper; namespace KAuth { static void debugMessageReceived(int t, const QString &message); DBusHelperProxy::DBusHelperProxy() : responder(nullptr) , m_stopRequest(false) , m_busConnection(QDBusConnection::systemBus()) { } DBusHelperProxy::DBusHelperProxy(const QDBusConnection &busConnection) : responder(nullptr) , m_stopRequest(false) , m_busConnection(busConnection) { } DBusHelperProxy::~DBusHelperProxy() { } void DBusHelperProxy::stopAction(const QString &action, const QString &helperID) { QDBusMessage message; message = QDBusMessage::createMethodCall(helperID, QLatin1String("/"), QLatin1String("org.kde.kf5auth"), QLatin1String("stopAction")); QList args; args << action; message.setArguments(args); m_busConnection.asyncCall(message); } void DBusHelperProxy::executeAction(const QString &action, const QString &helperID, const DetailsMap &details, const QVariantMap &arguments, int timeout) { QByteArray blob; { QDataStream stream(&blob, QIODevice::WriteOnly); stream << arguments; } //on unit tests we won't have a service, but the service will already be running const auto reply = m_busConnection.interface()->startService(helperID); if (!reply.isValid() && !m_busConnection.interface()->isServiceRegistered(helperID)) { ActionReply errorReply = ActionReply::DBusErrorReply(); errorReply.setErrorDescription(tr("DBus Backend error: service start %1 failed: %2").arg(helperID, reply.error().message())); emit actionPerformed(action, errorReply); return; } const bool connected = m_busConnection.connect(helperID, QLatin1String("/"), QLatin1String("org.kde.kf5auth"), QLatin1String("remoteSignal"), this, SLOT(remoteSignalReceived(int,QString,QByteArray))); //if already connected reply will be false but we won't have an error or a reason to fail if (!connected && m_busConnection.lastError().isValid()) { ActionReply errorReply = ActionReply::DBusErrorReply(); errorReply.setErrorDescription(tr("DBus Backend error: connection to helper failed. %1\n(application: %2 helper: %3)").arg( m_busConnection.lastError().message(), qApp->applicationName(), helperID)); emit actionPerformed(action, errorReply); return; } QDBusMessage message; message = QDBusMessage::createMethodCall(helperID, QLatin1String("/"), QLatin1String("org.kde.kf5auth"), QLatin1String("performAction")); QList args; args << action << BackendsManager::authBackend()->callerID() << BackendsManager::authBackend()->backendDetails(details) << blob; message.setArguments(args); m_actionsInProgress.push_back(action); QDBusPendingCall pendingCall = m_busConnection.asyncCall(message, timeout); auto watcher = new QDBusPendingCallWatcher(pendingCall, this); connect(watcher, &QDBusPendingCallWatcher::finished, this, [=] () mutable { watcher->deleteLater(); QDBusMessage reply = watcher->reply(); if (reply.type() == QDBusMessage::ErrorMessage) { if (watcher->error().type() == QDBusError::InvalidArgs) { // For backwards compatibility if helper binary was built with older KAuth version. args.removeAt(args.count() - 2); // remove backend details message.setArguments(args); reply = m_busConnection.call(message, QDBus::Block, timeout); if (reply.type() != QDBusMessage::ErrorMessage) { return; } } ActionReply r = ActionReply::DBusErrorReply(); r.setErrorDescription(tr("DBus Backend error: could not contact the helper. " "Connection error: %1. Message error: %2").arg(reply.errorMessage(), m_busConnection.lastError().message())); qCWarning(KAUTH) << reply.errorMessage(); emit actionPerformed(action, r); } }); } bool DBusHelperProxy::initHelper(const QString &name) { new Kf5authAdaptor(this); if (!m_busConnection.registerService(name)) { qCWarning(KAUTH) << "Error registering helper DBus service" << name << m_busConnection.lastError().message(); return false; } if (!m_busConnection.registerObject(QLatin1String("/"), this)) { qCWarning(KAUTH) << "Error registering helper DBus object:" << m_busConnection.lastError().message(); return false; } m_name = name; return true; } void DBusHelperProxy::setHelperResponder(QObject *o) { responder = o; } void DBusHelperProxy::remoteSignalReceived(int t, const QString &action, QByteArray blob) { SignalType type = static_cast(t); QDataStream stream(&blob, QIODevice::ReadOnly); if (type == ActionStarted) { emit actionStarted(action); } else if (type == ActionPerformed) { ActionReply reply = ActionReply::deserialize(blob); m_actionsInProgress.removeOne(action); emit actionPerformed(action, reply); } else if (type == DebugMessage) { int level; QString message; stream >> level >> message; debugMessageReceived(level, message); } else if (type == ProgressStepIndicator) { int step; stream >> step; emit progressStep(action, step); } else if (type == ProgressStepData) { QVariantMap data; stream >> data; emit progressStep(action, data); } } void DBusHelperProxy::stopAction(const QString &action) { Q_UNUSED(action) //#warning FIXME: The stop request should be action-specific rather than global m_stopRequest = true; } bool DBusHelperProxy::hasToStopAction() { QEventLoop loop; loop.processEvents(QEventLoop::AllEvents); return m_stopRequest; } bool DBusHelperProxy::isCallerAuthorized(const QString &action, const QByteArray &callerID, const QVariantMap &details) { // Check the caller is really who it says it is switch (BackendsManager::authBackend()->extraCallerIDVerificationMethod()) { case AuthBackend::NoExtraCallerIDVerificationMethod: break; case AuthBackend::VerifyAgainstDBusServiceName: if (message().service().toUtf8() != callerID) { return false; } break; case AuthBackend::VerifyAgainstDBusServicePid: if (connection().interface()->servicePid(message().service()).value() != callerID.toUInt()) { return false; } break; } return BackendsManager::authBackend()->isCallerAuthorized(action, callerID, details); } QByteArray DBusHelperProxy::performAction(const QString &action, const QByteArray &callerID, const QVariantMap &details, QByteArray arguments) { if (!responder) { return ActionReply::NoResponderReply().serialized(); } if (!m_currentAction.isEmpty()) { return ActionReply::HelperBusyReply().serialized(); } // Make sure we don't try restoring gui variants, in particular QImage/QPixmap/QIcon are super dangerous // since they end up calling the image loaders and thus are a vector for crashing → executing code auto origMetaTypeGuiHelper = qMetaTypeGuiHelper; qMetaTypeGuiHelper = nullptr; QVariantMap args; QDataStream s(&arguments, QIODevice::ReadOnly); s >> args; qMetaTypeGuiHelper = origMetaTypeGuiHelper; m_currentAction = action; emit remoteSignal(ActionStarted, action, QByteArray()); QEventLoop e; e.processEvents(QEventLoop::AllEvents); ActionReply retVal; QTimer *timer = responder->property("__KAuth_Helper_Shutdown_Timer").value(); timer->stop(); if (isCallerAuthorized(action, callerID, details)) { QString slotname = action; if (slotname.startsWith(m_name + QLatin1Char('.'))) { slotname = slotname.right(slotname.length() - m_name.length() - 1); } slotname.replace(QLatin1Char('.'), QLatin1Char('_')); // For legacy reasons we could be dealing with ActionReply types (i.e. // `using namespace KAuth`). Since Qt type names are verbatim this would // mismatch a return type that is called 'KAuth::ActionReply' and // vice versa. This effectively required client code to always 'use' the // namespace as otherwise we'd not be able to call into it. // To support both scenarios we now dynamically determine what kind of return type // we deal with and call Q_RETURN_ARG either with or without namespace. const auto metaObj = responder->metaObject(); const QString slotSignature(slotname + QStringLiteral("(QVariantMap)")); const QMetaMethod method = metaObj->method(metaObj->indexOfMethod(qPrintable(slotSignature))); if (method.isValid()) { const auto needle = "KAuth::"; bool success = false; if (strncmp(needle, method.typeName(), strlen(needle)) == 0) { success = method.invoke(responder, Qt::DirectConnection, Q_RETURN_ARG(KAuth::ActionReply, retVal), Q_ARG(QVariantMap, args)); } else { success = method.invoke(responder, Qt::DirectConnection, Q_RETURN_ARG(ActionReply, retVal), Q_ARG(QVariantMap, args)); } if (!success) { retVal = ActionReply::NoSuchActionReply(); } } else { retVal = ActionReply::NoSuchActionReply(); } } else { retVal = ActionReply::AuthorizationDeniedReply(); } timer->start(); emit remoteSignal(ActionPerformed, action, retVal.serialized()); e.processEvents(QEventLoop::AllEvents); m_currentAction.clear(); m_stopRequest = false; return retVal.serialized(); } void DBusHelperProxy::sendDebugMessage(int level, const char *msg) { QByteArray blob; QDataStream stream(&blob, QIODevice::WriteOnly); stream << level << QString::fromLocal8Bit(msg); emit remoteSignal(DebugMessage, m_currentAction, blob); } void DBusHelperProxy::sendProgressStep(int step) { QByteArray blob; QDataStream stream(&blob, QIODevice::WriteOnly); stream << step; emit remoteSignal(ProgressStepIndicator, m_currentAction, blob); } void DBusHelperProxy::sendProgressStep(const QVariantMap &data) { QByteArray blob; QDataStream stream(&blob, QIODevice::WriteOnly); stream << data; emit remoteSignal(ProgressStepData, m_currentAction, blob); } void debugMessageReceived(int t, const QString &message) { QtMsgType type = static_cast(t); switch (type) { case QtDebugMsg: qDebug("Debug message from helper: %s", message.toLatin1().data()); break; case QtInfoMsg: qInfo("Info message from helper: %s", message.toLatin1().data()); break; case QtWarningMsg: qWarning("Warning from helper: %s", message.toLatin1().data()); break; case QtCriticalMsg: qCritical("Critical warning from helper: %s", message.toLatin1().data()); break; case QtFatalMsg: qFatal("Fatal error from helper: %s", message.toLatin1().data()); break; } } } // namespace Auth diff --git a/src/backends/dbus/DBusHelperProxy.h b/src/backends/dbus/DBusHelperProxy.h index 5cd2efe..80080a2 100644 --- a/src/backends/dbus/DBusHelperProxy.h +++ b/src/backends/dbus/DBusHelperProxy.h @@ -1,89 +1,76 @@ /* -* Copyright (C) 2008 Nicola Gigante -* Copyright (C) 2009 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + SPDX-FileCopyrightText: 2009 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef DBUS_HELPER_PROXY_H #define DBUS_HELPER_PROXY_H #include "HelperProxy.h" #include "kauthactionreply.h" #include #include #include namespace KAuth { class DBusHelperProxy : public HelperProxy, protected QDBusContext { Q_OBJECT Q_PLUGIN_METADATA(IID "org.kde.DBusHelperProxy") Q_INTERFACES(KAuth::HelperProxy) QObject *responder; QString m_name; QString m_currentAction; bool m_stopRequest; QList m_actionsInProgress; QDBusConnection m_busConnection; enum SignalType { ActionStarted, // The blob argument is empty ActionPerformed, // The blob argument contains the ActionReply DebugMessage, // The blob argument contains the debug level and the message (in this order) ProgressStepIndicator, // The blob argument contains the step indicator ProgressStepData // The blob argument contains the QVariantMap }; public: DBusHelperProxy(); DBusHelperProxy(const QDBusConnection &busConnection); ~DBusHelperProxy() override; virtual void executeAction(const QString &action, const QString &helperID, const DetailsMap &details, const QVariantMap &arguments, int timeout = -1) override; void stopAction(const QString &action, const QString &helperID) override; bool initHelper(const QString &name) override; void setHelperResponder(QObject *o) override; bool hasToStopAction() override; void sendDebugMessage(int level, const char *msg) override; void sendProgressStep(int step) override; void sendProgressStep(const QVariantMap &data) override; public Q_SLOTS: void stopAction(const QString &action); QByteArray performAction(const QString &action, const QByteArray &callerID, const QVariantMap &details, QByteArray arguments); Q_SIGNALS: void remoteSignal(int type, const QString &action, const QByteArray &blob); // This signal is sent from the helper to the app private Q_SLOTS: void remoteSignalReceived(int type, const QString &action, QByteArray blob); private: bool isCallerAuthorized(const QString &action, const QByteArray &callerID, const QVariantMap &details); }; } // namespace Auth #endif diff --git a/src/backends/fake/FakeBackend.cpp b/src/backends/fake/FakeBackend.cpp index 022de89..db314c4 100644 --- a/src/backends/fake/FakeBackend.cpp +++ b/src/backends/fake/FakeBackend.cpp @@ -1,61 +1,48 @@ /* -* Copyright (C) 2008 Nicola Gigante -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include "FakeBackend.h" namespace KAuth { FakeBackend::FakeBackend() : AuthBackend() { setCapabilities(NoCapability); } Action::AuthStatus FakeBackend::authorizeAction(const QString &action) { Q_UNUSED(action) return Action::DeniedStatus; } void FakeBackend::setupAction(const QString &action) { Q_UNUSED(action) } Action::AuthStatus FakeBackend::actionStatus(const QString &action) { Q_UNUSED(action) return Action::DeniedStatus; } QByteArray FakeBackend::callerID() const { return QByteArray(); } bool FakeBackend::isCallerAuthorized(const QString &action, const QByteArray &callerID, const QVariantMap &details) { Q_UNUSED(action) Q_UNUSED(callerID) Q_UNUSED(details) return false; } } // namespace Auth diff --git a/src/backends/fake/FakeBackend.h b/src/backends/fake/FakeBackend.h index 9a0be1b..869fb91 100644 --- a/src/backends/fake/FakeBackend.h +++ b/src/backends/fake/FakeBackend.h @@ -1,47 +1,34 @@ /* -* Copyright (C) 2008 Nicola Gigante -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + + SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef FAKE_BACKEND_H #define FAKE_BACKEND_H #include "AuthBackend.h" #include class QByteArray; namespace KAuth { class FakeBackend : public AuthBackend { Q_OBJECT Q_INTERFACES(KAuth::AuthBackend) public: FakeBackend(); void setupAction(const QString &) override; Action::AuthStatus authorizeAction(const QString &) override; Action::AuthStatus actionStatus(const QString &) override; QByteArray callerID() const override; bool isCallerAuthorized(const QString &action, const QByteArray &callerID, const QVariantMap &details) override; }; } // namespace Auth #endif diff --git a/src/backends/fake/kauth-policy-gen-polkit.cpp b/src/backends/fake/kauth-policy-gen-polkit.cpp index 728ae0f..ad0e4a3 100644 --- a/src/backends/fake/kauth-policy-gen-polkit.cpp +++ b/src/backends/fake/kauth-policy-gen-polkit.cpp @@ -1,82 +1,69 @@ /* -* Copyright (C) 2008 Nicola Gigante -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include #include #include #include const char header[] = "" "\n" "\n" "\n"; const char policy_tag[] = "" " \n" " no\n" " %1\n" " \n"; const char dent[] = " "; void output(const QList &actions, const QMap &domain) { Q_UNUSED(domain) QTextStream out(stdout); out.setCodec("UTF-8"); out << header; for (const Action &action : qAsConst(actions)) { out << dent << "\n"; const auto lstKeys = action.descriptions.keys(); for (const QString &lang : lstKeys) { out << dent << dent << "' << action.messages.value(lang) << "\n"; } const auto lstMessagesKeys = action.messages.keys(); for (const QString &lang : lstMessagesKeys) { out << dent << dent << "' << action.descriptions.value(lang) << "\n"; } QString policy = action.policy; if (!action.persistence.isEmpty()) { policy += "_keep_" + action.persistence; } out << QString(policy_tag).arg(policy); out << dent << "\n"; } out << "\n"; } diff --git a/src/backends/fakehelper/FakeHelperProxy.cpp b/src/backends/fakehelper/FakeHelperProxy.cpp index 69c039e..b3e0e62 100644 --- a/src/backends/fakehelper/FakeHelperProxy.cpp +++ b/src/backends/fakehelper/FakeHelperProxy.cpp @@ -1,84 +1,71 @@ /* -* Copyright (C) 2010 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2010 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include "FakeHelperProxy.h" namespace KAuth { FakeHelperProxy::FakeHelperProxy() : HelperProxy() { } FakeHelperProxy::~FakeHelperProxy() { } void FakeHelperProxy::sendProgressStep(const QVariantMap &step) { Q_UNUSED(step) } void FakeHelperProxy::sendProgressStep(int step) { Q_UNUSED(step) } void FakeHelperProxy::sendDebugMessage(int level, const char *msg) { Q_UNUSED(level) Q_UNUSED(msg) } bool FakeHelperProxy::hasToStopAction() { return false; } void FakeHelperProxy::setHelperResponder(QObject *o) { Q_UNUSED(o) } bool FakeHelperProxy::initHelper(const QString &name) { Q_UNUSED(name) return false; } void FakeHelperProxy::stopAction(const QString &action, const QString &helperID) { Q_UNUSED(action) Q_UNUSED(helperID) } void FakeHelperProxy::executeAction(const QString &action, const QString &helperID, const DetailsMap &details, const QVariantMap &arguments, int timeout) { Q_UNUSED(helperID) Q_UNUSED(details) Q_UNUSED(arguments) Q_UNUSED(timeout) emit actionPerformed(action, KAuth::ActionReply::NoSuchActionReply()); } } diff --git a/src/backends/fakehelper/FakeHelperProxy.h b/src/backends/fakehelper/FakeHelperProxy.h index 3003fb0..d397ad3 100644 --- a/src/backends/fakehelper/FakeHelperProxy.h +++ b/src/backends/fakehelper/FakeHelperProxy.h @@ -1,49 +1,36 @@ /* -* Copyright (C) 2010 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2010 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef FAKEHELPERPROXY_H #define FAKEHELPERPROXY_H #include "HelperProxy.h" namespace KAuth { class FakeHelperProxy : public HelperProxy { Q_OBJECT Q_INTERFACES(KAuth::HelperProxy) public: FakeHelperProxy(); virtual ~FakeHelperProxy(); void sendProgressStep(const QVariantMap &step) override; void sendProgressStep(int step) override; void sendDebugMessage(int level, const char *msg) override; bool hasToStopAction() override; void setHelperResponder(QObject *o) override; bool initHelper(const QString &name) override; void stopAction(const QString &action, const QString &helperID) override; void executeAction(const QString &action, const QString &helperID, const DetailsMap &details, const QVariantMap &arguments, int timeout = -1) override; }; } #endif // FAKEHELPERPROXY_H diff --git a/src/backends/mac/AuthServicesBackend.cpp b/src/backends/mac/AuthServicesBackend.cpp index 77b7c85..31488e9 100644 --- a/src/backends/mac/AuthServicesBackend.cpp +++ b/src/backends/mac/AuthServicesBackend.cpp @@ -1,199 +1,186 @@ /* -* Copyright (C) 2008 Nicola Gigante -* Copyright (C) 2014,2016 René Bertin -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + SPDX-FileCopyrightText: 2014, 2016 René Bertin + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include "AuthServicesBackend.h" #include #include #include Q_DECLARE_LOGGING_CATEGORY(KAUTH_OSX) // logging category for this backend, default: log stuff >= warning Q_LOGGING_CATEGORY(KAUTH_OSX, "kf5.kauth.apple", QtWarningMsg) namespace KAuth { static AuthorizationRef s_authRef = NULL; AuthorizationRef authRef() { if (!s_authRef) { AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &s_authRef); } return s_authRef; } // GetActionRights return codes: // errAuthorizationSuccess = 0, // errAuthorizationInvalidSet = -60001, /* The authorization rights are invalid. */ // errAuthorizationInvalidRef = -60002, /* The authorization reference is invalid. */ // errAuthorizationInvalidTag = -60003, /* The authorization tag is invalid. */ // errAuthorizationInvalidPointer = -60004, /* The returned authorization is invalid. */ // errAuthorizationDenied = -60005, /* The authorization was denied. */ // errAuthorizationCanceled = -60006, /* The authorization was cancelled by the user. */ // errAuthorizationInteractionNotAllowed = -60007, /* The authorization was denied since no user interaction was possible. */ // errAuthorizationInternal = -60008, /* Unable to obtain authorization for this operation. */ // errAuthorizationExternalizeNotAllowed = -60009, /* The authorization is not allowed to be converted to an external format. */ // errAuthorizationInternalizeNotAllowed = -60010, /* The authorization is not allowed to be created from an external format. */ // errAuthorizationInvalidFlags = -60011, /* The provided option flag(s) are invalid for this authorization operation. */ // errAuthorizationToolExecuteFailure = -60031, /* The specified program could not be executed. */ // errAuthorizationToolEnvironmentError = -60032, /* An invalid status was returned during execution of a privileged tool. */ // errAuthorizationBadAddress = -60033, /* The requested socket address is invalid (must be 0-1023 inclusive). */ static OSStatus GetActionRights(const QString &action, AuthorizationFlags flags, AuthorizationRef auth) { AuthorizationItem item; item.name = action.toUtf8().constData(); item.valueLength = 0; item.value = NULL; item.flags = 0; AuthorizationRights rights; rights.count = 1; rights.items = &item; OSStatus result = AuthorizationCopyRights(auth, &rights, kAuthorizationEmptyEnvironment, flags, NULL); return result; } // On OS X we avoid using a helper but grab privilege from here, the client. AuthServicesBackend::AuthServicesBackend() : AuthBackend() { setCapabilities(AuthorizeFromClientCapability | CheckActionExistenceCapability); } AuthServicesBackend::~AuthServicesBackend() { if (s_authRef) { OSStatus err = AuthorizationFree(s_authRef, kAuthorizationFlagDefaults); qCDebug(KAUTH_OSX) << "AuthorizationFree(" << s_authRef << ") returned" << err; s_authRef = NULL; } } void AuthServicesBackend::setupAction(const QString &) { // Nothing to do here... } Action::AuthStatus AuthServicesBackend::authorizeAction(const QString &action) { Action::AuthStatus retval; OSStatus result = GetActionRights(action, kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed, authRef()); qCDebug(KAUTH_OSX) << "AuthServicesBackend::authorizeAction(" << action << ") AuthorizationCopyRights returned" << result; switch (result) { case errAuthorizationSuccess: retval = Action::AuthorizedStatus; break; case errAuthorizationCanceled: retval = Action::UserCancelledStatus; break; case errAuthorizationInteractionNotAllowed: case errAuthorizationDenied: retval = Action::DeniedStatus; break; case errAuthorizationInternal: // does this make sense? retval = Action::AuthRequiredStatus; break; case errAuthorizationExternalizeNotAllowed: case errAuthorizationInternalizeNotAllowed: case errAuthorizationToolExecuteFailure: case errAuthorizationToolEnvironmentError: case errAuthorizationBadAddress: retval = Action::ErrorStatus; break; default: retval = Action::InvalidStatus; break; } return retval; } Action::AuthStatus AuthServicesBackend::actionStatus(const QString &action) { Action::AuthStatus retval; OSStatus result = GetActionRights(action, kAuthorizationFlagExtendRights | kAuthorizationFlagPreAuthorize, authRef()); qCDebug(KAUTH_OSX) << "AuthServicesBackend::actionStatus(" << action << ") AuthorizationCopyRights returned" << result; // this function has a simpler return code parser: switch (result) { case errAuthorizationSuccess: retval = Action::AuthorizedStatus; break; case errAuthorizationCanceled: retval = Action::UserCancelledStatus; break; case errAuthorizationInteractionNotAllowed: retval = Action::AuthRequiredStatus; break; default: retval = Action::DeniedStatus; break; } return retval; } QByteArray AuthServicesBackend::callerID() const { AuthorizationExternalForm ext; AuthorizationMakeExternalForm(authRef(), &ext); QByteArray id((const char *)&ext, sizeof(ext)); return id; } bool AuthServicesBackend::isCallerAuthorized(const QString &action, const QByteArray &callerID, const QVariantMap &details) { Q_UNUSED(details); AuthorizationExternalForm ext; memcpy(&ext, callerID.data(), sizeof(ext)); AuthorizationRef auth; if (AuthorizationCreateFromExternalForm(&ext, &auth) != noErr) { qCWarning(KAUTH_OSX()) << "AuthorizationCreateFromExternalForm(" << action << "," << callerID.constData() << ") failed"; return false; } OSStatus result = GetActionRights( action, kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed, auth); AuthorizationFree(auth, kAuthorizationFlagDefaults); qCDebug(KAUTH_OSX) << "AuthServicesBackend::isCallerAuthorized(" << action << "," << callerID.constData() << ") AuthorizationCopyRights returned" << result; return result == errAuthorizationSuccess; } // OS X doesn't distinguish between "action doesn't exist" and "action not allowed". So the // best thing we can do is return true and hope that the action will be created if it didn't exist... bool AuthServicesBackend::actionExists(const QString &) { return true; } }; // namespace KAuth diff --git a/src/backends/mac/AuthServicesBackend.h b/src/backends/mac/AuthServicesBackend.h index 3ddf971..5a51082 100644 --- a/src/backends/mac/AuthServicesBackend.h +++ b/src/backends/mac/AuthServicesBackend.h @@ -1,50 +1,37 @@ /* -* Copyright (C) 2008 Nicola Gigante -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + + SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef AUTHSERVICES_BACKEND_H #define AUTHSERVICES_BACKEND_H #include "AuthBackend.h" #include namespace KAuth { class AuthServicesBackend : public AuthBackend { Q_OBJECT Q_PLUGIN_METADATA(IID "org.kde.AuthServicesBackend") Q_INTERFACES(KAuth::AuthBackend) public: AuthServicesBackend(); virtual ~AuthServicesBackend(); virtual void setupAction(const QString &); virtual Action::AuthStatus authorizeAction(const QString &); virtual Action::AuthStatus actionStatus(const QString &); virtual QByteArray callerID() const; virtual bool isCallerAuthorized(const QString &action, const QByteArray &callerID, const QVariantMap &details); virtual bool actionExists(const QString &action); }; } // namespace KAuth #endif diff --git a/src/backends/mac/kauth-policy-gen-mac.cpp b/src/backends/mac/kauth-policy-gen-mac.cpp index 213d96b..e160459 100644 --- a/src/backends/mac/kauth-policy-gen-mac.cpp +++ b/src/backends/mac/kauth-policy-gen-mac.cpp @@ -1,66 +1,53 @@ /* -* Copyright (C) 2008 Nicola Gigante -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include "../../policy-gen/policy-gen.h" #include #include #include using namespace std; void output(const QList &actions, const QMap &domain) { AuthorizationRef auth; AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &auth); OSStatus err; for (const Action &action : qAsConst(actions)) { err = AuthorizationRightGet(action.name.toLatin1().constData(), NULL); if (err != errAuthorizationSuccess) { QString rule; if (action.policy == QLatin1String("yes")) { rule = QString::fromLatin1(kAuthorizationRuleClassAllow); } else if (action.policy == QLatin1String("no")) { rule = QString::fromLatin1(kAuthorizationRuleClassDeny); } else if (action.policy == QLatin1String("auth_self")) { rule = QString::fromLatin1(kAuthorizationRuleAuthenticateAsSessionUser); } else if (action.policy == QLatin1String("auth_admin")) { rule = QString::fromLatin1(kAuthorizationRuleAuthenticateAsAdmin); } CFStringRef cfRule = CFStringCreateWithCString(NULL, rule.toLatin1().constData(), kCFStringEncodingASCII); CFStringRef cfPrompt = CFStringCreateWithCString(NULL, action.descriptions.value(QLatin1String("en")).toLatin1().constData(), kCFStringEncodingASCII); err = AuthorizationRightSet(auth, action.name.toLatin1().constData(), cfRule, cfPrompt, NULL, NULL); if (err != noErr) { cerr << "You don't have the right to edit the security database (try to run cmake with sudo): " << err << endl; exit(1); } else { qInfo() << "Created or updated rule" << rule << "for right entry" << action.name << "policy" << action.policy << "; domain=" << domain; } } } } diff --git a/src/backends/polkit-1/Polkit1Backend.cpp b/src/backends/polkit-1/Polkit1Backend.cpp index 2c2c34a..0cce557 100644 --- a/src/backends/polkit-1/Polkit1Backend.cpp +++ b/src/backends/polkit-1/Polkit1Backend.cpp @@ -1,229 +1,216 @@ /* -* Copyright (C) 2008 Nicola Gigante -* Copyright (C) 2009 Radek Novacek -* Copyright (C) 2009-2010 Dario Freddi -* Copyright (C) 2020 David Edmundson -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + SPDX-FileCopyrightText: 2009 Radek Novacek + SPDX-FileCopyrightText: 2009-2010 Dario Freddi + SPDX-FileCopyrightText: 2020 David Edmundson + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include "Polkit1Backend.h" #include #include #include #include #include #include #include #include #include #include #include "kauthdebug.h" namespace KAuth { PolkitResultEventLoop::PolkitResultEventLoop(QObject *parent) : QEventLoop(parent) { } PolkitResultEventLoop::~PolkitResultEventLoop() { } void PolkitResultEventLoop::requestQuit(const PolkitQt1::Authority::Result &result) { m_result = result; quit(); } PolkitQt1::Authority::Result PolkitResultEventLoop::result() const { return m_result; } Polkit1Backend::Polkit1Backend() : AuthBackend() { setCapabilities(AuthorizeFromHelperCapability | CheckActionExistenceCapability | PreAuthActionCapability); // Setup useful signals connect(PolkitQt1::Authority::instance(), SIGNAL(configChanged()), this, SLOT(checkForResultChanged())); connect(PolkitQt1::Authority::instance(), SIGNAL(consoleKitDBChanged()), this, SLOT(checkForResultChanged())); } Polkit1Backend::~Polkit1Backend() { } void Polkit1Backend::preAuthAction(const QString &action, QWidget *parent) { // If a parent was not specified, skip this if (!parent) { qCDebug(KAUTH) << "Parent widget does not exist, skipping"; return; } // Are we running our KDE auth agent? if (QDBusConnection::sessionBus().interface()->isServiceRegistered(QLatin1String("org.kde.polkit-kde-authentication-agent-1"))) { // Check if we actually are entitled to use GUI capabilities if (qApp == nullptr || !qobject_cast(qApp)) { qCDebug(KAUTH) << "Not streaming parent as we are on a TTY application"; } // Retrieve the dialog root window Id qulonglong wId = parent->effectiveWinId(); // Send it over the bus to our agent QDBusMessage methodCall = QDBusMessage::createMethodCall(QLatin1String("org.kde.polkit-kde-authentication-agent-1"), QLatin1String("/org/kde/Polkit1AuthAgent"), QLatin1String("org.kde.Polkit1AuthAgent"), QLatin1String("setWIdForAction")); methodCall << action; methodCall << wId; QDBusPendingCall call = QDBusConnection::sessionBus().asyncCall(methodCall); call.waitForFinished(); if (call.isError()) { qCWarning(KAUTH) << "ERROR while streaming the parent!!" << call.error(); } } else { qCDebug(KAUTH) << "KDE polkit agent appears too old or not registered on the bus"; } } Action::AuthStatus Polkit1Backend::authorizeAction(const QString &action) { Q_UNUSED(action) // Always return Yes here, we'll authorize inside isCallerAuthorized return Action::AuthorizedStatus; } void Polkit1Backend::setupAction(const QString &action) { m_cachedResults[action] = actionStatus(action); } Action::AuthStatus Polkit1Backend::actionStatus(const QString &action) { PolkitQt1::SystemBusNameSubject subject(QString::fromUtf8(callerID())); auto authority = PolkitQt1::Authority::instance(); PolkitQt1::Authority::Result r = authority->checkAuthorizationSync(action, subject, PolkitQt1::Authority::None); if (authority->hasError()) { qCDebug(KAUTH) << "Encountered error while checking action status, error code:" << authority->lastError() << authority->errorDetails(); authority->clearError(); return Action::InvalidStatus; } switch (r) { case PolkitQt1::Authority::Yes: return Action::AuthorizedStatus; case PolkitQt1::Authority::No: case PolkitQt1::Authority::Unknown: return Action::DeniedStatus; default: return Action::AuthRequiredStatus; } } QByteArray Polkit1Backend::callerID() const { return QDBusConnection::systemBus().baseService().toUtf8(); } AuthBackend::ExtraCallerIDVerificationMethod Polkit1Backend::extraCallerIDVerificationMethod() const { return VerifyAgainstDBusServiceName; } bool Polkit1Backend::isCallerAuthorized(const QString &action, const QByteArray &callerID, const QVariantMap &details) { PolkitQt1::SystemBusNameSubject subject(QString::fromUtf8(callerID)); PolkitQt1::Authority *authority = PolkitQt1::Authority::instance(); QMap polkit1Details; for (auto it = details.cbegin(); it != details.cend(); ++it) { polkit1Details.insert(it.key(), it.value().toString()); } PolkitResultEventLoop e; connect(authority, SIGNAL(checkAuthorizationFinished(PolkitQt1::Authority::Result)), &e, SLOT(requestQuit(PolkitQt1::Authority::Result))); #if POLKITQT1_IS_VERSION(0, 113, 0) authority->checkAuthorizationWithDetails(action, subject, PolkitQt1::Authority::AllowUserInteraction, polkit1Details); #else authority->checkAuthorization(action, subject, PolkitQt1::Authority::AllowUserInteraction); #endif e.exec(); if (authority->hasError()) { qCDebug(KAUTH) << "Encountered error while checking authorization, error code:" << authority->lastError() << authority->errorDetails(); authority->clearError(); } switch (e.result()) { case PolkitQt1::Authority::Yes: return true; default: return false; } } void Polkit1Backend::checkForResultChanged() { for (auto it = m_cachedResults.begin(); it != m_cachedResults.end(); ++it) { const QString action = it.key(); if (it.value() != actionStatus(action)) { *it = actionStatus(action); emit actionStatusChanged(action, *it); } } } bool Polkit1Backend::actionExists(const QString &action) { return m_cachedResults.value(action) != Action::InvalidStatus; } QVariantMap Polkit1Backend::backendDetails(const DetailsMap &details) { QVariantMap backendDetails; for (auto it = details.cbegin(); it != details.cend(); ++it) { switch (it.key()) { case Action::AuthDetail::DetailMessage: backendDetails.insert(QStringLiteral("polkit.message"), it.value()); break; case Action::AuthDetail::DetailOther: default: backendDetails.insert(QStringLiteral("other_details"), it.value()); break; } } return backendDetails; } } // namespace Auth diff --git a/src/backends/polkit-1/Polkit1Backend.h b/src/backends/polkit-1/Polkit1Backend.h index 0d51e9e..d261a97 100644 --- a/src/backends/polkit-1/Polkit1Backend.h +++ b/src/backends/polkit-1/Polkit1Backend.h @@ -1,82 +1,69 @@ /* -* Copyright (C) 2008 Nicola Gigante -* Copyright (C) 2009 Radek Novacek -* Copyright (C) 2009-2010 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + SPDX-FileCopyrightText: 2009 Radek Novacek + SPDX-FileCopyrightText: 2009-2010 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef POLKIT1BACKEND_H #define POLKIT1BACKEND_H #include "AuthBackend.h" #include #include #include #include class QByteArray; namespace KAuth { class Polkit1Backend : public AuthBackend { Q_OBJECT Q_PLUGIN_METADATA(IID "org.kde.Polkit1Backend") Q_INTERFACES(KAuth::AuthBackend) public: Polkit1Backend(); virtual ~Polkit1Backend(); void setupAction(const QString &) override; void preAuthAction(const QString &action, QWidget *parent) override; Action::AuthStatus authorizeAction(const QString &) override; Action::AuthStatus actionStatus(const QString &) override; QByteArray callerID() const override; ExtraCallerIDVerificationMethod extraCallerIDVerificationMethod() const override; virtual bool isCallerAuthorized(const QString &action, const QByteArray &callerID, const QVariantMap &details) override; bool actionExists(const QString &action) override; QVariantMap backendDetails(const DetailsMap &details) override; private Q_SLOTS: void checkForResultChanged(); private: QHash m_cachedResults; }; class PolkitResultEventLoop : public QEventLoop { Q_OBJECT public: PolkitResultEventLoop(QObject *parent = nullptr); virtual ~PolkitResultEventLoop(); PolkitQt1::Authority::Result result() const; public Q_SLOTS: void requestQuit(const PolkitQt1::Authority::Result &result); private: PolkitQt1::Authority::Result m_result; }; } // namespace Auth #endif diff --git a/src/backends/polkit-1/kauth-policy-gen-polkit1.cpp b/src/backends/polkit-1/kauth-policy-gen-polkit1.cpp index 39711e5..c0c499b 100644 --- a/src/backends/polkit-1/kauth-policy-gen-polkit1.cpp +++ b/src/backends/polkit-1/kauth-policy-gen-polkit1.cpp @@ -1,120 +1,107 @@ /* -* Copyright (C) 2008 Nicola Gigante -* Copyright (C) 2009-2010 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + SPDX-FileCopyrightText: 2009-2010 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include #include #include #include const char header[] = "" "\n" "\n" "\n"; const char policy_tag[] = "" " \n" " %1\n" " %2\n" " \n"; const char dent[] = " "; void output(const QList &actions, const QMap &domain) { QTextStream out(stdout); out.setCodec("UTF-8"); out << header; // Blacklisted characters + replacements QMap< QChar, QString > blacklist; blacklist.insert(QLatin1Char('&'), QLatin1String("&")); if (domain.contains(QLatin1String("vendor"))) { QString vendor = domain[QLatin1String("vendor")]; for (QMap< QChar, QString >::const_iterator blI = blacklist.constBegin(), total = blacklist.constEnd(); blI != total; ++blI) { vendor.replace(blI.key(), blI.value()); } out << "" << vendor << "\n"; } if (domain.contains(QLatin1String("vendorurl"))) { out << "" << domain[QLatin1String("vendorurl")] << "\n"; } if (domain.contains(QLatin1String("icon"))) { out << "" << domain[QLatin1String("icon")] << "\n"; } for (const Action &action : actions) { out << dent << "\n"; // Not a typo, messages and descriptions are actually inverted for (QMap< QString, QString >::const_iterator i = action.messages.constBegin(); i != action.messages.constEnd(); ++i) { out << dent << dent << "::const_iterator blI; QString description = i.value(); for (blI = blacklist.constBegin(); blI != blacklist.constEnd(); ++blI) { description.replace(blI.key(), blI.value()); } out << '>' << description << "\n"; } for (QMap< QString, QString >::const_iterator i = action.descriptions.constBegin(); i != action.descriptions.constEnd(); ++i) { out << dent << dent << "::const_iterator blI; QString message = i.value(); for (blI = blacklist.constBegin(); blI != blacklist.constEnd(); ++blI) { message.replace(blI.key(), blI.value()); } out << '>' << message << "\n"; } QString policy = action.policy; QString policyInactive = action.policyInactive.isEmpty() ? QLatin1String("no") : action.policyInactive; if (!action.persistence.isEmpty() && policy != QLatin1String("yes") && policy != QLatin1String("no")) { policy += QLatin1String("_keep"); } if (!action.persistence.isEmpty() && policyInactive != QLatin1String("yes") && policyInactive != QLatin1String("no")) { policyInactive += QLatin1String("_keep"); } out << QString(QLatin1String(policy_tag)).arg(policyInactive, policy); out << dent << "\n"; } out << "\n"; } diff --git a/src/kauth.h b/src/kauth.h index 6be5c7c..1e9aa64 100644 --- a/src/kauth.h +++ b/src/kauth.h @@ -1,29 +1,16 @@ /* -* Copyright (C) 2008 Nicola Gigante -* Copyright (C) 2009-2012 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + SPDX-FileCopyrightText: 2009-2012 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef KAUTH_H #define KAUTH_H #include "kauthaction.h" #include "kauthactionreply.h" #include "kauthexecutejob.h" #include "kauthhelpersupport.h" #endif diff --git a/src/kauthaction.cpp b/src/kauthaction.cpp index ea65f84..8f34edf 100644 --- a/src/kauthaction.cpp +++ b/src/kauthaction.cpp @@ -1,234 +1,221 @@ /* -* Copyright (C) 2009-2012 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2009-2012 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include "kauthaction.h" #include #include class QWidget; #include "kauthexecutejob.h" #include "BackendsManager.h" namespace KAuth { class ActionData : public QSharedData { public: ActionData() : parent(nullptr), timeout(-1) {} ActionData(const ActionData &other) : QSharedData(other) , name(other.name) , helperId(other.helperId) , details(other.details) , args(other.args) , parent(other.parent) , timeout(other.timeout) {} ~ActionData() {} QString name; QString helperId; Action::DetailsMap details; QVariantMap args; QWidget *parent = nullptr; int timeout; }; // Constructors Action::Action() : d(new ActionData()) { } Action::Action(const Action &action) : d(action.d) { } Action::Action(const QString &name) : d(new ActionData()) { setName(name); BackendsManager::authBackend()->setupAction(d->name); } #if KAUTHCORE_BUILD_DEPRECATED_SINCE(5, 71) Action::Action(const QString &name, const QString &details) : Action(name, DetailsMap{{AuthDetail::DetailOther, details}}) { } #endif Action::Action(const QString &name, const DetailsMap &details) : d(new ActionData()) { setName(name); setDetailsV2(details); BackendsManager::authBackend()->setupAction(d->name); } Action::~Action() { } // Operators Action &Action::operator=(const Action &action) { if (this == &action) { // Protect against self-assignment return *this; } d = action.d; return *this; } bool Action::operator==(const Action &action) const { return d->name == action.d->name; } bool Action::operator!=(const Action &action) const { return d->name != action.d->name; } // Accessors QString Action::name() const { return d->name; } void Action::setName(const QString &name) { d->name = name; } // Accessors int Action::timeout() const { return d->timeout; } void Action::setTimeout(int timeout) { d->timeout = timeout; } #if KAUTHCORE_BUILD_DEPRECATED_SINCE(5, 71) QString Action::details() const { return d->details.value(AuthDetail::DetailOther).toString(); } #endif #if KAUTHCORE_BUILD_DEPRECATED_SINCE(5, 71) void Action::setDetails(const QString &details) { d->details.clear(); d->details.insert(AuthDetail::DetailOther, details); } #endif Action::DetailsMap Action::detailsV2() const { return d->details; } void Action::setDetailsV2(const DetailsMap &details) { d->details = details; } bool Action::isValid() const { if (d->name.isEmpty()) { return false; } // Does the backend support checking for known actions? if (BackendsManager::authBackend()->capabilities() & KAuth::AuthBackend::CheckActionExistenceCapability) { // In this case, just ask the backend return BackendsManager::authBackend()->actionExists(name()); } else { // Otherwise, check through a regexp const QRegularExpression re(QRegularExpression::anchoredPattern(QStringLiteral("[0-z]+(\\.[0-z]+)*"))); return re.match(name()).hasMatch(); } } void Action::setArguments(const QVariantMap &arguments) { d->args = arguments; } void Action::addArgument(const QString &key, const QVariant &value) { d->args.insert(key, value); } QVariantMap Action::arguments() const { return d->args; } QString Action::helperId() const { return d->helperId; } // TODO: Check for helper id's syntax void Action::setHelperId(const QString &id) { d->helperId = id; } void Action::setParentWidget(QWidget *parent) { d->parent = parent; } QWidget *Action::parentWidget() const { return d->parent; } Action::AuthStatus Action::status() const { if (!isValid()) { return Action::InvalidStatus; } return BackendsManager::authBackend()->actionStatus(d->name); } ExecuteJob *Action::execute(ExecutionMode mode) { return new ExecuteJob(*this, mode, nullptr); } bool Action::hasHelper() const { return !d->helperId.isEmpty(); } } // namespace Auth diff --git a/src/kauthaction.h b/src/kauthaction.h index cad18a8..018f1d3 100644 --- a/src/kauthaction.h +++ b/src/kauthaction.h @@ -1,451 +1,438 @@ /* -* Copyright (C) 2009-2012 Dario Freddi -* Copyright (C) 2008 Nicola Gigante -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2009-2012 Dario Freddi + SPDX-FileCopyrightText: 2008 Nicola Gigante + + SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef ACTION_H #define ACTION_H #include #include #include #include #include namespace KAuth { class ExecuteJob; class ActionData; /** * @class Action kauthaction.h * * @brief Class to access, authorize and execute actions. * * This is the main class of the kauth API. It provides the interface to * manipulate actions. Every action is identified by its name. Every instance * of the Action class with the same name refers to the same action. * * Once you have an action object you can tell the helper to execute it * (asking the user to authenticate if needed) with the execute() method. * The simplest thing to do is to execute a single action synchronously * blocking for the reply by callin exec() on the job object returned by * execute(). * * For asynchronous calls, use KAuth::ExecuteJob::start() instead. * It sends the request * to the helper and returns immediately. Before doing so you should however * connect to at least the KJob::result(KJob *) signal to receive a slot call * once the action is done executing. * * To use the execute() method you have to set the default helper's ID using * the setHelperID() static method. Alternatively, you can specify the helperID using * the overloaded version of the methods that takes it as a parameter. * * Each action object contains a QVariantMap object that is passed directly to the * helper when the action is executed. You can access this map using the arguments() * method. You can insert into it any kind of custom data you need to pass to the helper. * * @code * void MyApp::runAction() * { * action = KAuth::Action("org.kde.myapp.action"); * KAuth::ExecuteJob *job = action.execute(); * connect(job, &KAuth::ExecuteJob::result, this, &MyApp::actionResult); * job->start(); * } * * void MyApp::actionResult(KJob *kjob) * { * auto job = qobject_cast(kjob); * qDebug() << job.error() << job.data(); * } * @endcode * * @since 4.4 */ class KAUTHCORE_EXPORT Action { Q_GADGET public: /** * The three values set by authorization methods */ enum AuthStatus { DeniedStatus, ///< The authorization has been denied by the authorization backend ErrorStatus, ///< An error occurred InvalidStatus, ///< An invalid action cannot be authorized AuthorizedStatus, ///< The authorization has been granted by the authorization backend AuthRequiredStatus, ///< The user could obtain the authorization after authentication UserCancelledStatus ///< The user pressed Cancel the authentication dialog. Currently used only on the mac }; Q_ENUM(AuthStatus) enum ExecutionMode { ExecuteMode, AuthorizeOnlyMode }; Q_ENUM(ExecutionMode) /** * The backend specific details. */ enum class AuthDetail { DetailOther = 0, DetailMessage, ///< The message to show in authentication dialog. }; Q_ENUM(AuthDetail) /** * Map of details. */ typedef QMap DetailsMap; /** * @brief Default constructor * * This constructor sets the name to the empty string. * Such an action is invalid and cannot be authorized nor executed, so * you need to call setName() before you can use the object. */ Action(); /** Copy constructor */ Action(const Action &action); /** * This creates a new action object with this name * @param name The name of the new action */ Action(const QString &name); #if KAUTHCORE_ENABLE_DEPRECATED_SINCE(5, 71) /** * This creates a new action object with this name and details * @param name The name of the new action * @param details The details of the action * * @see setDetails * @deprecated since 5.68, use constructor with DetailsMap */ KAUTHCORE_DEPRECATED_VERSION_BELATED(5, 71, 5, 68, "Use constructor with DetailsMap") Action(const QString &name, const QString &details); #endif /** * This creates a new action object with this name and details * @param name The name of the new action * @param details The details of the action * * @see setDetails * @since 5.68 */ Action(const QString &name, const DetailsMap &details); /// Virtual destructor ~Action(); /// Assignment operator Action &operator=(const Action &action); /** * @brief Comparison operator * * This comparison operator compares the names of two * actions and returns whether they are the same. It does not * care about the arguments stored in the actions. However, * if two actions are invalid they'll match as equal, even * if the invalid names are different. * * @returns true if the two actions are the same or both invalid */ bool operator==(const Action &action) const; /** * @brief Negated comparison operator * * Returns the negation of operator== * * @returns true if the two actions are different and not both invalid */ bool operator!=(const Action &action) const; /** * @brief Gets the action's name. * * This is the unique attribute that identifies * an action object. Two action objects with the same * name always refer to the same action. * * @return The action name */ QString name() const; /** * @brief Sets the action's name. * * It's not common to change the action name * after its creation. Usually you set the name * with the constructor (and you have to, because * there's no default constructor) */ void setName(const QString &name); /** * @brief Gets the action's timeout. * * The timeout of the action in milliseconds * -1 means the default D-Bus timeout (usually 25 seconds) * * @since 5.29 * * @return The action timeouts */ int timeout() const; /** * @brief Sets the action's timeout. * * The timeout of the action in milliseconds * -1 means the default D-Bus timeout (usually 25 seconds) * * @since 5.29 * */ void setTimeout(int timeout); #if KAUTHCORE_ENABLE_DEPRECATED_SINCE(5, 71) /** * @brief Sets the action's details * * You can use this function to provide the user more details * (if the backend supports it) on the action being authorized in * the authorization dialog * * @deprecated since 5.68, use setDetailsV2() with DetailsMap. */ KAUTHCORE_DEPRECATED_VERSION_BELATED(5, 71, 5, 68, "Use setDetailsV2() with DetailsMap") void setDetails(const QString &details); #endif /** * @brief Sets the action's details * * You can use this function to provide the user more details * (if the backend supports it) on the action being authorized in * the authorization dialog * * @param details the details describing the action. For e.g, "DetailMessage" key can * be used to give a customized authentication message. * * @since 5.68 */ void setDetailsV2(const DetailsMap &details); #if KAUTHCORE_ENABLE_DEPRECATED_SINCE(5, 71) /** * @brief Gets the action's details * * The details that will be shown in the authorization dialog, if the * backend supports it. * * @return The action's details * @deprecated since 5.68, use detailsV2() with DetailsMap. */ KAUTHCORE_DEPRECATED_VERSION_BELATED(5, 71, 5, 68, "Use detailsV2() with DetailsMap") QString details() const; #endif /** * @brief Gets the action's details * * The details that will be shown in the authorization dialog, if the * backend supports it. * * @return The action's details * @since 5.68 */ DetailsMap detailsV2() const; /** * @brief Returns if the object represents a valid action * * Action names have to respect a simple syntax. * They have to be all in lowercase characters, separated * by dots. Dots can't appear at the beginning and at the end of * the name. * * In other words, the action name has to match this perl-like * regular expression: * @verbatim * /^[a-z]+(\.[a-z]+)*$/ * @endverbatim * * This method returns false if the action name doesn't match the * valid syntax. * * If the backend supports it, this method also checks if the action is * valid and recognized by the backend itself. * @note This may spawn a nested event loop. * * Invalid actions cannot be authorized nor executed. * The empty string is not a valid action name, so the default * constructor returns an invalid action. */ bool isValid() const; /** * @brief Gets the default helper ID used for actions execution * * The helper ID is the string that uniquely identifies the helper in * the system. It is the string passed to the KAUTH_HELPER() macro * in the helper source. Because one could have different helpers, * you need to specify an helper ID for each execution, or set a default * ID by calling setHelperID(). This method returns the current default * value. * * @return The default helper ID. */ QString helperId() const; /** * @brief Sets the default helper ID used for actions execution * * This method sets the helper ID which contains the body of this action. * If the string is non-empty, the corresponding helper will be fired and * the action executed inside the helper. Otherwise, the action will be just * authorized. * * @note To unset a previously set helper, just pass an empty string * * @param id The default helper ID. * * @see hasHelper * @see helperId */ void setHelperId(const QString &id); /** * @brief Checks if the action has an helper * * This function can be used to check if an helper will be called upon the * execution of an action. Such an helper can be set through setHelperID. If * this function returns false, upon execution the action will be just authorized. * * @since 4.5 * * @return Whether the action has an helper or not * * @see setHelperID */ bool hasHelper() const; /** * @brief Sets the map object used to pass arguments to the helper. * * This method sets the variant map that the application * can use to pass arbitrary data to the helper when executing the action. * * Only non-gui variants are supported. * * @param arguments The new arguments map */ void setArguments(const QVariantMap &arguments); /** * @brief Returns map object used to pass arguments to the helper. * * This method returns the variant map that the application * can use to pass arbitrary data to the helper when executing the action. * * @return The arguments map that will be passed to the helper. */ QVariantMap arguments() const; /** * @brief Convenience method to add an argument. * * This method adds the pair @c key/value to the QVariantMap used to * send custom data to the helper. * * Use this method if you don't want to create a new QVariantMap only to * add a new entry. * * @param key The new entry's key * @param value The value of the new entry */ void addArgument(const QString &key, const QVariant &value); /** * @brief Gets information about the authorization status of an action * * This methods query the authorization backend to know if the user can try * to acquire the authorization for this action. If the result is Action::AuthRequired, * the user can try to acquire the authorization by authenticating. * * It should not be needed to call this method directly, because the execution methods * already take care of all the authorization stuff. * * @return @c Action::Denied if the user doesn't have the authorization to execute the action, * @c Action::Authorized if the action can be executed, * @c Action::AuthRequired if the user could acquire the authorization after authentication, * @c Action::UserCancelled if the user cancels the authentication dialog. Not currently supported by the Polkit backend */ AuthStatus status() const; /** * @brief Get the job object used to execute the action * * @return The KJob::ExecuteJob object to be used to run the action. */ ExecuteJob *execute(ExecutionMode mode = ExecuteMode); /** * @brief Sets a parent widget for the authentication dialog * * This function is used for explicitly setting a parent window for an eventual authentication dialog required when * authorization is triggered. Some backends, in fact, (like polkit-1) need to have a parent explicitly set for displaying * the dialog correctly. * * @note If you are using KAuth through one of KDE's GUI components (KPushButton, KCModule...) you do not need and should not * call this function, as it is already done by the component itself. * * @since 4.6 * * @param parent A QWidget which will be used as the dialog's parent */ void setParentWidget(QWidget *parent); /** * @brief Returns the parent widget for the authentication dialog for this action * * @since 4.6 * * @returns A QWidget which will is being used as the dialog's parent */ QWidget *parentWidget() const; private: QSharedDataPointer d; }; } // namespace Auth #endif diff --git a/src/kauthactionreply.cpp b/src/kauthactionreply.cpp index be043e7..a3be3fa 100644 --- a/src/kauthactionreply.cpp +++ b/src/kauthactionreply.cpp @@ -1,252 +1,239 @@ /* -* Copyright (C) 2009-2012 Dario Freddi -* Copyright (C) 2008 Nicola Gigante -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2009-2012 Dario Freddi + SPDX-FileCopyrightText: 2008 Nicola Gigante + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include "kauthactionreply.h" #include namespace KAuth { class ActionReplyData : public QSharedData { public: ActionReplyData() {} ActionReplyData(const ActionReplyData &other) : QSharedData(other) , data(other.data) , errorCode(other.errorCode) , errorDescription(other.errorDescription) , type(other.type) {} ~ActionReplyData() {} QVariantMap data; // User-defined data for success and helper error replies, empty for kauth errors uint errorCode; QString errorDescription; ActionReply::Type type; }; // Predefined replies const ActionReply ActionReply::SuccessReply() { return ActionReply(); } const ActionReply ActionReply::HelperErrorReply() { ActionReply reply(ActionReply::HelperErrorType); reply.setError(-1); return reply; } const ActionReply ActionReply::HelperErrorReply(int error) { ActionReply reply(ActionReply::HelperErrorType); reply.setError(error); return reply; } const ActionReply ActionReply::NoResponderReply() { return ActionReply(ActionReply::NoResponderError); } const ActionReply ActionReply::NoSuchActionReply() { return ActionReply(ActionReply::NoSuchActionError); } const ActionReply ActionReply::InvalidActionReply() { return ActionReply(ActionReply::InvalidActionError); } const ActionReply ActionReply::AuthorizationDeniedReply() { return ActionReply(ActionReply::AuthorizationDeniedError); } const ActionReply ActionReply::UserCancelledReply() { return ActionReply(ActionReply::UserCancelledError); } const ActionReply ActionReply::HelperBusyReply() { return ActionReply(ActionReply::HelperBusyError); } const ActionReply ActionReply::AlreadyStartedReply() { return ActionReply(ActionReply::AlreadyStartedError); } const ActionReply ActionReply::DBusErrorReply() { return ActionReply(ActionReply::DBusError); } // Constructors ActionReply::ActionReply(const ActionReply &reply) : d(reply.d) { } ActionReply::ActionReply() : d(new ActionReplyData()) { d->errorCode = 0; d->type = SuccessType; } ActionReply::ActionReply(ActionReply::Type type) : d(new ActionReplyData()) { d->errorCode = 0; d->type = type; } ActionReply::ActionReply(int error) : d(new ActionReplyData()) { d->errorCode = error; d->type = KAuthErrorType; } ActionReply::~ActionReply() { } void ActionReply::setData(const QVariantMap &data) { d->data = data; } void ActionReply::addData(const QString &key, const QVariant &value) { d->data.insert(key, value); } QVariantMap ActionReply::data() const { return d->data; } ActionReply::Type ActionReply::type() const { return d->type; } void ActionReply::setType(ActionReply::Type type) { d->type = type; } bool ActionReply::succeeded() const { return d->type == SuccessType; } bool ActionReply::failed() const { return !succeeded(); } ActionReply::Error ActionReply::errorCode() const { return (ActionReply::Error)d->errorCode; } void ActionReply::setErrorCode(Error errorCode) { d->errorCode = errorCode; if (d->type != HelperErrorType) { d->type = KAuthErrorType; } } int ActionReply::error() const { return d->errorCode; } void ActionReply::setError(int error) { d->errorCode = error; } QString ActionReply::errorDescription() const { return d->errorDescription; } void ActionReply::setErrorDescription(const QString &error) { d->errorDescription = error; } QByteArray ActionReply::serialized() const { QByteArray data; QDataStream s(&data, QIODevice::WriteOnly); s << *this; return data; } ActionReply ActionReply::deserialize(const QByteArray &data) { ActionReply reply; QByteArray a(data); QDataStream s(&a, QIODevice::ReadOnly); s >> reply; return reply; } // Operators ActionReply &ActionReply::operator=(const ActionReply &reply) { if (this == &reply) { // Protect against self-assignment return *this; } d = reply.d; return *this; } bool ActionReply::operator==(const ActionReply &reply) const { return (d->type == reply.d->type && d->errorCode == reply.d->errorCode); } bool ActionReply::operator!=(const ActionReply &reply) const { return (d->type != reply.d->type || d->errorCode != reply.d->errorCode); } QDataStream &operator<<(QDataStream &d, const ActionReply &reply) { return d << reply.d->data << reply.d->errorCode << static_cast(reply.d->type) << reply.d->errorDescription; } QDataStream &operator>>(QDataStream &stream, ActionReply &reply) { quint32 i; stream >> reply.d->data >> reply.d->errorCode >> i >> reply.d->errorDescription; reply.d->type = static_cast(i); return stream; } } // namespace Auth diff --git a/src/kauthactionreply.h b/src/kauthactionreply.h index 53ecf77..e634ffc 100644 --- a/src/kauthactionreply.h +++ b/src/kauthactionreply.h @@ -1,611 +1,598 @@ /* -* Copyright (C) 2008 Nicola Gigante -* Copyright (C) 2009-2012 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + SPDX-FileCopyrightText: 2009-2012 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef ACTION_REPLY_H #define ACTION_REPLY_H #include #include #include #include #include #include /** @namespace KAuth @section kauth_intro Introduction The KDE Authorization API allows developers to write desktop applications that run high-privileged tasks in an easy, secure and cross-platform way. Previously, if an application had to do administrative tasks, it had to be run as root, using mechanisms such as sudo or graphical equivalents, or by setting the executable's setuid bit. This approach has some drawbacks. For example, the whole application code, including GUI handling and network communication, had to be done as root. More code that runs as root means more possible security holes. The solution is the caller/helper pattern. With this pattern, the privileged code is isolated in a small helper tool that runs as root. This tool includes only the few lines of code that actually need to be run with privileges, not the whole application logic. All the other parts of the application are run as a normal user, and the helper tool is called when needed, using a secure mechanism that ensures that the user is authorized to do so. This pattern is not very easy to implement, because the developer has to deal with a lot of details about how to authorize the user, how to call the helper with the right privileges, how to exchange data with the helper, etc.. This is where the new KDE Authorization API becomes useful. Thanks to this new library, every developer can implement the caller/helper pattern to write application that require high privileges, with a few lines of code in an easy, secure and cross-platform way. Not only: the library can also be used to lock down some actions in your application without using a helper but just checking for authorization and verifying if the user is allowed to perform it. The KDE Authorization library uses different backends depending on the system where it's built. As far as the user authorization is concerned, it currently uses polkit-1 on linux and Authorization Services on Mac OSX, and a Windows backend will eventually be written, too. At the communication layer, the library uses D-Bus on every supported platform. @section kauth_concepts Concepts There are a few concepts to understand when using the library. Much of those are carried from underlying APIs such as polkit-1, so if you know something about them there shouldn't be problems. An action is a single task that needs to be done by the application. You refer to an action using an action identifier, which is a string in reverse domain name syntax (to avoid duplicates). For example, if the date/time control center module needs to change the date, it would need an action like "org.kde.datatime.change". If your application has to perform more than one privileged task, you should configure more than one action. This allows system administrators to fine tune the policies that allow users to perform your actions. The authorization is the process that is executed to decide if a user can perform an action or not. In order to execute the helper as root, the user has to be authorized. For example, on linux, che policykit backend will look at the policykit policy database to see what requirements the user has to meet in order to execute the action you requested. The policy set for that action could allow or deny that user, or could say the user has to authenticate in order to gain the authorization. The authentication is the process that allows the system to know that the person is in front of the console is who he says to be. If an action can be allowed or not depending on the user's identity, it has to be proved by entering a password or any other identification data the system requires. A typical session with the authorization API is like this: - The user want to perform some privileged task - The application asks the system if the user is authorized. - The system asks the user to authenticate, if needed, and reply the application. - The application uses some system-provided mechanism to execute the helper's code as the root user. Previously, you had to set the setuid bit to do this, but we have something cool called "D-Bus activation" that doesn't require the setuid bit and is much more flexible. - The helper code, immediately after starting, checks if the caller is authorized to do what it asks. If not the helper immediately exits! - If the caller is authorized, the helper executes the task and exits. - The application receives data back from the helper. All these steps are managed by the library. Following sections will focus on how to write the helper to implement your actions and how to call the helper from the application. @section kauth_helper Writing the helper tool The first thing you need to do before writing anything is to decide what actions you need to implement. Every action needs to be identified by a string in the reverse domain name syntax. This helps to avoid duplicates. An example of action id is "org.kde.datetime.change" or "org.kde.ksysguard.killprocess". Action names can only contain lowercase letters and dots (not as the first or last char). You also need an identifier for your helper. An application using the KDE auth api can implement and use more than one helper, implementing different actions. An helper is uniquely identified in the system context with a string. It, again, is in reverse domain name syntax to avoid duplicates. A common approach is to call the helper like the common prefix of your action names. For example, the Date/Time kcm module could use a helper called "org.kde.datetime", to perform actions like "org.kde.datetime.changedate" and "org.kde.datetime.changetime". This naming convention simplifies the implementation of the helper. From the code point of view, the helper is implemented as a QObject subclass. Every action is implemented by a public slot. In the example/ directory in the source code tree you find a complete example. Let's look at that. The helper.h file declares the class that implements the helper. It looks like: @snippet helper.h helper_declaration The slot names are the last part of the action name, without the helper's ID if it's a prefix, with all the dots replaced by underscores. In this case, the helper ID is "org.kde.kf5auth.example", so those three slots implement the actions "org.kde.kf5auth.example.read", "org.kde.kf5auth.example.write" and "org.kde.kf5auth.example.longaction". The helper ID doesn't have to appear at the beginning of the action name, but it's good practice. If you want to extend MyHelper to implement also a different action like "org.kde.datetime.changetime", since the helper ID doesn't match you'll have to implement a slot called org_kde_datetime_changetime(). The slot's signature is fixed: the return type is ActionReply, a class that allows you to return results, error codes and custom data to the application when your action has finished to run. Let's look at the read action implementation. Its purpose is to read files: @snippet helper.cpp helper_read_action First, the code creates a default reply object. The default constructor creates a reply that reports success. Then it gets the filename parameter from the argument QVariantMap, that has previously been set by the application, before calling the helper. If it fails to open the file, it creates an ActionReply object that notifies that some error has happened in the helper, then set the error code to that returned by QFile and returns. If there is no error, it reads the file. The contents are added to the reply. Because this class will be compiled into a standalone executable, we need a main() function and some code to initialize everything: you don't have to write it. Instead, you use the KAUTH_HELPER_MAIN() macro that will take care of everything. It's used like this: @snippet helper.cpp helper_main The first parameter is the string containing the helper identifier. Please note that you need to use this same string in the application's code to tell the library which helper to call, so please stay away from typos, because we don't have any way to detect them. The second parameter is the name of the helper's class. Your helper, if complex, can be composed of a lot of source files, but the important thing is to include this macro in at least one of them. To build the helper, KDE macros provide a function named kauth_install_helper_files(). Use it in your cmake file like this: @code add_executable( your sources...) target_link_libraries( your libraries...) install(TARGETS DESTINATION ${KAUTH_HELPER_INSTALL_DIR}) kauth_install_helper_files( ) @endcode As locale is not inherited, the auth helper will have the text codec explicitly set to use UTF-8. The first argument is the cmake target name for the helper executable, which you have to build and install separately. Make sure to INSTALL THE HELPER IN ${KAUTH_HELPER_INSTALL_DIR}, otherwise kauth_install_helper_files will not work. The second argument is the helper id. Please be sure to don't misspell it, and to not quote it. The user parameter is the user that the helper has to be run as. It usually is root, but some actions could require less strict permissions, so you should use the right user where possible (for example the user apache if you have to mess with apache settings). Note that the target created by this macro already links to libkauth and QtCore. @section kauth_actions Action registration To be able to authorize the actions, they have to be added to the policy database. To do this in a cross-platform way, we provide a cmake macro. It looks like: @code kauth_install_actions( ) @endcode The action definition file describes which actions are implemented by your code and which default security options they should have. It is a common text file in ini format, with one section for each action and some parameters. The definition for the read action is: @verbatim [org.kde.kf5auth.example.read] Name=Read action Description=Read action description Policy=auth_admin Persistence=session @endverbatim The name parameter is a text describing the action for who reads the file. The description parameter is the message shown to the user in the authentication dialog. It should be a finite phrase. The policy attribute specify the default rule that the user must satisfy to be authorized. Possible values are: - yes: the action should be always allowed - no: the action should be always denied - auth_self: the user should authenticate as itself - auth_admin: the user should authenticate as an administrator user The persistence attribute is optional. It says how long an authorization should be retained for that action. The values could be: - session: the authorization persists until the user logs-out - always: the authorization will persist indefinitely If this attribute is missing, the authorization will be queried every time. @note Only the PolicyKit and polkit-1 backends use this attribute. @warning With the polkit-1 backend, 'session' and 'always' have the same meaning. They just make the authorization persists for a few minutes. @section kauth_app Calling the helper from the application Once the helper is ready, we need to call it from the main application. In examples/client.cpp you can see how this is done. To create a reference to an action, an object of type Action has to be created. Every Action object refers to an action by its action id. Two objects with the same action id will act on the same action. With an Action object, you can authorize and execute the action. To execute an action you need to retrieve an ExecuteJob, which is a standard KJob that you can run synchronously or asynchronously. See the KJob documentation (from KCoreAddons) for more details. The piece of code that calls the action of the previous example is: @snippet client.cpp client_how_to_call_helper First of all, it creates the action object specifying the action id. Then it loads the filename (we want to read a forbidden file) into the arguments() QVariantMap, which will be directly passed to the helper in the read() slot's parameter. This example code uses a synchronous call to execute the action and retrieve the reply. If the reply succeeded, the reply data is retrieved from the returned QVariantMap object. Please note that you have to explicitly set the helper ID to the action: this is done for added safety, to prevent the caller from accidentally invoking a helper, and also because KAuth actions may be used without a helper attached (the default). Please note that if your application is calling the helper multiple times it must do so from the same thread. @section kauth_async Asynchronous calls, data reporting, and action termination For a more advanced example, we look at the action "org.kde.kf5auth.example.longaction" in the example helper. This is an action that takes a long time to execute, so we need some features: - The helper needs to regularly send data to the application, to inform about the execution status. - The application needs to be able to stop the action execution if the user stops it or close the application. The example code follows: @snippet helper.cpp helper_longaction In this example, the action is only waiting a "long" time using a loop, but we can see some interesting line. The progress status is sent to the application using the HelperSupport::progressStep() method. When this method is called, the HelperProxy associated with this action will emit the progressStep() signal, reporting back the data to the application. There are two overloads of these methods and corresponding signals. The one used here takes an integer. Its meaning is application dependent, so you can use it as a sort of percentage. The other overload takes a QVariantMap object that is directly passed to the app. In this way, you can report to the application all the custom data you want. In this example code, the loop exits when the HelperSupport::isStopped() returns true. This happens when the application calls the HelperProxy::stopAction() method on the correponding action object. The stopAction() method, this way, asks the helper to stop the action execution. It's up to the helper to obbey to this request, and if it does so, it should return from the slot, _not_ exit. @section kauth_other Other features It doesn't happen very frequently that you code something that doesn't require some debugging, and you'll need some tool, even a basic one, to debug your helper code as well. For this reason, the KDE Authorization library provides a message handler for the Qt debugging system. This means that every call to qDebug() & co. will be reported to the application, and printed using the same qt debugging system, with the same debug level. If, in the helper code, you write something like: @code qDebug() << "I'm in the helper"; @endcode You'll see something like this in the application's output: @verbatim Debug message from the helper: I'm in the helper @endverbatim Remember that the debug level is preserved, so if you use qFatal() you won't only abort the helper (which isn't suggested anyway), but also the application. */ namespace KAuth { class ActionReplyData; /** * @class ActionReply kauthactionreply.h * * @brief Class that encapsulates a reply coming from the helper after executing * an action * * Helper applications will return this to describe the result of the action. * * Callers should access the reply though the KAuth::ExecuteJob job. * * @since 4.4 */ class KAUTHCORE_EXPORT ActionReply { public: /** * Enumeration of the different kinds of replies. */ enum Type { KAuthErrorType, ///< An error reply generated by the library itself. HelperErrorType, ///< An error reply generated by the helper. SuccessType ///< The action has been completed successfully }; static const ActionReply SuccessReply(); ///< An empty successful reply. Same as using the default constructor static const ActionReply HelperErrorReply(); ///< An empty reply with type() == HelperError and errorCode() == -1 static const ActionReply HelperErrorReply(int error); ///< An empty reply with type() == HelperError and error is set to the passed value static const ActionReply NoResponderReply(); ///< errorCode() == NoResponder static const ActionReply NoSuchActionReply(); ///< errorCode() == NoSuchAction static const ActionReply InvalidActionReply(); ///< errorCode() == InvalidAction static const ActionReply AuthorizationDeniedReply(); ///< errorCode() == AuthorizationDenied static const ActionReply UserCancelledReply(); ///< errorCode() == UserCancelled static const ActionReply HelperBusyReply(); ///< errorCode() == HelperBusy static const ActionReply AlreadyStartedReply(); ///< errorCode() == AlreadyStartedError static const ActionReply DBusErrorReply(); ///< errorCode() == DBusError /** * The enumeration of the possible values of errorCode() when type() is ActionReply::KAuthError */ enum Error { NoError = 0, ///< No error. NoResponderError, ///< The helper responder object hasn't been set. This shouldn't happen if you use the KAUTH_HELPER macro in the helper source NoSuchActionError, ///< The action you tried to execute doesn't exist. InvalidActionError, ///< You tried to execute an invalid action object AuthorizationDeniedError, ///< You don't have the authorization to execute the action UserCancelledError, ///< Action execution has been cancelled by the user HelperBusyError, ///< The helper is busy executing another action (or group of actions). Try later AlreadyStartedError, ///< The action was already started and is currently running DBusError, ///< An error from D-Bus occurred BackendError ///< The underlying backend reported an error }; /// Default constructor. Sets type() to Success and errorCode() to zero. ActionReply(); /** * @brief Constructor to directly set the type. * * This constructor directly sets the reply type. You shouldn't need to * directly call this constructor, because you can use the more convenient * predefined replies constants. You also shouldn't create a reply with * the KAuthError type because it's reserved for errors coming from the * library. * * @param type The type of the new reply */ ActionReply(Type type); /** * @brief Constructor that creates a KAuthError reply with a specified error code. * Do not use outside the library. * * This constructor is for internal use only, since it creates a reply * with KAuthError type, which is reserved for errors coming from the library. * * @param errorCode The error code of the new reply */ ActionReply(int errorCode); /// Copy constructor ActionReply(const ActionReply &reply); /// Virtual destructor virtual ~ActionReply(); /** * @brief Sets the custom data to send back to the application * * In the helper's code you can use this function to set an QVariantMap * with custom data that will be sent back to the application. * * @param data The new QVariantMap object. */ void setData(const QVariantMap &data); /** * @brief Returns the custom data coming from the helper. * * This method is used to get the object that contains the custom * data coming from the helper. In the helper's code, you can set it * using setData() or the convenience method addData(). * * @return The data coming from (or that will be sent by) the helper */ QVariantMap data() const; /** * @brief Convenience method to add some data to the reply. * * This method adds the pair @c key/value to the QVariantMap used to * report back custom data to the application. * * Use this method if you don't want to create a new QVariantMap only to * add a new entry. * * @param key The new entry's key * @param value The value of the new entry */ void addData(const QString &key, const QVariant &value); /// Returns the reply's type Type type() const; /** * @brief Sets the reply type * * Every time you create an action reply, you implicitly set a type. * Default constructed replies or ActionReply::SuccessReply have * type() == Success. * ActionReply::HelperErrorReply has type() == HelperError. * Predefined error replies have type() == KAuthError. * * This means you rarely need to change the type after the creation, * but if you need to, don't set it to KAuthError, because it's reserved * for errors coming from the library. * * @param type The new reply type */ void setType(Type type); /// Returns true if type() == Success bool succeeded() const; /// Returns true if type() != Success bool failed() const; /** * @brief Returns the error code of an error reply * * The error code returned is one of the values in the ActionReply::Error * enumeration if type() == KAuthError, or is totally application-dependent if * type() == HelperError. It also should be zero for successful replies. * * @return The reply error code */ int error() const; /** * @brief Returns the error code of an error reply * * The error code returned is one of the values in the ActionReply::Error * enumeration if type() == KAuthError. * Result is only valid if the type() == HelperError * * @return The reply error code */ Error errorCode() const; /** * @brief Sets the error code of an error reply * * If you're setting the error code in the helper because * you need to return an error to the application, please make sure * you already have set the type to HelperError, either by calling * setType() or by creating the reply in the right way. * * If the type is Success when you call this method, it will become KAuthError * * @param error The new reply error code */ void setError(int error); /** * @brief Sets the error code of an error reply * * @see * If you're setting the error code in the helper, use setError(int) * * If the type is Success when you call this method, it will become KAuthError * * @param errorCode The new reply error code */ void setErrorCode(Error errorCode); /** * @brief Gets a human-readble description of the error, if available * * Currently, replies of type KAuthError rarely report an error description. * This situation could change in the future. * * By now, you can use this method for custom errors of type HelperError. * * @return The error human-readable description */ QString errorDescription() const; /** * @brief Sets a human-readble description of the error * * Call this method from the helper if you want to send back a description for * a custom error. Note that this method doesn't affect the errorCode in any way * * @param error The new error description */ void setErrorDescription(const QString &error); /** * @brief Serialize the reply into a QByteArray. * * This is a convenience method used internally to sent the reply to a remote peer. * To recreate the reply, use deserialize() * * @return A QByteArray representation of this reply */ QByteArray serialized() const; /** * @brief Deserialize a reply from a QByteArray * * This method returns a reply from a QByteArray obtained from * the serialized() method. * * @param data A QByteArray obtained with serialized() */ static ActionReply deserialize(const QByteArray &data); /// Assignment operator ActionReply &operator=(const ActionReply &reply); /** * @brief Comparison operator * * This operator checks if the type and the error code of two replies are the same. * It doesn't compare the data or the error descriptions, so be careful. * * The suggested use it to compare a reply agains one of the predefined error replies: * @code * if(reply == ActionReply::HelperBusyReply) { * // Do something... * } * @endcode * * Note that you can do it also by compare errorCode() with the relative enumeration value. */ bool operator==(const ActionReply &reply) const; /** * @brief Negated comparison operator * * See the operator==() for an important notice. */ bool operator!=(const ActionReply &reply) const; /// Output streaming operator for QDataStream friend QDataStream &operator<<(QDataStream &, const ActionReply &); /// Input streaming operator for QDataStream friend QDataStream &operator>>(QDataStream &, ActionReply &); private: QSharedDataPointer d; }; } // namespace Auth Q_DECLARE_METATYPE(KAuth::ActionReply) #endif diff --git a/src/kauthexecutejob.cpp b/src/kauthexecutejob.cpp index a1d6978..4cf233c 100644 --- a/src/kauthexecutejob.cpp +++ b/src/kauthexecutejob.cpp @@ -1,241 +1,228 @@ /* -* Copyright (C) 2009-2012 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2009-2012 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include "kauthexecutejob.h" #include "BackendsManager.h" #include #include #include #include "kauthdebug.h" namespace KAuth { class Q_DECL_HIDDEN ExecuteJob::Private { public: Private(ExecuteJob *parent) : q(parent) {} ExecuteJob *q; Action action; Action::ExecutionMode mode; QVariantMap data; void doExecuteAction(); void doAuthorizeAction(); void actionPerformedSlot(const QString &action, const ActionReply &reply); void progressStepSlot(const QString &action, int i); void progressStepSlot(const QString &action, const QVariantMap &data); void statusChangedSlot(const QString &action, KAuth::Action::AuthStatus status); }; static QHash s_watchers; ExecuteJob::ExecuteJob(const Action &action, Action::ExecutionMode mode, QObject *parent) : KJob(parent) , d(new Private(this)) { d->action = action; d->mode = mode; HelperProxy *helper = BackendsManager::helperProxy(); connect(helper, SIGNAL(actionPerformed(QString,KAuth::ActionReply)), this, SLOT(actionPerformedSlot(QString,KAuth::ActionReply))); connect(helper, SIGNAL(progressStep(QString,int)), this, SLOT(progressStepSlot(QString,int))); connect(helper, SIGNAL(progressStep(QString,QVariantMap)), this, SLOT(progressStepSlot(QString,QVariantMap))); connect(BackendsManager::authBackend(), SIGNAL(actionStatusChanged(QString,KAuth::Action::AuthStatus)), this, SLOT(statusChangedSlot(QString,KAuth::Action::AuthStatus))); } ExecuteJob::~ExecuteJob() { delete d; } Action ExecuteJob::action() const { return d->action; } QVariantMap ExecuteJob::data() const { return d->data; } void ExecuteJob::start() { if (!d->action.isValid()) { qCWarning(KAUTH) << "Tried to start an invalid action: " << d->action.name(); ActionReply reply(ActionReply::InvalidActionError); reply.setErrorDescription(tr("Tried to start an invalid action")); d->actionPerformedSlot(d->action.name(), reply); return; } switch (d->mode) { case Action::ExecuteMode: QTimer::singleShot(0, this, [this]() {d->doExecuteAction();}); break; case Action::AuthorizeOnlyMode: QTimer::singleShot(0, this, [this]() {d->doAuthorizeAction();}); break; default: { ActionReply reply(ActionReply::InvalidActionError); reply.setErrorDescription(tr("Unknown execution mode chosen")); d->actionPerformedSlot(d->action.name(), reply); } break; } } bool ExecuteJob::kill(KillVerbosity verbosity) { BackendsManager::helperProxy()->stopAction(d->action.name(), d->action.helperId()); KJob::kill(verbosity); return true; } void ExecuteJob::Private::doExecuteAction() { // If this action authorizes from the client, let's do it now if (BackendsManager::authBackend()->capabilities() & KAuth::AuthBackend::AuthorizeFromClientCapability) { if (BackendsManager::authBackend()->capabilities() & KAuth::AuthBackend::PreAuthActionCapability) { BackendsManager::authBackend()->preAuthAction(action.name(), action.parentWidget()); } Action::AuthStatus s = BackendsManager::authBackend()->authorizeAction(action.name()); if (s == Action::AuthorizedStatus) { if (action.hasHelper()) { BackendsManager::helperProxy()->executeAction(action.name(), action.helperId(), action.detailsV2(), action.arguments(), action.timeout()); } else { // Done actionPerformedSlot(action.name(), ActionReply::SuccessReply()); } } else { // Abort if authorization fails switch (s) { case Action::DeniedStatus: actionPerformedSlot(action.name(), ActionReply::AuthorizationDeniedReply()); break; case Action::InvalidStatus: actionPerformedSlot(action.name(), ActionReply::InvalidActionReply()); break; case Action::UserCancelledStatus: actionPerformedSlot(action.name(), ActionReply::UserCancelledReply()); break; default: { ActionReply r(ActionReply::BackendError); r.setErrorDescription(tr("Unknown status for the authentication procedure")); actionPerformedSlot(action.name(), r); } break; } } } else if (BackendsManager::authBackend()->capabilities() & KAuth::AuthBackend::AuthorizeFromHelperCapability) { if (BackendsManager::authBackend()->capabilities() & KAuth::AuthBackend::PreAuthActionCapability) { BackendsManager::authBackend()->preAuthAction(action.name(), action.parentWidget()); } if (!action.hasHelper()) { ActionReply r(ActionReply::InvalidActionReply()); r.setErrorDescription(tr("The current backend only allows helper authorization, but this action does not have a helper.")); actionPerformedSlot(action.name(), r); return; } BackendsManager::helperProxy()->executeAction(action.name(), action.helperId(), action.detailsV2(), action.arguments(), action.timeout()); } else { // There's something totally wrong here ActionReply r(ActionReply::BackendError); r.setErrorDescription(tr("The backend does not specify how to authorize")); actionPerformedSlot(action.name(), r); } } void ExecuteJob::Private::doAuthorizeAction() { // Check the status first Action::AuthStatus s = action.status(); if (s == Action::AuthRequiredStatus) { // Let's check what to do if (BackendsManager::authBackend()->capabilities() & KAuth::AuthBackend::AuthorizeFromClientCapability) { // In this case we can actually try an authorization if (BackendsManager::authBackend()->capabilities() & KAuth::AuthBackend::PreAuthActionCapability) { BackendsManager::authBackend()->preAuthAction(action.name(), action.parentWidget()); } s = BackendsManager::authBackend()->authorizeAction(action.name()); } else if (BackendsManager::authBackend()->capabilities() & KAuth::AuthBackend::AuthorizeFromHelperCapability) { // In this case, just throw out success, as the auth will take place later s = Action::AuthorizedStatus; } else { // This should never, never happen ActionReply r(ActionReply::BackendError); r.setErrorDescription(tr("The backend does not specify how to authorize")); actionPerformedSlot(action.name(), r); } } // Return based on the current status if (s == Action::AuthorizedStatus) { actionPerformedSlot(action.name(), ActionReply::SuccessReply()); } else { actionPerformedSlot(action.name(), ActionReply::AuthorizationDeniedReply()); } } void ExecuteJob::Private::actionPerformedSlot(const QString &taction, const ActionReply &reply) { if (taction == action.name()) { if (reply.failed()) { q->setError(reply.errorCode()); q->setErrorText(reply.errorDescription()); } else { data = reply.data(); } q->emitResult(); } } void ExecuteJob::Private::progressStepSlot(const QString &taction, int i) { if (taction == action.name()) { q->setPercent(i); } } void ExecuteJob::Private::progressStepSlot(const QString &taction, const QVariantMap &data) { if (taction == action.name()) { emit q->newData(data); } } void ExecuteJob::Private::statusChangedSlot(const QString &taction, Action::AuthStatus status) { if (taction == action.name()) { emit q->statusChanged(status); } } } // namespace Auth #include "moc_kauthexecutejob.cpp" diff --git a/src/kauthexecutejob.h b/src/kauthexecutejob.h index 48a3c51..36d19df 100644 --- a/src/kauthexecutejob.h +++ b/src/kauthexecutejob.h @@ -1,140 +1,127 @@ /* -* Copyright (C) 2012 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2012 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef EXECUTE_JOB_H #define EXECUTE_JOB_H #include #include #include "kauthaction.h" #include "kauthactionreply.h" namespace KAuth { /** * @class ExecuteJob kauthexecutejob.h * * @brief Job for executing an Action * * To run the action synchonously use KJob::exec() and check the return code for * success. * * For longer tasks connect KJob::result(KJob*) and any other signals such as * percent(KJob*, unsigned long) and newData(const QVariantMap &) then run start(). * * To check for authentiation success or problems connect to * statusChanged(KAuth::Action::AuthStatus status) signal. * * Use data() to get the return result of the action. * * @since 5.0 */ class KAUTHCORE_EXPORT ExecuteJob : public KJob { Q_OBJECT ExecuteJob(const KAuth::Action &action, KAuth::Action::ExecutionMode mode, QObject *parent); friend class Action; class Private; Private *const d; Q_PRIVATE_SLOT(d, void doExecuteAction()) Q_PRIVATE_SLOT(d, void doAuthorizeAction()) Q_PRIVATE_SLOT(d, void actionPerformedSlot(const QString &action, const KAuth::ActionReply &reply)) Q_PRIVATE_SLOT(d, void progressStepSlot(const QString &action, int i)) Q_PRIVATE_SLOT(d, void progressStepSlot(const QString &action, const QVariantMap &data)) Q_PRIVATE_SLOT(d, void statusChangedSlot(const QString &action, KAuth::Action::AuthStatus status)) public: /// Virtual destructor virtual ~ExecuteJob(); /** * Starts the job asynchronously. * @see KJob::result * @see newData * @see statusChanged */ void start() override; /** * @returns the action associated with this job */ Action action() const; /** * Use this to get the data set in the action by * HelperSupport::progressStep(QVariant) or returned at the end of the * action. * * This function is particularly useful once the job has completed. During * execution, simply read the data in the newData signal. * * @see ExecuteJob::newData * @returns the data set by the helper */ QVariantMap data() const; public Q_SLOTS: /** * Attempts to halt the execution of the action associated with this job. * You should listen to the finished and result signals to work out whether * halting was successful (as long running operations can also take time * to shut down cleanly). * @see HelperSupport::isStopped() * @see KJob::result * @see KJob::finished * @return Always returns true */ bool kill(KillVerbosity verbosity = Quietly); Q_SIGNALS: /** * @brief Signal emitted by the helper to notify the action's progress * * This signal is emitted every time the helper's code calls the * HelperSupport::progressStep(QVariantMap) method. This is useful to let the * helper notify the execution status of a long action, also providing * some data, for example if you want to achieve some sort of progressive loading. * The meaning of the data passed here is totally application-dependent. * If you only need to pass some percentage, you can use the other signal that * pass an int. * * @param data The progress data from the helper */ void newData(const QVariantMap &data); /** * @brief Signal emitted when the authentication status changes * @param status the new authentication status */ void statusChanged(KAuth::Action::AuthStatus status); private: Q_DISABLE_COPY(ExecuteJob) }; } // namespace Auth #endif diff --git a/src/kauthhelpersupport.cpp b/src/kauthhelpersupport.cpp index ade000b..e6ad592 100644 --- a/src/kauthhelpersupport.cpp +++ b/src/kauthhelpersupport.cpp @@ -1,170 +1,157 @@ /* -* Copyright (C) 2008 Nicola Gigante -* Copyright (C) 2009 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + SPDX-FileCopyrightText: 2009 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include "kauthhelpersupport.h" #include #ifndef Q_OS_WIN #include #include #include #include #else // Quick hack to replace syslog (just write to stderr) // TODO: should probably use ReportEvent #define LOG_ERR 3 #define LOG_WARNING 4 #define LOG_DEBUG 7 #define LOG_INFO 6 #define LOG_USER (1<<3) static inline void openlog(const char*, int, int) {} static inline void closelog() {} #define syslog(level, ...) fprintf(stderr, __VA_ARGS__) #endif #include #include #ifdef Q_OS_UNIX #include #endif #include "BackendsManager.h" namespace KAuth { namespace HelperSupport { void helperDebugHandler(QtMsgType type, const QMessageLogContext &context, const QString &msgStr); } static bool remote_dbg = false; #ifdef Q_OS_UNIX static void fixEnvironment() { //try correct HOME const char *home = "HOME"; if (getenv(home) == nullptr) { struct passwd *pw = getpwuid(getuid()); if (pw != nullptr) { int overwrite = 0; setenv(home, pw->pw_dir, overwrite); } } } #endif int HelperSupport::helperMain(int argc, char **argv, const char *id, QObject *responder) { #ifdef Q_OS_UNIX fixEnvironment(); //As we don't inherit lang, the locale could be something that doesn't support UTF-8. Force it auto utf8Codec = QTextCodec::codecForName("UTF-8"); if (utf8Codec) { QTextCodec::setCodecForLocale(utf8Codec); } #endif #ifdef Q_OS_OSX openlog(id, LOG_CONS|LOG_PID, LOG_USER); int logLevel = LOG_WARNING; #else openlog(id, 0, LOG_USER); int logLevel = LOG_DEBUG; #endif qInstallMessageHandler(&HelperSupport::helperDebugHandler); // NOTE: The helper proxy might use dbus, and we should have the qapp // before using dbus. QCoreApplication app(argc, argv); if (!BackendsManager::helperProxy()->initHelper(QString::fromLatin1(id))) { syslog(logLevel, "Helper initialization failed"); return -1; } //closelog(); remote_dbg = true; BackendsManager::helperProxy()->setHelperResponder(responder); // Attach the timer QTimer *timer = new QTimer(nullptr); responder->setProperty("__KAuth_Helper_Shutdown_Timer", QVariant::fromValue(timer)); timer->setInterval(10000); timer->start(); QObject::connect(timer, SIGNAL(timeout()), &app, SLOT(quit())); app.exec(); //krazy:exclude=crashy return 0; } void HelperSupport::helperDebugHandler(QtMsgType type, const QMessageLogContext &context, const QString &msgStr) { Q_UNUSED(context); // can be used to find out about file, line, function name QByteArray msg = msgStr.toLocal8Bit(); if (!remote_dbg) { int level = LOG_DEBUG; switch (type) { case QtDebugMsg: level = LOG_DEBUG; break; case QtWarningMsg: level = LOG_WARNING; break; case QtCriticalMsg: case QtFatalMsg: level = LOG_ERR; break; case QtInfoMsg: level = LOG_INFO; break; } syslog(level, "%s", msg.constData()); } else { BackendsManager::helperProxy()->sendDebugMessage(type, msg.constData()); } // Anyway I should follow the rule: if (type == QtFatalMsg) { exit(-1); } } void HelperSupport::progressStep(int step) { BackendsManager::helperProxy()->sendProgressStep(step); } void HelperSupport::progressStep(const QVariantMap &data) { BackendsManager::helperProxy()->sendProgressStep(data); } bool HelperSupport::isStopped() { return BackendsManager::helperProxy()->hasToStopAction(); } } // namespace Auth diff --git a/src/kauthhelpersupport.h b/src/kauthhelpersupport.h index a6e27a4..a586d62 100644 --- a/src/kauthhelpersupport.h +++ b/src/kauthhelpersupport.h @@ -1,108 +1,95 @@ /* -* Copyright (C) 2008 Nicola Gigante -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + + SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef HELPER_SUPPORT_H #define HELPER_SUPPORT_H #include #include #include #define KAUTH_HELPER_MAIN(ID, HelperClass) \ int main(int argc, char **argv) { return KAuth::HelperSupport::helperMain(argc, argv, ID, new HelperClass()); } namespace KAuth { /** * @brief Support class with some KAUTHCORE_EXPORT methods useful to the helper's code * * This class provides the API to write the helper tool that executes your actions. * You don't create instances of HelperSupport. Instead, you use its KAUTHCORE_EXPORT methods. * * This them you can notify the application of progress in your action's execution * and you can check if the application asked you to terminate it. * * @since 4.4 */ namespace HelperSupport { /** * @brief Send a progressStep signal to the caller application * * You can use this method to notify progress information about the * action execution. When you call this method, the KAuth::ExecuteJob * object associated with the current action will emit the KJob::percent(KJob*, unsigned long) * signal. The meaning of the integer passed here is totally application dependent, * but you'll want to use it as a sort of percentage. * If you need to be more expressive, use the other overload which takes a QVariantMap * * @param step The progress indicator */ KAUTHCORE_EXPORT void progressStep(int step); /** * @brief Send a progressStep signal to the caller application * * You can use this method to notify progress information about the * action execution. When you call this method, the KAuth::ExecuteJob * object associated with the current action will emit the progressStep(QVariantMap) * signal. The meaning of the data passed here is totally application dependent. * * If you only need a simple percentage value, use the other overload which takes an int. * * @param data The progress data */ KAUTHCORE_EXPORT void progressStep(const QVariantMap &data); /** * @brief Check if the caller asked the helper to stop the execution * * This method will return true if the helper has been asked to stop the * execution of the current action. If this happens, your helper should * return (NOT exit). The meaning of the data you return in this case is * application-dependent. * * It's good practice to check it regularly if you have a long-running action * * @see ExecuteJob::kill * @return true if the helper has been asked to stop, false otherwise */ KAUTHCORE_EXPORT bool isStopped(); /** * @brief Method that implements the main function of the helper tool. Do not call directly * * This method is called in the proper way by the code generated by the KAUTH_HELPER_MAIN(), * which creates a main() function for the helper tool. * macro. You shouldn't call this method directly. * * @param argc The argc parameter from the main() function. * @param argv The argv parameter from the main() function. * @param id The helper ID as passed to the macro * @param responder The responder object for the helper. The macro passes a default-constructed, * heap-allocated object of the class specified as the last macro parameter */ KAUTHCORE_EXPORT int helperMain(int argc, char **argv, const char *id, QObject *responder); } // namespace HelperSupport } // namespace Auth #endif diff --git a/src/kauthobjectdecorator.cpp b/src/kauthobjectdecorator.cpp index cc01dea..ec6243e 100644 --- a/src/kauthobjectdecorator.cpp +++ b/src/kauthobjectdecorator.cpp @@ -1,177 +1,165 @@ -/* This file is part of the KDE libraries - Copyright (C) 2009-2012 Dario Freddi - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. +/* + This file is part of the KDE libraries + SPDX-FileCopyrightText: 2009-2012 Dario Freddi + + SPDX-License-Identifier: LGPL-2.0-or-later */ #include "kauthobjectdecorator.h" #include "kauthaction.h" #include "kauthexecutejob.h" #include "kauthdebug.h" #include #include #include namespace KAuth { class ObjectDecoratorPrivate { public: ObjectDecoratorPrivate(ObjectDecorator *parent) : q(parent), decoratedObject(parent->parent()) { } ObjectDecorator *const q; QObject *const decoratedObject; KAuth::Action authAction; // TODO: Remove whenever QIcon overlays will get fixed QIcon oldIcon; void connectDecorated(); void linkActionToWidget(); void slotActivated(); void authStatusChanged(KAuth::Action::AuthStatus status); }; void ObjectDecoratorPrivate::connectDecorated() { if (qobject_cast(decoratedObject)) { q->connect(decoratedObject, SIGNAL(clicked()), q, SLOT(slotActivated())); return; } if (qobject_cast(decoratedObject)) { q->connect(decoratedObject, SIGNAL(triggered(bool)), q, SLOT(slotActivated())); return; } qCWarning(KAUTH) << Q_FUNC_INFO << "We're not decorating an action or a button"; } void ObjectDecoratorPrivate::linkActionToWidget() { QWidget *widget = qobject_cast(decoratedObject); if (widget) { authAction.setParentWidget(widget); return; } QAction *action = qobject_cast(decoratedObject); if (action) { authAction.setParentWidget(action->parentWidget()); return; } qCWarning(KAUTH) << Q_FUNC_INFO << "We're not decorating an action or a widget"; } void ObjectDecoratorPrivate::slotActivated() { if (authAction.isValid()) { KAuth::ExecuteJob *job = authAction.execute(KAuth::Action::AuthorizeOnlyMode); q->connect(job, SIGNAL(statusChanged(KAuth::Action::AuthStatus)), q, SLOT(authStatusChanged(KAuth::Action::AuthStatus))); if (job->exec()) { emit q->authorized(authAction); } else { decoratedObject->setProperty("enabled", false); } } } void ObjectDecoratorPrivate::authStatusChanged(KAuth::Action::AuthStatus status) { switch (status) { case KAuth::Action::AuthorizedStatus: decoratedObject->setProperty("enabled", true); if (!oldIcon.isNull()) { decoratedObject->setProperty("icon", QVariant::fromValue(oldIcon)); oldIcon = QIcon(); } break; case KAuth::Action::AuthRequiredStatus: decoratedObject->setProperty("enabled", true); oldIcon = decoratedObject->property("icon").value(); decoratedObject->setProperty("icon", QIcon::fromTheme(QLatin1String("dialog-password"))); break; default: decoratedObject->setProperty("enabled", false); if (!oldIcon.isNull()) { decoratedObject->setProperty("icon", QVariant::fromValue(oldIcon)); oldIcon = QIcon(); } } } ObjectDecorator::ObjectDecorator(QObject *parent) : QObject(parent), d(new ObjectDecoratorPrivate(this)) { d->connectDecorated(); } ObjectDecorator::~ObjectDecorator() { delete d; } KAuth::Action ObjectDecorator::authAction() const { return d->authAction; } void ObjectDecorator::setAuthAction(const QString &actionName) { if (actionName.isEmpty()) { setAuthAction(KAuth::Action()); } else { setAuthAction(KAuth::Action(actionName)); } } void ObjectDecorator::setAuthAction(const KAuth::Action &action) { if (d->authAction == action) { return; } if (d->authAction.isValid()) { if (!d->oldIcon.isNull()) { d->decoratedObject->setProperty("icon", QVariant::fromValue(d->oldIcon)); d->oldIcon = QIcon(); } } if (action.isValid()) { d->authAction = action; // Set the parent widget d->linkActionToWidget(); d->authStatusChanged(d->authAction.status()); } } } // namespace KAuth #include "moc_kauthobjectdecorator.cpp" diff --git a/src/kauthobjectdecorator.h b/src/kauthobjectdecorator.h index 6165a2b..a9e2ef7 100644 --- a/src/kauthobjectdecorator.h +++ b/src/kauthobjectdecorator.h @@ -1,113 +1,101 @@ -/* This file is part of the KDE libraries - Copyright (C) 2009-2012 Dario Freddi - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. +/* + This file is part of the KDE libraries + SPDX-FileCopyrightText: 2009-2012 Dario Freddi + + SPDX-License-Identifier: LGPL-2.0-or-later */ #ifndef OBJECTDECORATOR_H #define OBJECTDECORATOR_H #include #include #include namespace KAuth { class ObjectDecoratorPrivate; /** * @class ObjectDecorator kauthobjectdecorator.h * * @brief A decorator to add auth features to a button or an action * * @author Dario Freddi */ class KAUTH_EXPORT ObjectDecorator : public QObject { Q_OBJECT public: /** * Instantiate a new decorator attached to an object * * @param parent The parent object this decorator will be attached to */ explicit ObjectDecorator(QObject *parent); /** * Destructs the decorator */ ~ObjectDecorator(); /** * Returns the action object associated with this decorator, or 0 if it does not have one * * @returns the KAuth::Action associated with this decorator. */ KAuth::Action authAction() const; /** * Sets the action object associated with this decorator * * By setting a KAuth::Action, this decorator will become associated with it, and * whenever the action or button it is attached to gets clicked, it will trigger the * authorization and execution process for the action. * Pass 0 to this function to disassociate the decorator * * @param action the KAuth::Action to associate with this decorator. */ void setAuthAction(const KAuth::Action &action); /** * Sets the action object associated with this decorator * * Overloaded member to allow creating the action by name * * @param actionName the name of the action to associate */ void setAuthAction(const QString &actionName); Q_SIGNALS: /** * Signal emitted when the action is authorized * * If the decorator needs authorization, whenever the user triggers it, * the authorization process automatically begins. * If it succeeds, this signal is emitted. The KAuth::Action object is provided for convenience * if you have multiple Action objects, but of course it's always the same set with * setAuthAction(). * * WARNING: If your button or action needs authorization you should connect eventual slots * processing stuff to this signal, and NOT clicked/triggered. Clicked/triggered will be emitted * even if the user has not been authorized * * @param action The object set with setAuthAction() */ void authorized(const KAuth::Action &action); private: friend class ObjectDecoratorPrivate; ObjectDecoratorPrivate *const d; Q_PRIVATE_SLOT(d, void slotActivated()) Q_PRIVATE_SLOT(d, void authStatusChanged(KAuth::Action::AuthStatus)) }; } // namespace KAuth #endif // OBJECTDECORATOR_H diff --git a/src/policy-gen/policy-gen.cpp b/src/policy-gen/policy-gen.cpp index fec02c0..d9e85ea 100644 --- a/src/policy-gen/policy-gen.cpp +++ b/src/policy-gen/policy-gen.cpp @@ -1,182 +1,169 @@ /* -* Copyright (C) 2008 Nicola Gigante -* Copyright (C) 2009 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + SPDX-FileCopyrightText: 2009 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #include "policy-gen.h" #include #include #include #include #include #include #include #include using namespace std; QList parse(QSettings &ini); QMap parseDomain(QSettings &ini); int main(int argc, char **argv) { QCoreApplication app(argc, argv); if (argc < 2) { qCritical("Too few arguments"); return 1; } QSettings ini(QFile::decodeName(argv[1]), QSettings::IniFormat); ini.setIniCodec("UTF-8"); if (ini.status()) { qCritical("Error loading file: %s", argv[1]); return 1; } if (argc == 3) { // Support an optional 2nd argument pointing to the output file // // This is safer to use in build systems than // "kauth-policy-gen foo.actions > foo.policy" because when using a // redirection "foo.policy" is created even if kauth-policy-gen fails. // This means the first call to make fails, but a second call succeeds // because an empty "foo.policy" exists. if (!freopen(argv[2], "w", stdout)) { qCritical("Failed to open %s for writing: %s", argv[2], strerror(errno)); return 1; } } output(parse(ini), parseDomain(ini)); } QList parse(QSettings &ini) { QList actions; // example: [org.kde.kcontrol.kcmfoo.save] const QRegularExpression actionExp(QRegularExpression::anchoredPattern(QStringLiteral("[0-9a-z]+(\\.[0-9a-z]+)*"))); // example: Description[ca]=Mòdul de control del Foo. const QRegularExpression descriptionExp(QRegularExpression::anchoredPattern(QStringLiteral("description(?:\\[(\\w+)\\])?")), QRegularExpression::CaseInsensitiveOption); // example: Name[ca]=Mòdul de control del Foo const QRegularExpression nameExp(QRegularExpression::anchoredPattern(QStringLiteral("name(?:\\[(\\w+)\\])?")), QRegularExpression::CaseInsensitiveOption); // example: Policy=auth_admin const QRegularExpression policyExp(QRegularExpression::anchoredPattern(QStringLiteral("(?:yes|no|auth_self|auth_admin)"))); const auto listChilds = ini.childGroups(); for (const QString &name : listChilds) { Action action; if (name == QLatin1String("Domain")) { continue; } if (!actionExp.match(name).hasMatch()) { qCritical("Wrong action syntax: %s\n", name.toLatin1().data()); exit(1); } action.name = name; ini.beginGroup(name); const auto listChildKeys = ini.childKeys(); for (const QString &key : listChildKeys) { QRegularExpressionMatch match; if ((match = descriptionExp.match(key)).hasMatch()) { QString lang = match.captured(1); if (lang.isEmpty()) { lang = QString::fromLatin1("en"); } action.descriptions.insert(lang, ini.value(key).toString()); } else if ((match = nameExp.match(key)).hasMatch()) { QString lang = match.captured(1); if (lang.isEmpty()) { lang = QString::fromLatin1("en"); } action.messages.insert(lang, ini.value(key).toString()); } else if (key.toLower() == QLatin1String("policy")) { QString policy = ini.value(key).toString(); if (!policyExp.match(policy).hasMatch()) { qCritical("Wrong policy: %s", policy.toLatin1().data()); exit(1); } action.policy = policy; } else if (key.toLower() == QLatin1String("policyinactive")) { QString policyInactive = ini.value(key).toString(); if (!policyExp.match(policyInactive).hasMatch()) { qCritical("Wrong policy: %s", policyInactive.toLatin1().data()); exit(1); } action.policyInactive = policyInactive; } else if (key.toLower() == QLatin1String("persistence")) { QString persistence = ini.value(key).toString(); if (persistence != QLatin1String("session") && persistence != QLatin1String("always")) { qCritical("Wrong persistence: %s", persistence.toLatin1().data()); exit(1); } action.persistence = persistence; } } if (action.policy.isEmpty() || action.messages.isEmpty() || action.descriptions.isEmpty()) { qCritical("Missing option in action: %s", name.toLatin1().data()); exit(1); } ini.endGroup(); actions.append(action); } return actions; } QMap parseDomain(QSettings &ini) { QMap rethash; if (ini.childGroups().contains(QString::fromLatin1("Domain"))) { if (ini.contains(QString::fromLatin1("Domain/Name"))) { rethash[QString::fromLatin1("vendor")] = ini.value(QString::fromLatin1("Domain/Name")).toString(); } if (ini.contains(QString::fromLatin1("Domain/URL"))) { rethash[QString::fromLatin1("vendorurl")] = ini.value(QString::fromLatin1("Domain/URL")).toString(); } if (ini.contains(QString::fromLatin1("Domain/Icon"))) { rethash[QString::fromLatin1("icon")] = ini.value(QString::fromLatin1("Domain/Icon")).toString(); } } return rethash; } diff --git a/src/policy-gen/policy-gen.h b/src/policy-gen/policy-gen.h index ab1e605..9bb425a 100644 --- a/src/policy-gen/policy-gen.h +++ b/src/policy-gen/policy-gen.h @@ -1,41 +1,28 @@ /* -* Copyright (C) 2008 Nicola Gigante -* Copyright (C) 2009 Dario Freddi -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU Lesser General Public License as published by -* the Free Software Foundation; either version 2.1 of the License, or -* (at your option) any later version. -* -* 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 Lesser General Public License -* along with this program; if not, write to the -* Free Software Foundation, Inc., -* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . + SPDX-FileCopyrightText: 2008 Nicola Gigante + SPDX-FileCopyrightText: 2009 Dario Freddi + + SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef _POLICY_GEN_H_ #define _POLICY_GEN_H_ #include #include #include struct Action { QString name; QMap descriptions; QMap messages; QString policy; QString policyInactive; QString persistence; }; extern void output(const QList &actions, const QMap &domain); #endif