~jamesh/online-accounts-api/custom-connection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
/*
 * This file is part of OnlineAccountsDaemon
 *
 * Copyright (C) 2015-2016 Canonical Ltd.
 *
 * Contact: Alberto Mardegan <alberto.mardegan@canonical.com>
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version 3, as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranties of
 * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the GNU Lesser 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, see <http://www.gnu.org/licenses/>.
 */

#include "manager.h"

#include <Accounts/Account>
#include <Accounts/AccountService>
#include <Accounts/Application>
#include <Accounts/AuthData>
#include <Accounts/Manager>
#include <Accounts/Service>
#include <QCoreApplication>
#include <QDebug>
#include <QHash>
#include <QPair>
#include <QSet>
#include "access_request.h"
#include "authentication_request.h"
#include "client_registry.h"
#include "dbus_constants.h"
#include "manager_adaptor.h"
#include "state_saver.h"

using namespace OnlineAccountsDaemon;

namespace OnlineAccountsDaemon {

struct ActiveAccount {
    ActiveAccount(): accountService(0) {}

    bool isValid() const { return accountService != 0; }
    Accounts::AccountService *accountService;
    QSet<QString> clients;
};

typedef QPair<Accounts::AccountId,QString> AccountCoordinates;
typedef QHash<QString,Accounts::Application> ClientMap;

class ManagerPrivate: public QObject
{
    Q_OBJECT
    Q_DECLARE_PUBLIC(Manager)

public:
    ManagerPrivate(Manager *q);
    ~ManagerPrivate();

    QString applicationIdFromServiceId(const QString &serviceId);

    void watchAccount(Accounts::Account *account);
    void handleNewAccountService(Accounts::Account *account,
                                 const Accounts::Service &service);
    void loadActiveAccounts();
    void saveState();
    ActiveAccount &addActiveAccount(Accounts::AccountId accountId,
                                    const QString &serviceName,
                                    const QString &client);
    ActiveAccount &addActiveAccount(Accounts::AccountId accountId,
                                    const QString &serviceName,
                                    const QStringList &clients);

    int authMethod(const Accounts::AuthData &authData);
    AccountInfo readAccountInfo(const Accounts::AccountService *as);
    QList<AccountInfo> getAccounts(const QVariantMap &filters,
                                   const CallContext &context);
    void authenticate(uint accountId, const QString &serviceId,
                      bool interactive, bool invalidate,
                      const QVariantMap &parameters,
                      const CallContext &context);
    void requestAccess(const QString &serviceId,
                       const QVariantMap &parameters,
                       const CallContext &context);
    bool canAccess(const QString &context, const QString &serviceId);

    void notifyAccountChange(const ActiveAccount &account, uint change);

private Q_SLOTS:
    void onActiveContextsChanged();
    void onAccountServiceEnabled(bool enabled);
    void onAccountServiceChanged();
    void onAccountEnabled(const QString &serviceId, bool enabled);
    void onAccountCreated(Accounts::AccountId accountId);
    void onLoadRequest(uint accountId, const QString &serviceId);

private:
    ManagerAdaptor *m_adaptor;
    Accounts::Manager m_manager;
    StateSaver m_stateSaver;
    bool m_mustEmitNotifications;
    QHash<AccountCoordinates,ActiveAccount> m_activeAccounts;
    ClientMap m_clients;
    QList<Accounts::Account*> m_watchedAccounts;
    bool m_isIdle;
    Manager *q_ptr;
};

} // namespace

ManagerPrivate::ManagerPrivate(Manager *q):
    QObject(q),
    m_adaptor(new ManagerAdaptor(q)),
    m_mustEmitNotifications(false),
    m_isIdle(true),
    q_ptr(q)
{
    CallContextCounter *counter = CallContextCounter::instance();
    QObject::connect(counter, SIGNAL(activeContextsChanged()),
                     this, SLOT(onActiveContextsChanged()));

    loadActiveAccounts();

    QObject::connect(&m_manager, SIGNAL(accountCreated(Accounts::AccountId)),
                     this, SLOT(onAccountCreated(Accounts::AccountId)));
}

