aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/coreplugin/secretaspect.cpp
blob: cd96733da60df096ef47908266bfa9bae58d3816 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "secretaspect.h"

#include "coreplugintr.h"
#include "credentialquery.h"

#include <qtkeychain/keychain.h>

#include <QtTaskTree/QTaskTree>
#include <QtTaskTree/QSingleTaskTreeRunner>

#include <utils/guardedcallback.h>
#include <utils/hostosinfo.h>
#include <utils/layoutbuilder.h>
#include <utils/passworddialog.h>
#include <utils/qtcsettings.h>
#include <utils/utilsicons.h>

#include <QIcon>
#include <QPointer>

using namespace QKeychain;
using namespace QtTaskTree;
using namespace Utils;

namespace Core {

using ReadCallback = std::function<void(Utils::Result<QString>)>;

class SecretAspectPrivate
{
public:
    void callReadCallbacks(const Result<QString> &value)
    {
        for (const auto &callback : readCallbacks)
            callback(value);
        readCallbacks.clear();
    }

public:
    QSingleTaskTreeRunner readRunner;
    QSingleTaskTreeRunner writeRunner;
    bool wasFetchedFromSecretStorage = false;
    bool wasEdited = false;
    bool repeatWriting = false;
    std::vector<ReadCallback> readCallbacks;
    QString value;
};

SecretAspect::SecretAspect(AspectContainer *container)
    : Utils::BaseAspect(container)
    , d(new SecretAspectPrivate)
{}

SecretAspect::~SecretAspect() = default;

static bool applyKey(const SecretAspect &aspect, CredentialQuery &op)
{
    QStringList keyParts = stringFromKey(aspect.settingsKey()).split('.');
    if (keyParts.size() < 2)
        return false;
    op.setKey(keyParts.takeLast());
    op.setService(keyParts.join('.'));
    return true;
}

void SecretAspect::readSecret(const std::function<void(Result<QString>)> &cb) const
{
    d->readCallbacks.push_back(cb);

    if (d->readRunner.isRunning())
        return;

    if (!QKeychain::isAvailable()) {
        qWarning() << "No Keychain available, reading from plaintext";
        QtcSettings &settings = Utils::userSettings();
        settings.beginGroup("Secrets");
        QVariant value = settings.value(settingsKey());
        settings.endGroup();

        d->callReadCallbacks(fromSettingsValue(value).toString());
        return;
    }

    const auto onGetCredentialSetup = [this](CredentialQuery &credential) {
        credential.setOperation(CredentialOperation::Get);
        if (!applyKey(*this, credential))
            return SetupResult::StopWithError;
        return SetupResult::Continue;
    };
    const auto onGetCredentialDone = [this](const CredentialQuery &credential, DoneWith result) {
        if (result == DoneWith::Success) {
            d->value = QString::fromUtf8(credential.data().value_or(QByteArray{}));
            d->wasFetchedFromSecretStorage = true;
            d->callReadCallbacks(d->value);
        } else {
            d->callReadCallbacks(make_unexpected(credential.errorString()));
        }
        return DoneResult::Success;
    };

    d->readRunner.start({CredentialQueryTask(onGetCredentialSetup, onGetCredentialDone)});
}

QString SecretAspect::warningThatNoSecretStorageIsAvailable()
{
    static QString warning
        = Tr::tr("Secret storage is not available! "
                 "Your values will be stored as plaintext in the settings!")
          + (HostOsInfo::isLinuxHost()
                 ? (" " + Tr::tr("You can install libsecret or KWallet to enable secret storage."))
                 : QString());
    return warning;
}

void SecretAspect::readSettings()
{
    readSecret([](const Result<QString> &) {});
}

void SecretAspect::writeSettings() const
{
    if (!d->wasEdited)
        return;

    if (!QKeychain::isAvailable()) {
        QtcSettings &settings = Utils::userSettings();
        settings.beginGroup("Secrets");
        settings.setValue(settingsKey(), toSettingsValue(d->value));
        settings.endGroup();
        d->wasEdited = false;
        return;
    }

    d->repeatWriting = true;

    if (d->writeRunner.isRunning())
        return;

    const auto onSetCredentialSetup = [this](CredentialQuery &credential) {
        credential.setOperation(CredentialOperation::Set);
        credential.setData(d->value.toUtf8());

        if (!applyKey(*this, credential))
            return SetupResult::StopWithError;
        return SetupResult::Continue;
    };

    const auto onSetCredentialsDone = [this](const CredentialQuery &, DoneWith result) {
        if (result == DoneWith::Success)
            d->wasEdited = false;
        return DoneResult::Success;
    };

    const UntilIterator iterator([this](int) { return std::exchange(d->repeatWriting, false); });

    // clang-format off
    d->writeRunner.start(
        For (iterator) >> Do {
            CredentialQueryTask(onSetCredentialSetup, onSetCredentialsDone)
        }
    );
    // clang-format on
}

bool SecretAspect::isDirty()
{
    return d->wasEdited;
}

void SecretAspect::addToLayoutImpl(Layouting::Layout &parent)
{
    auto edit = createSubWidget<FancyLineEdit>();
    edit->setEchoMode(QLineEdit::Password);
    auto showPasswordButton = createSubWidget<Utils::ShowPasswordButton>();
    // Keep read-only/disabled until we have retrieved the value.
    edit->setReadOnly(true);
    showPasswordButton->setEnabled(false);
    QLabel *warningLabel = nullptr;

    if (!QKeychain::isAvailable()) {
        warningLabel = new QLabel();
        warningLabel->setPixmap(Utils::Icons::WARNING.icon().pixmap(16, 16));
        warningLabel->setToolTip(warningThatNoSecretStorageIsAvailable());
        edit->setToolTip(warningThatNoSecretStorageIsAvailable());
    }

    requestValue(
        guardedCallback(edit, [edit, showPasswordButton](const Utils::Result<QString> &value) {
            if (!value) {
                edit->setPlaceholderText(value.error());
                return;
            }

            edit->setReadOnly(false);
            showPasswordButton->setEnabled(true);
            edit->setText(*value);
        }));

    connect(showPasswordButton, &ShowPasswordButton::toggled, edit, [showPasswordButton, edit] {
        edit->setEchoMode(showPasswordButton->isChecked() ? QLineEdit::Normal : QLineEdit::Password);
    });

    connect(edit, &FancyLineEdit::textChanged, this, [this](const QString &text) {
        d->value = text;
        d->wasEdited = true;
    });

    addLabeledItem(parent, Layouting::Row{Layouting::noMargin, edit, warningLabel, showPasswordButton}.emerge());
}

void SecretAspect::requestValue(
    const std::function<void(const Utils::Result<QString> &)> &callback) const
{
    if (d->wasEdited)
        callback(d->value);
    else if (d->wasFetchedFromSecretStorage)
        callback(d->value);
    else
        readSecret(callback);
}

void SecretAspect::setValue(const QString &value)
{
    d->value = value;
    d->wasEdited = true;
}

bool SecretAspect::isSecretStorageAvailable()
{
    return QKeychain::isAvailable();
}

} // namespace Core