QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
usersdialog.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2015 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
8#include "usersdialog.h"
9#include "importkeydialog.h"
10#include "pass.h"
11#include "plainmessagebox.h"
12#include "qtpasssettings.h"
13#include "ui_usersdialog.h"
14#include "util.h"
15#include "windowstatestore.h"
16#include <QApplication>
17#include <QDateTime>
18#include <QDialogButtonBox>
19#include <QDir>
20#include <QFileInfo>
21#include <QFont>
22#include <QHash>
23#include <QKeyEvent>
24#include <QLabel>
25#include <QLineEdit>
26#include <QListWidget>
27#include <QMessageBox>
28#include <QPalette>
29#include <QPushButton>
30#include <QRegularExpression>
31#include <QScrollArea>
32#include <QSet>
33#include <QSignalBlocker>
34#include <QWidget>
35#include <algorithm>
36#include <iterator>
37#include <utility>
38
39#include "qtpasslogging.h"
40UsersDialog::UsersDialog(Pass *pass, const AppSettings &s, QString dir,
41 QWidget *parent)
42 : UsersDialog(pass, s, std::move(dir), Preselect::FromList, parent) {}
43
44UsersDialog::UsersDialog(Pass *pass, const AppSettings &s, QString dir,
45 Preselect preselect, QWidget *parent)
46 : QDialog(parent), ui(new Ui::UsersDialog), m_pass(pass),
47 m_passStore(s.passStore), m_gpgExe(s.gpgExecutable),
48 m_dir(std::move(dir)), m_preselect(preselect) {
49 Q_ASSERT(pass);
50 ui->setupUi(this);
51
53 if (!loadGpgKeys()) {
54 connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
55 return;
56 }
57
61
63}
64
66 connect(ui->buttonBox, &QDialogButtonBox::accepted, this,
68 connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
69 connect(ui->listWidget, &QListWidget::itemChanged, this,
71 // importKeyButton is wired via Qt's automatic on_<name>_<signal> mechanism
72 // already triggered by setupUi().
73
74 ui->lineEdit->setClearButtonEnabled(true);
75}
76
78 WindowStateStore::attach(*this, QStringLiteral("usersDialog"));
79}
80
82 QList<UserInfo> users = m_pass->listKeys();
83 if (users.isEmpty()) {
84 QMessageBox::critical(parentWidget(), tr("Keylist missing"),
85 tr("Could not fetch list of available GPG keys"));
86 reject();
87 return false;
88 }
89
90 markSecretKeys(users);
91
92 m_userList = std::move(users);
93 return true;
94}
95
96void UsersDialog::markSecretKeys(QList<UserInfo> &users) {
97 QList<UserInfo> secret_keys = m_pass->listKeys("", true);
98 QSet<QString> secretKeyIds;
99 for (const UserInfo &sec : std::as_const(secret_keys)) {
100 secretKeyIds.insert(sec.key_id);
101 }
102 for (auto &user : users) {
103 if (secretKeyIds.contains(user.key_id)) {
104 user.have_secret = true;
105 }
106 }
107}
108
109void UsersDialog::showRecipientWarning(const QString &text,
110 const QString &name) {
111 // Plain text before the text is set: it can quote the store's recipient
112 // list, which as rich text could make Qt load a file (<img src=...>).
113 auto *banner = new QLabel(this);
114 banner->setTextFormat(Qt::PlainText);
115 // And with nothing in it that changes how the rest reads: a folder name
116 // with a bidi override mirrored the warning after it.
117 banner->setText(Util::displayable(text));
118 banner->setObjectName(name);
119 banner->setWordWrap(true);
120 // Palette, not a stylesheet colour, so it reads on dark themes too; red as
121 // ProcessOutputPanel paints error lines.
122 QFont bold = banner->font();
123 bold.setBold(true);
124 banner->setFont(bold);
125 QPalette palette = banner->palette();
126 palette.setColor(QPalette::WindowText, QColor(Qt::red));
127 banner->setPalette(palette);
128 banner->setContentsMargins(4, 4, 4, 4);
129 // In a scroll area of a few lines: the text quotes folder paths a
130 // co-writer chose, and a word-wrapped label is as wide as its longest
131 // run without a space and as tall as its lines. Unscrolled it sized the
132 // dialog to tens of thousands of pixels; a scroll area asks for at most
133 // a bounded size, and all of the text can still be read.
134 auto *area = new QScrollArea(this);
135 area->setWidget(banner);
136 area->setWidgetResizable(true);
137 area->setFrameShape(QFrame::NoFrame);
138 area->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
139 area->setMaximumHeight(banner->fontMetrics().lineSpacing() * 8 + 8);
140 ui->verticalLayout->insertWidget(1, area);
141}
142
144 // The walk re-encryption takes: hidden folders and links are not entered.
145 const QString dir = QDir::cleanPath(m_dir);
146 if (!QFileInfo(dir).isDir()) {
147 return;
148 }
149 QStringList unlisted;
150 const QStringList lists = Util::regularFilesUnder(
151 dir, {QStringLiteral(".gpg-id")}, nullptr, true, &unlisted);
152 const auto relative = [&dir](const QString &folder) {
153 return QDir::toNativeSeparators(QDir(dir).relativeFilePath(folder));
154 };
155 QStringList nested;
156 for (const QString &list : lists) {
157 const QString folder = QFileInfo(list).path();
158 if (QDir::cleanPath(folder) != dir) {
159 nested << relative(folder);
160 }
161 }
162 QStringList unread;
163 for (const QString &folder : std::as_const(unlisted)) {
164 unread << relative(folder);
165 }
166 constexpr qsizetype kMaxNamed = 5;
167 const auto named = [](const QStringList &folders) {
168 QString names = folders.mid(0, kMaxNamed).join(QStringLiteral(", "));
169 if (folders.size() > kMaxNamed) {
170 names += QStringLiteral(", …");
171 }
172 return names;
173 };
174 QStringList text;
175 if (!nested.isEmpty()) {
176 //: %1 lists folders, such as "work, work/bank". Shown when changing the
177 //: recipients of a folder that has folders with their own list below it.
178 text << tr("%n folder(s) below this one have their own recipients, which "
179 "saving here does not change: %1",
180 nullptr, static_cast<int>(nested.size()))
181 .arg(named(nested));
182 }
183 if (!unread.isEmpty()) {
184 //: %1 lists folders, such as "work, work/bank", that QtPass could not
185 //: read: no permission, or a name in them that is not valid UTF-8.
186 text << tr("%n folder(s) below this one could not be read, so whether "
187 "they have their own recipients is unknown: %1",
188 nullptr, static_cast<int>(unread.size()))
189 .arg(named(unread));
190 }
191 if (!text.isEmpty()) {
192 showRecipientWarning(text.join(QLatin1Char('\n')),
193 QStringLiteral("nestedListsWarning"));
194 }
195}
196
197namespace {
198
200auto normalisedKeyId(const QString &id) -> QString {
201 const QString trimmed = id.trimmed();
202 return (trimmed.startsWith(QLatin1String("0x"), Qt::CaseInsensitive)
203 ? trimmed.mid(2)
204 : trimmed)
205 .toUpper();
206}
207
211auto keyIdsMatch(const QString &first, const QString &second) -> bool {
212 static const QRegularExpression hexId(QStringLiteral("^[0-9A-F]{8,}$"));
213 const QString a = normalisedKeyId(first);
214 const QString b = normalisedKeyId(second);
215 if (!hexId.match(a).hasMatch() || !hexId.match(b).hasMatch()) {
216 return false;
217 }
218 if (a.size() == 64) {
219 return b == a || (b.size() == 16 && a.startsWith(b)) ||
220 (b.size() == 8 && a.mid(8, 8) == b);
221 }
222 if (b.size() == 64) {
223 return a == b || (a.size() == 16 && b.startsWith(a)) ||
224 (a.size() == 8 && b.mid(8, 8) == a);
225 }
226 return a.endsWith(b) || b.endsWith(a);
227}
228
232auto keyIdOfLine(const QString &recipient) -> QString {
233 static const QRegularExpression hexLine(
234 QStringLiteral("^(?:0[xX])?([0-9A-Fa-f]+)!?$"));
235 const QRegularExpressionMatch match = hexLine.match(recipient.trimmed());
236 if (!match.hasMatch()) {
237 return {};
238 }
239 const QString digits = match.captured(1);
240 const qsizetype size = digits.size();
241 return size == 8 || size == 16 || size == 40 || size == 64 ? digits
242 : QString();
243}
244
248auto nameTermOfLine(const QString &recipient) -> QString {
249 const QString line = recipient.trimmed();
250 if (line.isEmpty()) {
251 return {};
252 }
253 // A leading 0x, digits only, or groups of four digits split by spaces (a
254 // fingerprint as gpg prints it) is a key ID gpg reads in its own way
255 // (keyIdOfLine() takes the lengths it accepts); ".", "+", "#", "&", "^",
256 // "/", "[" and ":" start search modes this dialog does not model.
257 static const QRegularExpression hexish(QStringLiteral(
258 "^(?:0[xX]|[0-9A-Fa-f]+!?$|[0-9A-Fa-f]{4}(?:\\s+[0-9A-Fa-f]{4})+!?$)"));
259 if (hexish.match(line).hasMatch() ||
260 QStringLiteral(".+#&^/[:!\\").contains(line.front())) {
261 return {};
262 }
263 QString term = line;
264 if (term.startsWith(u'<')) {
265 if (!term.endsWith(u'>')) {
266 return {};
267 }
268 term = term.mid(1, term.size() - 2);
269 } else if (term.startsWith(u'=') || term.startsWith(u'@') ||
270 term.startsWith(u'*')) {
271 term.remove(0, 1);
272 }
273 return term;
274}
275
282auto judgedLocally(const QString &recipient) -> bool {
283 return !keyIdOfLine(recipient).isEmpty() ||
284 !nameTermOfLine(recipient).isEmpty();
285}
286
294auto answersTo(const UserInfo &key, const QString &recipient) -> bool {
295 const QString keyId = keyIdOfLine(recipient);
296 if (!keyId.isEmpty()) {
297 return keyIdsMatch(key.key_id, keyId) ||
298 std::any_of(key.subkeys.cbegin(), key.subkeys.cend(),
299 [&keyId](const QString &subkey) {
300 return keyIdsMatch(subkey, keyId);
301 });
302 }
303 const QString term = nameTermOfLine(recipient);
304 if (term.isEmpty()) {
305 return false;
306 }
307 const auto holds = [&term](const QString &uid) {
308 return uid.contains(term, Qt::CaseInsensitive);
309 };
310 return holds(key.name) ||
311 std::any_of(key.uids.cbegin(), key.uids.cend(), holds);
312}
313
316auto uniqueLines(const QStringList &listed) -> QStringList {
317 QStringList lines;
318 QSet<QString> seen;
319 for (const QString &line : listed) {
320 if (!seen.contains(line)) {
321 seen.insert(line);
322 lines.append(line);
323 }
324 }
325 return lines;
326}
327
328} // namespace
329
330void UsersDialog::selectRecipients(const QStringList &listed) {
331 QStringList recipients = uniqueLines(listed);
332
333 // OK saves what is ticked, so the ticks are the keys gpg's -r reaches for
334 // the list, found by a throwaway encryption. A keyring search would also
335 // find keys that only resemble a recipient: a user ID containing its
336 // address, a subkey bound to its key, which whoever made the key decides.
337 // Every reached key must have a row, or OK would drop it.
338 if (!setAsideHeldTwice(&recipients)) {
339 return;
340 }
341 const std::optional<QStringList> reached =
342 m_pass->encryptionReaches(recipients);
343 if (reached && !reached->isEmpty() && tickReached(*reached, recipients)) {
344 return;
345 }
346 // gpg refused the list as a whole: one line it cannot encrypt to (a
347 // key gone, expired or revoked), as in a list edited after someone
348 // left. Each line on its own, so the others still tick only what they
349 // reach, and a line gpg cannot encrypt to is kept as written. Address
350 // and name lines first, where look-alike keys come from: a key ID or
351 // fingerprint reaches the same key by probe or search. A line past the
352 // few probed is kept as written too, so OK writes it back and adds no
353 // key; only a line whose probe names no one goes to the search below.
354 if (!reached && !probeEachLine(&recipients)) {
355 return;
356 }
357 // What a probe could not settle: gpg encrypted but did not say whom, or
358 // reached a key without a row. The keyring search below, as before.
359 searchKeyring(recipients);
360}
361
362void UsersDialog::keepAsWritten(const QString &line, const QString &why) {
363 UserInfo kept;
364 kept.key_id = line;
365 kept.enabled = true;
366 kept.name = " ?? " + why;
367 m_userList.append(kept);
368}
369
370// Ticks the rows @p ids (what a probe of @p lines reached) belong to;
371// false, ticking nothing, when one has no row. A long key ID is a line
372// answersTo() judges as gpg does: the key's or one of its subkeys'. An
373// ID on more than one row is a subkey bound to several keys, where the
374// probe cannot tell which key gpg chose: only a line naming a reached
375// key's own primary key ticks its row, and any other line is kept as
376// written, so OK neither adds the key that shares the subkey nor drops
377// the recipient the line meant. Ticks are only added: after a key import
378// the rows ticked before stay.
379auto UsersDialog::tickReached(const QStringList &ids, const QStringList &lines)
380 -> bool {
381 bool shared = false;
382 QSet<int> reachedRows;
383 for (const QString &id : ids) {
384 QList<int> rows;
385 for (int row = 0; row < m_userList.size(); ++row) {
386 if (answersTo(m_userList.at(row), id)) {
387 rows << row;
388 }
389 }
390 if (rows.isEmpty()) {
391 return false;
392 }
393 shared = shared || rows.size() > 1;
394 for (const int row : std::as_const(rows)) {
395 reachedRows.insert(row);
396 }
397 }
398 if (!shared) {
399 for (const int row : std::as_const(reachedRows)) {
400 m_userList[row].enabled = true;
401 }
402 return true;
403 }
404 for (const QString &line : lines) {
405 const QString keyId = keyIdOfLine(line);
406 bool ticked = false;
407 if (!keyId.isEmpty()) {
408 for (const int row : std::as_const(reachedRows)) {
409 if (keyIdsMatch(m_userList.at(row).key_id, keyId)) {
410 m_userList[row].enabled = true;
411 ticked = true;
412 }
413 }
414 }
415 if (!ticked) {
416 keepAsWritten(line, tr("Matches more than one key; kept as written"));
417 }
418 }
419 return true;
420}
421
422// A key ID or fingerprint that two key blocks hold (someone bound another
423// person's key to their own as a subkey) may encrypt to either: kept as
424// written and named, and not looked up, which would tick the other key.
425// A keyring that cannot be listed leaves every line untold: all kept as
426// written, nothing probed.
427auto UsersDialog::setAsideHeldTwice(QStringList *recipients) -> bool {
428 if (const std::optional<QHash<QString, QStringList>> held =
429 m_pass->keyLinesHeldTwice(*recipients);
430 !held || !held->isEmpty()) {
432 QStringLiteral("heldTwiceWarning"));
433 QStringList rest;
434 for (const QString &line : std::as_const(*recipients)) {
435 if (!held) {
436 keepAsWritten(line, tr("Keys could not be checked; kept as written"));
437 } else if (held->contains(line)) {
438 keepAsWritten(line, tr("Held by more than one key; kept as written"));
439 } else {
440 rest << line;
441 }
442 }
443 if (rest.isEmpty()) {
444 return false;
445 }
446 *recipients = std::move(rest);
447 }
448 return true;
449}
450
451auto UsersDialog::probeEachLine(QStringList *recipients) -> bool {
452 QStringList order;
453 std::copy_if(recipients->cbegin(), recipients->cend(),
454 std::back_inserter(order),
455 [](const QString &line) { return keyIdOfLine(line).isEmpty(); });
456 std::copy_if(
457 recipients->cbegin(), recipients->cend(), std::back_inserter(order),
458 [](const QString &line) { return !keyIdOfLine(line).isEmpty(); });
459 constexpr int kMaxLineProbes = 10;
460 QStringList unsure;
461 int probes = 0;
462 for (const QString &line : std::as_const(order)) {
463 if (probes++ >= kMaxLineProbes) {
464 keepAsWritten(line, tr("Not checked; kept as written"));
465 continue;
466 }
467 // A one-line list: the probe that failed was this line's own.
468 const std::optional<QStringList> one =
469 recipients->size() == 1 ? std::nullopt
470 : m_pass->encryptionReaches({line});
471 if (!one) {
472 keepAsWritten(line, tr("Key not found in keyring, or not usable"));
473 } else if (one->isEmpty() || !tickReached(*one, {line})) {
474 unsure << line;
475 }
476 }
477 if (unsure.isEmpty()) {
478 return false;
479 }
480 *recipients = std::move(unsure);
481 return true;
482}
483
484void UsersDialog::searchKeyring(const QStringList &recipients) {
485 // One gpg call resolves every recipient, by key ID or by email/UID.
486 QList<UserInfo> resolved = m_pass->listKeys(recipients);
487 if (resolved.isEmpty() && recipients.size() > 1) {
488 // One line gpg cannot read as a key search ("0x", a fingerprint one
489 // digit short) aborts that whole call with exit code 2, so nothing is
490 // listed for the other lines, whose keys are in the keyring all the same.
491 // Every form judgedLocally() accepts gpg reads, so ask again for those;
492 // the rest get a call of their own below.
493 QStringList readable;
494 std::copy_if(recipients.cbegin(), recipients.cend(),
495 std::back_inserter(readable), judgedLocally);
496 if (!readable.isEmpty() && readable.size() < recipients.size()) {
497 resolved = m_pass->listKeys(std::move(readable));
498 }
499 }
500
501 // A line answersTo() cannot judge gets gpg's own verdict, one blocking
502 // call each on the dialog's way up. Only unusual forms need it, so a few
503 // are asked; past that a line is listed unticked as not looked up, so it
504 // does not stay in the list unseen (a member could otherwise hide behind
505 // it a key the user unticks).
506 constexpr int kMaxLookups = 10;
507 int lookups = 0;
508 QHash<QString, bool> perLineHasKey;
509 QSet<QString> notLookedUp;
510 for (const QString &recipient : std::as_const(recipients)) {
511 if (judgedLocally(recipient)) {
512 continue;
513 }
514 if (lookups++ >= kMaxLookups) {
515 notLookedUp.insert(recipient);
516 continue;
517 }
518 const QList<UserInfo> keys = m_pass->listKeys(recipient);
519 perLineHasKey.insert(recipient, !keys.isEmpty());
520 resolved += keys;
521 }
522
523 for (UserInfo &user : m_userList) {
524 if (std::any_of(resolved.cbegin(), resolved.cend(),
525 [&user](const UserInfo &key) {
526 return key.key_id == user.key_id;
527 })) {
528 user.enabled = true;
529 }
530 }
531 // Only what gpg itself cannot find is reported missing. A per-line answer
532 // is gpg's own verdict for that line and decides it outright; that also
533 // keeps a genuinely unreadable line ("0x") reported missing. Any other
534 // line is missing when no key gpg resolved answers to it: the full listing
535 // carries every user ID and subkey, so nothing is left for gpg to add.
536 for (const QString &recipient : std::as_const(recipients)) {
537 UserInfo missing;
538 missing.key_id = recipient;
539 if (notLookedUp.contains(recipient)) {
540 missing.name = " ?? " + tr("Not looked up in keyring");
541 m_notLookedUp.insert(recipient);
542 m_userList.append(missing);
543 continue;
544 }
545 const auto cached = perLineHasKey.constFind(recipient);
546 const bool found = cached != perLineHasKey.constEnd()
547 ? cached.value()
548 : std::any_of(resolved.cbegin(), resolved.cend(),
549 [&recipient](const UserInfo &key) {
550 return answersTo(key, recipient);
551 });
552 if (!found) {
553 missing.enabled = true;
554 missing.name = " ?? " + tr("Key not found in keyring");
555 m_userList.append(missing);
556 }
557 }
558}
559
561 // A store that had no list when it was chosen (a new profile): a list
562 // that appeared since is nobody's choice, and was read under the active
563 // backend's signing policy, not the new profile's.
565 return;
566 }
567 // Through the backend: with a signing key only a verified list may be
568 // preselected, since OK signs whatever is selected.
569 const Pass::RecipientsForEditing loaded =
571 m_listRead = true;
572 m_readState = static_cast<int>(loaded.state);
574 if (!loaded.warning.isEmpty()) {
576 }
577 // A folder without .gpg-id (new store, new profile) has no recipients yet;
578 // listKeys() with no filter would return the whole keyring, preselected.
580 !loaded.recipients.isEmpty()) {
582 }
583}
584
585UsersDialog::~UsersDialog() = default;
586
590 return static_cast<int>(now.state) != m_readState ||
592}
593
595 if (!hasSelection()) {
596 // Nothing to encrypt to: an empty .gpg-id would make every insert fail
597 // and the wizard never offers this dialog again once the file exists.
598 return;
599 }
600 // OK writes the whole selection, ticked from the list as it was read. A
601 // newer list that arrived meanwhile (a pull the watchdog let run on under
602 // the dialog, a sync) would be overwritten by the old one plus the user's
603 // change: someone just removed came back, signed as the next generation.
605 QMessageBox::warning(
606 this, tr("Recipients not changed"),
607 tr("The recipient list of this folder changed while this dialog was "
608 "open, for example through an update from Git. OK would have "
609 "written the old list back. Close this dialog and open it again "
610 "to see the new list."));
611 return;
612 }
613 if (m_initOnAccept) {
614 // The pass backend re-encrypts every entry itself: asked first when one
615 // would gain a reader it does not have.
618 })) {
619 return;
620 }
621 if (m_listRead) {
622 // Compared again by the backend at the last point before it writes:
623 // a pull in a terminal can still land between here and there.
627 // Refused there (changed after all, or another operation runs): the
628 // dialog stays open with the selection, as the message asks to save
629 // again.
631 read)) {
632 return;
633 }
634 } else {
636 }
637 }
638
639 QDialog::accept();
640}
641
642auto UsersDialog::hasSelection() const -> bool {
643 return std::any_of(m_userList.cbegin(), m_userList.cend(),
644 [](const UserInfo &user) { return user.enabled; });
645}
646
648 if (auto *ok = ui->buttonBox->button(QDialogButtonBox::Ok)) {
649 ok->setEnabled(hasSelection());
650 }
651}
652
653void UsersDialog::keyPressEvent(QKeyEvent *event) {
654 switch (event->key()) {
655 case Qt::Key_Escape:
656 ui->lineEdit->clear();
657 break;
658 default:
659 break;
660 }
661}
662
663void UsersDialog::itemChange(QListWidgetItem *item) {
664 if (!item) {
665 return;
666 }
667 bool ok = false;
668 const int index = item->data(Qt::UserRole).toInt(&ok);
669 if (!ok) {
670 qCWarning(lcQtPass)
671 << "UsersDialog::itemChange: invalid user index data for item";
672 return;
673 }
674 if (index < 0 || index >= m_userList.size()) {
675 qCWarning(lcQtPass) << "UsersDialog::itemChange: user index out of range:"
676 << index << "valid range is [0,"
677 << (m_userList.size() - 1) << "]";
678 return;
679 }
680 m_userList[index].enabled = item->checkState() == Qt::Checked;
682}
683
684void UsersDialog::populateList(const QString &filter) {
685 // Invalidate cached datetime so expiry checks use fresh current time
686 m_cachedDateTimeValid = false;
687
688 QString patternString = "*" + filter + "*";
689 if (m_cachedPatternString != patternString) {
690 // A user ID is not a path: "*" and "?" must match a "/" as well, or a
691 // key named "ACME A/S" or "(dev/ops)" drops out of the search and stays
692 // ticked unseen while the listed rows are unticked.
693 QRegularExpression re(
694 QRegularExpression::wildcardToRegularExpression(
695 patternString, QRegularExpression::NonPathWildcardConversion),
696 QRegularExpression::CaseInsensitiveOption);
697 if (re.isValid()) {
699 m_cachedPatternString = std::move(patternString);
700 }
701 }
702 const QRegularExpression &nameFilter = m_cachedNameFilter;
703 // Sorted once at the end: with sorting on, each badge and tick below
704 // re-sorted every row added so far, and a .gpg-id of thousands of
705 // unknown recipients kept the dialog from opening for minutes.
706 ui->listWidget->setSortingEnabled(false);
707 ui->listWidget->clear();
708
709 for (int i = 0; i < m_userList.size(); ++i) {
710 const auto &user = m_userList.at(i);
711 if (!passesFilter(user, filter, nameFilter)) {
712 continue;
713 }
714
715 // Built outside the list and added whole: an item made with the list as
716 // its parent is in it at once, and each setter below then reports a
717 // change for a row that has no user index yet.
718 auto *item = new QListWidgetItem(buildUserText(user));
719 applyUserStyling(item, user);
720 item->setCheckState(user.enabled ? Qt::Checked : Qt::Unchecked);
721 item->setData(Qt::UserRole, QVariant::fromValue(i));
722 ui->listWidget->addItem(item);
723 }
724 // setSortingEnabled() only sets the flag; sortItems() sorts.
725 ui->listWidget->sortItems();
726 ui->listWidget->setSortingEnabled(true);
728}
729
730bool UsersDialog::passesFilter(const UserInfo &user, const QString &filter,
731 const QRegularExpression &nameFilter) const {
732 if (!filter.isEmpty() && !nameFilter.match(user.name).hasMatch()) {
733 return false;
734 }
735 // A ticked key is one the folder is encrypted to: it is shown whatever
736 // its state, or an expired or missing recipient stays in .gpg-id unseen and
737 // cannot be unticked. "Show unusable keys" is about keys to add. A line
738 // listed unticked without a lookup is shown too: OK would drop it unseen.
739 if (user.enabled || ui->checkBox->isChecked() ||
740 m_notLookedUp.contains(user.key_id)) {
741 return true;
742 }
743 return user.isValid() && !isUserExpired(user);
744}
745
746auto UsersDialog::isUserExpired(const UserInfo &user) const -> bool {
748 m_cachedCurrentDateTime = QDateTime::currentDateTime();
750 }
751 // gpg marks a key it already judged expired with validity 'e'.
752 return user.validity == 'e' ||
753 (user.expiry.isValid() && m_cachedCurrentDateTime > user.expiry);
754}
755
756namespace {
768auto shortened(const QString &text) -> QString {
769 constexpr qsizetype kMaxShown = 256;
770 if (text.size() <= kMaxShown) {
771 return text;
772 }
773 qsizetype cut = kMaxShown;
774 if (text.at(cut - 1).isHighSurrogate()) {
775 --cut;
776 }
777 return text.left(cut) + QChar(0x2026);
778}
779} // namespace
780
781QString UsersDialog::buildUserText(const UserInfo &user) const {
782 // One line for the user ID: a line separator in it (gpg escapes only
783 // ASCII) drew a line that looked like the key's fingerprint.
784 // The key ID too: a recipient no key answers to is the .gpg-id line as
785 // written, which may hold the same separators.
786 QString text = Util::displayable(shortened(user.name), false) + "\n" +
787 Util::displayable(shortened(user.key_id), false);
788 if (user.created.isValid()) {
789 text += " " + tr("created") + " " +
790 QLocale::system().toString(user.created, QLocale::ShortFormat);
791 }
792 if (user.expiry.isValid()) {
793 text += " " + tr("expires") + " " +
794 QLocale::system().toString(user.expiry, QLocale::ShortFormat);
795 }
796 return text;
797}
798
799void UsersDialog::applyUserStyling(QListWidgetItem *item,
800 const UserInfo &user) const {
801 const QString originalText = item->text();
802 // Status badge first: an own key can be expired too, and then the marker
803 // matters more than the "you can decrypt with this" colour.
804 bool badged = true;
805 // Expired before invalid: gpg gives an expired key validity 'e', which is
806 // not a valid one, and "expired" says what to do about it.
807 if (isUserExpired(user)) {
808 // A lone dark-red foreground is unreadable on dark themes, and gpg
809 // refuses to encrypt to expired keys anyway.
810 item->setBackground(Qt::darkRed);
811 item->setForeground(Qt::white);
812 item->setText(tr("[EXPIRED] ") + originalText);
813 } else if (!user.isValid()) {
814 item->setBackground(Qt::darkRed);
815 item->setForeground(Qt::white);
816 item->setText(tr("[INVALID] ") + originalText);
817 } else if (!user.fullyValid()) {
818 item->setBackground(Qt::darkYellow);
819 item->setForeground(Qt::white);
820 item->setText(tr("[PARTIAL] ") + originalText);
821 } else {
822 item->setText(originalText);
823 badged = false;
824 }
825 if (user.have_secret) {
826 if (!badged) {
827 item->setForeground(QApplication::palette().color(QPalette::Link));
828 }
829 QFont font = item->font();
830 font.setBold(true);
831 item->setFont(font);
832 }
833}
834
835void UsersDialog::on_lineEdit_textChanged(const QString &filter) {
836 populateList(filter);
837}
838
840
841void UsersDialog::selectImportedKey(const QString &importedKey) {
842 // The stored key_id, not the item text.
843 for (int i = 0; i < ui->listWidget->count(); ++i) {
844 QListWidgetItem *item = ui->listWidget->item(i);
845 bool ok = false;
846 const int idx = item != nullptr ? item->data(Qt::UserRole).toInt(&ok) : -1;
847 if (ok && idx >= 0 && idx < m_userList.size() &&
848 !m_userList[idx].key_id.isEmpty() &&
849 keyIdsMatch(m_userList[idx].key_id, importedKey)) {
850 ui->listWidget->setCurrentItem(item);
851 return;
852 }
853 }
854}
855
857 ImportKeyDialog dialog(m_gpgExe, this);
858 if (dialog.exec() != QDialog::Accepted) {
859 return;
860 }
861
862 // Non-empty after Accepted, but an empty id would make the endsWith()
863 // below match the first listed key.
864 const QString importedKey = dialog.importedKeyId();
865 if (importedKey.isEmpty()) {
866 return;
867 }
868
869 // loadGpgKeys() rebuilds the key list from the keyring and drops every tick.
870 // Remember which recipients were selected (the .gpg-id list and the user's
871 // own ticks, including any "key not found" rows) and re-apply them after, so
872 // importing a key does not silently remove the other recipients.
873 QStringList selected;
874 for (const UserInfo &user : std::as_const(m_userList)) {
875 if (user.enabled) {
876 selected.append(user.key_id);
877 }
878 }
879
880 if (!loadGpgKeys()) {
881 return;
882 }
883
884 // Re-apply the remembered selection. Most saved identifiers are a key ID that
885 // is in the rebuilt list, so match those exactly first (no gpg lookup). An
886 // identifier that does not match a row is one that was listed as "key not
887 // found" - a short ID or email that gpg could not resolve, or whose key has
888 // just been imported and now shows under its fingerprint. Hand those to
889 // selectRecipients(), which resolves each against the refreshed keyring,
890 // ticks the matching row, and re-adds a "key not found" row for any that
891 // still does not resolve.
892 QStringList unresolved;
893 for (const QString &keyId : std::as_const(selected)) {
894 bool matched = false;
895 for (UserInfo &user : m_userList) {
896 if (user.key_id == keyId) {
897 user.enabled = true;
898 matched = true;
899 }
900 }
901 if (!matched) {
902 unresolved.append(keyId);
903 }
904 }
905 if (!unresolved.isEmpty()) {
906 selectRecipients(unresolved);
907 }
908
909 // Clear the filter so the just-imported key is visible. setText("") still
910 // emits textChanged once, so don't double-populate.
911 {
912 const QSignalBlocker blocker(ui->lineEdit);
913 ui->lineEdit->clear();
914 }
915 populateList(QString());
916
917 selectImportedKey(importedKey);
918}
Dialog for importing GPG keys from file or clipboard.
auto importedKeyId() const -> QString
Get the imported key id on success.
Abstract base class for password store operations.
Definition pass.h:77
virtual auto encryptionReaches(const QStringList &recipients) -> std::optional< QStringList >
The keys a gpg encryption to recipients reaches: a throwaway encryption outside the store,...
Definition pass.cpp:707
auto initIfUnchanged(const QString &path, const QList< UserInfo > &users, const QString &dir, const QString &passStore, const RecipientsForEditing &read) -> bool
Init(), but only while the list of dir still reads as the caller read it with recipientsForEditing().
Definition pass.cpp:1442
static auto describeKeyLinesHeldTwice(const std::optional< QHash< QString, QStringList > > &held) -> QString
A message naming each line keyLinesHeldTwice() found and what the user can do about it.
Definition pass.cpp:643
virtual auto entriesInitWouldWiden(const QString &dir, const QList< UserInfo > &users) -> QStringList
Entries a pass init of dir with users would hand to someone who cannot read them now (an entry copied...
Definition pass.h:296
auto listKeys(QStringList keystrings, bool secret=false) -> QList< UserInfo >
List GPG keys matching patterns.
Definition pass.cpp:763
auto recipientsForEditing(const QString &dir, const QString &passStore) -> RecipientsForEditing
The recipients a dialog may preselect for editing the list of dir.
Definition pass.cpp:1745
virtual void Init(QString path, const QList< UserInfo > &users)=0
Initialize new password store.
QString m_cachedPatternString
~UsersDialog() override
Destroys the dialog and its generated form.
void updateOkButton()
Enable OK only while at least one key is ticked (hasSelection()).
bool m_initOnAccept
void itemChange(QListWidgetItem *item)
Handle user selection change.
QRegularExpression m_cachedNameFilter
void on_importKeyButton_clicked()
Import a GPG key and refresh the list.
void on_lineEdit_textChanged(const QString &filter)
Filter user list.
auto isUserExpired(const UserInfo &user) const -> bool
Check if GPG key is expired.
void keyPressEvent(QKeyEvent *event) override
Handle key press.
void showRecipientWarning(const QString &text, const QString &name=QStringLiteral("recipientWarning"))
Show text above the key list in bold red, for a recipient list that could not be verified.
void selectRecipients(const QStringList &listed)
Tick the keys the folder is encrypted to, and list recipients no key in the keyring answers to,...
void applyUserStyling(QListWidgetItem *item, const UserInfo &user) const
Apply visual styling to user item.
void searchKeyring(const QStringList &recipients)
Tick the keys a keyring search resolves recipients to, and list the lines no key answers to,...
QString m_dir
Preselect
Whether the recipients on disk are ticked when it opens.
Definition usersdialog.h:41
@ Nothing
None: for a store that had no list when it was chosen.
Definition usersdialog.h:43
auto tickReached(const QStringList &ids, const QStringList &lines) -> bool
Tick the rows of the keys ids, which a probe of lines reached. A key on more than one row (a shared s...
void keepAsWritten(const QString &line, const QString &why)
List line as a ticked row of its own, named by why, so OK writes it back as it was.
QList< UserInfo > m_userList
void connectSignals()
Connect dialog signals.
auto setAsideHeldTwice(QStringList *recipients) -> bool
Keep as written, and warn about, the lines a key ID or fingerprint names that two key blocks hold,...
QString m_passStore
QDateTime m_cachedCurrentDateTime
void restoreDialogState()
auto listChangedSinceRead() const -> bool
Whether the folder's recipient list reads differently now from when loadRecipients() read it: a pull,...
QString buildUserText(const UserInfo &user) const
Build display text for user: the user ID and key ID on a line each, each cut to 256 characters (the r...
QStringList m_readRecipients
The recipients the list named when the dialog read it.
void populateList(const QString &filter=QString())
Populate user list.
void selectImportedKey(const QString &importedKey)
Make the key gpg just imported the current row. gpg reports a 16-character long ID (IMPORTED) or a 40...
void showNestedLists()
Name the folders below this one that have a recipient list of their own: saving here does not change ...
void loadRecipients()
Load recipients and handle missing keys.
void accept() override
Handle dialog acceptance.
bool m_cachedDateTimeValid
QString m_gpgExe
UsersDialog(Pass *pass, const AppSettings &s, QString dir, QWidget *parent=nullptr)
Construct users dialog.
void markSecretKeys(QList< UserInfo > &users)
Mark which keys have secret counterparts.
Preselect m_preselect
auto probeEachLine(QStringList *recipients) -> bool
After gpg refused the list as a whole, probe each line on its own (address and name lines first,...
QSet< QString > m_notLookedUp
.gpg-id lines selectRecipients() listed unticked without asking gpg. They are shown without "Show unu...
bool passesFilter(const UserInfo &user, const QString &filter, const QRegularExpression &nameFilter) const
Check if user passes filter.
auto hasSelection() const -> bool
Whether at least one key is ticked.
void on_checkBox_clicked()
Handle select all checkbox.
QScopedPointer< Ui::UsersDialog > ui
The widgets from usersdialog.ui.
auto loadGpgKeys() -> bool
Load GPG keys and determine secret key status.
Pass * m_pass
static auto regularFilesUnder(const QString &dir, const QStringList &nameFilters, QStringList *skipped=nullptr, bool hiddenFiles=false, QStringList *unlisted=nullptr) -> QStringList
Regular files under dir whose name matches one of nameFilters, found by walking only real directories...
Definition util.cpp:1149
static auto displayable(const QString &text, bool lineBreaks=true) -> QString
text with the characters that change how the text around them reads replaced by U+FFFD,...
Definition util.cpp:898
Dialog that imports an ASCII-armored GPG public key from a file or the clipboard by running gpg --imp...
auto confirmPassRun(QWidget *parent, const QString &store, const std::function< QStringList()> &check) -> bool
Run check (which lists the entries a pass run would give new readers, one gpg call each) under a wait...
void attach(QDialog &dialog, const QString &key)
restore() now, save() whenever the dialog finishes.
Pass, the abstract password-store backend that RealPass and ImitatePass implement,...
QMessageBox helpers that force Qt::PlainText so store-controlled names can never be read as rich-text...
The "qtpass" logging category.
QtPassSettings, the QSettings singleton behind every saved setting, the profiles and the Pass backend...
Plain value-object holding all flat QtPass configuration.
Definition appsettings.h:36
What a dialog may do with the list of a folder (recipientsForEditing()).
Definition pass.h:604
QStringList recipients
The recipients to preselect; empty when Rejected.
Definition pass.h:627
State state
How the list on disk stood up.
Definition pass.h:625
QString warning
What the dialog should show, if anything.
Definition pass.h:629
State
How the list on disk stood up.
Definition pass.h:606
@ Rejected
Not to be used: signature invalid, written for another folder or for no folder in particular while a ...
Definition pass.h:622
Stores GPG key info including validity, creation date, and more.
Definition userinfo.h:20
bool have_secret
Whether secret key is available (can decrypt with this key).
Definition userinfo.h:72
bool enabled
Whether this user/key is enabled for normal use.
Definition userinfo.h:76
QString key_id
Hexadecimal representation of the GnuPG key identifier.
Definition userinfo.h:53
auto fullyValid() const -> bool
Check full validity per GnuPG validity codes.
Definition userinfo.h:31
auto isValid() const -> bool
Check whether the key has any usable validity level.
Definition userinfo.h:44
QDateTime created
Date/time when key was created.
Definition userinfo.h:84
QString name
GPG user ID / full name.
Definition userinfo.h:49
QDateTime expiry
Date/time when key expires.
Definition userinfo.h:80
UsersDialog, the recipient picker for a folder's .gpg-id.
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...
WindowStateStore: saves and restores top-level window geometry through QtPassSettings,...