ManagerPrivate::~ManagerPrivate()
{
    saveState();
}

void ManagerPrivate::onActiveContextsChanged()
{
    Q_Q(Manager);
    CallContextCounter *counter = CallContextCounter::instance();
    if (counter->activeContexts() == 0) {
        m_isIdle = true;
        Q_EMIT q->isIdleChanged();
    } else if (m_isIdle) {
        m_isIdle = false;
        Q_EMIT q->isIdleChanged();
    }
}

QString ManagerPrivate::applicationIdFromServiceId(const QString &serviceId)
{
    Accounts::Service service = m_manager.service(serviceId);
    Accounts::ApplicationList apps = m_manager.applicationList(service);
    if (apps.isEmpty()) return QString();

    /* TODO: to figure out the correct app, take the security context into
     * account */
    return apps.first().name();
}

void ManagerPrivate::watchAccount(Accounts::Account *account)
{
    if (m_watchedAccounts.contains(account)) return;

    QObject::connect(account, SIGNAL(enabledChanged(const QString &, bool)),
                     this, SLOT(onAccountEnabled(const QString &, bool)));
    m_watchedAccounts.append(account);
}

void ManagerPrivate::handleNewAccountService(Accounts::Account *account,
                                             const Accounts::Service &service)
{
    AccountCoordinates coords(account->id(), service.name());
    if (m_activeAccounts.contains(coords)) {
        /* This event is also received via the AccountService instance; we'll
         * handle it from there. */
        return;
    }

    QStringList interestedClients;
    for (auto i = m_clients.constBegin();
         i != m_clients.constEnd(); i++) {
        const Accounts::Application &application = i.value();

        if (!application.serviceUsage(service).isEmpty()) {
            interestedClients.append(i.key());
        }
    }
    ActiveAccount &activeAccount =
        addActiveAccount(account->id(), service.name(), interestedClients);
    notifyAccountChange(activeAccount,
                        ONLINE_ACCOUNTS_INFO_CHANGE_ENABLED);
}

void ManagerPrivate::loadActiveAccounts()
{
    QSet<Client> oldClients = m_stateSaver.clients().toSet();
    ClientRegistry *clientRegistry = ClientRegistry::instance();
    QStringList oldClientNames;
    Q_FOREACH(const Client &client, oldClients) {
        oldClientNames.append(client.first);
    }
    clientRegistry->registerActiveClients(oldClientNames);

    /* Build the table of the active clients */
    QStringList activeClientNames = clientRegistry->clients();
    Q_FOREACH(const Client &client, oldClients) {
        if (activeClientNames.contains(client.first)) {
            m_clients[client.first] = m_manager.application(client.second);
        }
    }

    QList<AccountInfo> oldAccounts = m_stateSaver.accounts();
    Q_FOREACH(const AccountInfo &accountInfo, oldAccounts) {
        // If no clients are interested in this account, ignore it
        Accounts::Service service =
            m_manager.service(accountInfo.serviceId());
        if (Q_UNLIKELY(!service.isValid())) continue;

        QStringList clients;
        for (auto i = m_clients.constBegin();
             i != m_clients.constEnd(); i++) {
            const Accounts::Application &application = i.value();
            if (!application.serviceUsage(service).isEmpty()) {
                clients.append(i.key());
            }
        }
        if (clients.isEmpty()) {
            // no one is interested in this account
            continue;
        }

        ActiveAccount &activeAccount =
            addActiveAccount(accountInfo.accountId, service.name(), clients);
        if (Q_UNLIKELY(!activeAccount.isValid())) continue;

        if (!activeAccount.accountService->isEnabled()) {
            // the account got disabled while this daemon was not running
            notifyAccountChange(activeAccount,
                                ONLINE_ACCOUNTS_INFO_CHANGE_DISABLED);
        } else {
            AccountInfo newAccountInfo =
                readAccountInfo(activeAccount.accountService);
            if (newAccountInfo.details != accountInfo.details) {
                notifyAccountChange(activeAccount,
                                    ONLINE_ACCOUNTS_INFO_CHANGE_UPDATED);
            }
        }
    }

    /* Last, go through all active clients and see if there are new accounts
     * for any of them. */
    Q_FOREACH(Accounts::AccountId accountId, m_manager.accountListEnabled()) {
        Accounts::Account *account = m_manager.account(accountId);
        if (Q_UNLIKELY(!account)) continue;

        watchAccount(account);
        Q_FOREACH(Accounts::Service service, account->enabledServices()) {
            handleNewAccountService(account, service);
        }
    }
}

void ManagerPrivate::saveState()
{
    QList<Client> clients;
    for (auto i = m_clients.constBegin(); i != m_clients.constEnd(); i++) {
        const Accounts::Application &application = i.value();
        clients.append(Client(i.key(), application.name()));
    }
    m_stateSaver.setClients(clients);

    QList<AccountInfo> accounts;
    Q_FOREACH(const ActiveAccount &activeAccount, m_activeAccounts) {
        if (!activeAccount.isValid()) continue;

        accounts.append(readAccountInfo(activeAccount.accountService));
    }
    m_stateSaver.setAccounts(accounts);
}

void ManagerPrivate::notifyAccountChange(const ActiveAccount &account,
                                         uint change)
{
    AccountInfo info = readAccountInfo(account.accountService);
    m_adaptor->notifyAccountChange(info, change);
}

ActiveAccount &ManagerPrivate::addActiveAccount(Accounts::AccountId accountId,
                                                const QString &serviceName,
                                                const QString &client)
{
    return addActiveAccount(accountId, serviceName, QStringList() << client);
}

ActiveAccount &ManagerPrivate::addActiveAccount(Accounts::AccountId accountId,
                                                const QString &serviceName,
                                                const QStringList &clients)
{
    ActiveAccount &activeAccount =
        m_activeAccounts[AccountCoordinates(accountId, serviceName)];
    activeAccount.clients += clients.toSet();
    if (!activeAccount.accountService) {
        Accounts::Account *account = m_manager.account(accountId);
        if (Q_UNLIKELY(!account)) return activeAccount;

        Accounts::Service service = m_manager.service(serviceName);
        auto as = new Accounts::AccountService(account, service);
        activeAccount.accountService = as;
        QObject::connect(as, SIGNAL(enabled(bool)),
                         this, SLOT(onAccountServiceEnabled(bool)));
        QObject::connect(as, SIGNAL(changed()),
                         this, SLOT(onAccountServiceChanged()));
    }

    return activeAccount;
}

int ManagerPrivate::authMethod(const Accounts::AuthData &authData)
{
    QString method = authData.method();
    QString mechanism = authData.mechanism();
    if (method == "oauth2") {
        if (mechanism == "web_server" || mechanism == "user_agent") {
            return ONLINE_ACCOUNTS_AUTH_METHOD_OAUTH2;
        } else if (mechanism == "HMAC-SHA1" || mechanism == "PLAINTEXT") {
            return ONLINE_ACCOUNTS_AUTH_METHOD_OAUTH1;
        }
    } else if (method == "sasl") {
        return ONLINE_ACCOUNTS_AUTH_METHOD_SASL;
    } else if (method == "password") {
        return ONLINE_ACCOUNTS_AUTH_METHOD_PASSWORD;
    }

    return ONLINE_ACCOUNTS_AUTH_METHOD_UNKNOWN;
}

AccountInfo ManagerPrivate::readAccountInfo(const Accounts::AccountService *as)
{
    QVariantMap info;

    info[ONLINE_ACCOUNTS_INFO_KEY_DISPLAY_NAME] = as->account()->displayName();
    info[ONLINE_ACCOUNTS_INFO_KEY_SERVICE_ID] = as->service().name();

    info[ONLINE_ACCOUNTS_INFO_KEY_AUTH_METHOD] = authMethod(as->authData());
    QString settingsPrefix(QStringLiteral(ONLINE_ACCOUNTS_INFO_KEY_SETTINGS));
    /* First, read the global settings */
    Accounts::Account *a = as->account();
    a->selectService();
    Q_FOREACH(const QString &key, a->allKeys()) {
        if (key == "enabled" || key == "CredentialsId" || key == "name" ||
            key.startsWith("auth/")) continue;
        info[settingsPrefix + key] = a->value(key);
    }

    /* Then, add service-specific settings */
    Q_FOREACH(const QString &key, as->allKeys()) {
        if (key == "enabled") continue;
        info[settingsPrefix + key] = as->value(key);
    }

    return AccountInfo(as->account()->id(), info);
}

QList<AccountInfo> ManagerPrivate::getAccounts(const QVariantMap &filters,
                                               const CallContext &context)
{
    QString desiredApplicationId = filters.value("applicationId").toString();
    QString desiredServiceId = filters.value("serviceId").toString();
    Accounts::AccountId desiredAccountId = filters.value("accountId").toUInt();

    Accounts::Application application = desiredApplicationId.isEmpty() ?
        Accounts::Application() : m_manager.application(desiredApplicationId);

    if (application.isValid() &&
        canAccess(context.securityContext(), desiredApplicationId)) {
        m_clients.insert(context.clientName(), application);
    }

    QList<AccountInfo> accounts;

    Q_FOREACH(Accounts::AccountId accountId, m_manager.accountListEnabled()) {
        if (desiredAccountId != 0 && accountId != desiredAccountId) {
            continue;
        }

        Accounts::Account *account = m_manager.account(accountId);
        if (Q_UNLIKELY(!account)) continue;

        Q_FOREACH(Accounts::Service service, account->enabledServices()) {
            if (!desiredServiceId.isEmpty() &&
                service.name() != desiredServiceId) {
                continue;
            }

            if (!canAccess(context.securityContext(), service.name())) {
                continue;
            }

            if (application.isValid() &&
                application.serviceUsage(service).isEmpty()) {
                /* The application does not support this service */
                continue;
            }

            ActiveAccount &activeAccount =
                addActiveAccount(accountId, service.name(),
                                 context.clientName());
            accounts.append(readAccountInfo(activeAccount.accountService));
        }
    }

    return accounts;
}

void ManagerPrivate::authenticate(uint accountId, const QString &serviceId,
                                  bool interactive, bool invalidate,
                                  const QVariantMap &parameters,
                                  const CallContext &context)
{
    if (!canAccess(context.securityContext(), serviceId)) {
        context.sendError(ONLINE_ACCOUNTS_ERROR_PERMISSION_DENIED,
                          QString("Access to service ID %1 forbidden").arg(serviceId));
        return;
    }

    ActiveAccount &activeAccount =
        addActiveAccount(accountId, serviceId, context.clientName());
    auto as = activeAccount.accountService;
    if (!as || !as->isEnabled()) {
        context.sendError(ONLINE_ACCOUNTS_ERROR_PERMISSION_DENIED,
                          QString("Account %1 is disabled").arg(accountId));
        return;
    }

    AuthenticationRequest *authentication =
        new AuthenticationRequest(context, this);
    authentication->setInteractive(interactive);
    if (invalidate) {
        authentication->invalidateCache();
    }
    authentication->authenticate(as->authData(), parameters);
}

void ManagerPrivate::requestAccess(const QString &serviceId,
                                   const QVariantMap &parameters,
                                   const CallContext &context)
{
    Q_UNUSED(parameters);
    if (!canAccess(context.securityContext(), serviceId)) {
        context.sendError(ONLINE_ACCOUNTS_ERROR_PERMISSION_DENIED,
                          QString("Access to service ID %1 forbidden").arg(serviceId));
        return;
    }

    AccessRequest *accessRequest = new AccessRequest(context, this);
    QObject::connect(accessRequest, SIGNAL(loadRequest(uint, const QString&)),
                     this, SLOT(onLoadRequest(uint, const QString&)));
    QString applicationId = applicationIdFromServiceId(serviceId);
    accessRequest->requestAccess(applicationId, serviceId, parameters,
                                 context.clientPid());
}

bool ManagerPrivate::canAccess(const QString &context,
                               const QString &serviceId)
{
    // Could not determine peer's AppArmor context, so deny access
    if (context.isEmpty()) {
        return false;
    }
    // Unconfined processes can access anything
    if (context == "unconfined") {
        return true;
    }

    // Try to extract the click package name from the AppArmor context.
    int pos = context.indexOf('_');
    if (pos < 0) {
        qWarning() << "AppArmor context doesn't contain package ID: " << context;
        return false;
    }
    QString pkgname = context.left(pos);

    // Do the same on the service ID: we are only dealing with
    // confined apps at this point, so only $pkgname prefixed
    // services are accessible.
    pos = serviceId.indexOf('_');
    if (pos < 0) {
        return false;
    }
    return serviceId.left(pos) == pkgname;
}

void ManagerPrivate::onAccountServiceEnabled(bool enabled)
{
    auto as = qobject_cast<Accounts::AccountService*>(sender());

    ActiveAccount &activeAccount =
        m_activeAccounts[AccountCoordinates(as->account()->id(),
                                            as->service().name())];
    if (Q_UNLIKELY(!activeAccount.isValid())) return;

    notifyAccountChange(activeAccount,
                        enabled ? ONLINE_ACCOUNTS_INFO_CHANGE_ENABLED :
                        ONLINE_ACCOUNTS_INFO_CHANGE_DISABLED);
}

void ManagerPrivate::onAccountServiceChanged()
{
    auto as = qobject_cast<Accounts::AccountService*>(sender());
    if (!as->isEnabled()) {
        // Nobody cares about disabled accounts
        return;
    }

    ActiveAccount &activeAccount =
        m_activeAccounts[AccountCoordinates(as->account()->id(),
                                            as->service().name())];
    if (Q_UNLIKELY(!activeAccount.isValid())) return;

    notifyAccountChange(activeAccount, ONLINE_ACCOUNTS_INFO_CHANGE_UPDATED);
}

void ManagerPrivate::onAccountEnabled(const QString &serviceId, bool enabled)
{
    if (!enabled) {
        /* We don't care about these. If we have an AccountService active, we
         * will be receiving the same event though it. */
        return;
    }
    auto account = qobject_cast<Accounts::Account*>(sender());
    handleNewAccountService(account, m_manager.service(serviceId));
}

void ManagerPrivate::onAccountCreated(Accounts::AccountId accountId)
{
    Accounts::Account *account = m_manager.account(accountId);
    if (Q_UNLIKELY(!account)) return;
    watchAccount(account);
    Q_FOREACH(Accounts::Service service, account->enabledServices()) {
        handleNewAccountService(account, service);
    }
}

void ManagerPrivate::onLoadRequest(uint accountId, const QString &serviceId)
{
    AccessRequest *request = qobject_cast<AccessRequest*>(sender());

    ActiveAccount &activeAccount =
        addActiveAccount(accountId, serviceId,
                         request->context().clientName());
    auto as = activeAccount.accountService;
    request->setAccountInfo(readAccountInfo(as), as->authData());
}

Manager::Manager(QObject *parent):
    QObject(parent),
    d_ptr(new ManagerPrivate(this))
{
}

Manager::~Manager()
{
    delete d_ptr;
}

bool Manager::isIdle() const
{
    Q_D(const Manager);
    return d->m_isIdle;
}

QList<AccountInfo> Manager::getAccounts(const QVariantMap &filters,
                                        const CallContext &context)
{
    Q_D(Manager);
    return d->getAccounts(filters, context);
}

void Manager::authenticate(uint accountId, const QString &serviceId,
                           bool interactive, bool invalidate,
                           const QVariantMap &parameters,
                           const CallContext &context)
{
    Q_D(Manager);
    d->authenticate(accountId, serviceId, interactive, invalidate,
                    parameters, context);
}

void Manager::requestAccess(const QString &serviceId,
                            const QVariantMap &parameters,
                            const CallContext &context)
{
    Q_D(Manager);
    d->requestAccess(serviceId, parameters, context);
}

void Manager::onDisconnected()
{
    qDebug() << "Disconnected from D-Bus: quitting";
    QCoreApplication::instance()->quit();
}

void *oad_create_manager(QObject *parent)
{
    return new Manager(parent);
}

#include "manager.moc"