• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

IJHack / QtPass / 46856794352

02 Dec 2026 10:00AM UTC coverage: 94.576% (-0.02%) from 94.593%
46856794352

push

github

web-flow
Users dialog: no warning for each badged row while the list fills (#2465)

populateList() made each row with the list as its parent, so the row was in the list before it had its user index. Each setter after that (the badge colours and text, the tick) reported a change, and itemChange() warned "invalid user index data for item" once per change. One run of the tests printed that line 79 times, and a user with an expired or unknown recipient got it on stderr each time the list was filled.

The row is now built outside the list and added once it is whole.

Refs #2446

Signed-off-by: Anne Jan Brouwer <brouwer@annejan.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

1 of 1 new or added line in 1 file covered. (100.0%)

3 existing lines in 1 file now uncovered.

11509 of 12169 relevant lines covered (94.58%)

23815.54 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.5
/src/usersdialog.cpp
1
// SPDX-FileCopyrightText: 2015 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
/**
4
 * @file
5
 * @brief Implements UsersDialog; selectRecipients() matches the `.gpg-id`
6
 * lines against the keyring and lists the ones no key answers to.
7
 */
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"
40
UsersDialog::UsersDialog(Pass *pass, const AppSettings &s, QString dir,
67 ✔
41
                         QWidget *parent)
67 ✔
42
    : UsersDialog(pass, s, std::move(dir), Preselect::FromList, parent) {}
134 ✔
43

44
UsersDialog::UsersDialog(Pass *pass, const AppSettings &s, QString dir,
71 ✔
45
                         Preselect preselect, QWidget *parent)
71 ✔
46
    : QDialog(parent), ui(new Ui::UsersDialog), m_pass(pass),
71 ✔
47
      m_passStore(s.passStore), m_gpgExe(s.gpgExecutable),
48
      m_dir(std::move(dir)), m_preselect(preselect) {
142 ✔
49
  Q_ASSERT(pass);
50
  ui->setupUi(this);
71 ✔
51

52
  restoreDialogState();
71 ✔
53
  if (!loadGpgKeys()) {
71 ✔
54
    connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
1 ✔
55
    return;
1 ✔
56
  }
57

58
  loadRecipients();
70 ✔
59
  showNestedLists();
70 ✔
60
  populateList();
70 ✔
61

62
  connectSignals();
70 ✔
63
}
×
64

65
void UsersDialog::connectSignals() {
70 ✔
66
  connect(ui->buttonBox, &QDialogButtonBox::accepted, this,
70 ✔
67
          &UsersDialog::accept);
70 ✔
68
  connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
70 ✔
69
  connect(ui->listWidget, &QListWidget::itemChanged, this,
70 ✔
70
          &UsersDialog::itemChange);
140 ✔
71
  // importKeyButton is wired via Qt's automatic on_<name>_<signal> mechanism
72
  // already triggered by setupUi().
73

74
  ui->lineEdit->setClearButtonEnabled(true);
70 ✔
75
}
70 ✔
76

77
void UsersDialog::restoreDialogState() {
71 ✔
78
  WindowStateStore::attach(*this, QStringLiteral("usersDialog"));
142 ✔
79
}
71 ✔
80

81
auto UsersDialog::loadGpgKeys() -> bool {
73 ✔
82
  QList<UserInfo> users = m_pass->listKeys();
73 ✔
83
  if (users.isEmpty()) {
73 ✔
84
    QMessageBox::critical(parentWidget(), tr("Keylist missing"),
3 ✔
85
                          tr("Could not fetch list of available GPG keys"));
×
86
    reject();
1 ✔
87
    return false;
88
  }
89

90
  markSecretKeys(users);
72 ✔
91

92
  m_userList = std::move(users);
93
  return true;
72 ✔
94
}
95

96
void UsersDialog::markSecretKeys(QList<UserInfo> &users) {
72 ✔
97
  QList<UserInfo> secret_keys = m_pass->listKeys("", true);
144 ✔
98
  QSet<QString> secretKeyIds;
99
  for (const UserInfo &sec : std::as_const(secret_keys)) {
79 ✔
100
    secretKeyIds.insert(sec.key_id);
7 ✔
101
  }
102
  for (auto &user : users) {
211 ✔
103
    if (secretKeyIds.contains(user.key_id)) {
139 ✔
104
      user.have_secret = true;
7 ✔
105
    }
106
  }
107
}
72 ✔
108

109
void UsersDialog::showRecipientWarning(const QString &text,
14 ✔
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);
14 ✔
114
  banner->setTextFormat(Qt::PlainText);
14 ✔
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));
14 ✔
118
  banner->setObjectName(name);
14 ✔
119
  banner->setWordWrap(true);
14 ✔
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();
14 ✔
123
  bold.setBold(true);
124
  banner->setFont(bold);
14 ✔
125
  QPalette palette = banner->palette();
14 ✔
126
  palette.setColor(QPalette::WindowText, QColor(Qt::red));
14 ✔
127
  banner->setPalette(palette);
14 ✔
128
  banner->setContentsMargins(4, 4, 4, 4);
14 ✔
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);
14 ✔
135
  area->setWidget(banner);
14 ✔
136
  area->setWidgetResizable(true);
14 ✔
137
  area->setFrameShape(QFrame::NoFrame);
14 ✔
138
  area->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
14 ✔
139
  area->setMaximumHeight(banner->fontMetrics().lineSpacing() * 8 + 8);
14 ✔
140
  ui->verticalLayout->insertWidget(1, area);
14 ✔
141
}
14 ✔
142

143
void UsersDialog::showNestedLists() {
70 ✔
144
  // The walk re-encryption takes: hidden folders and links are not entered.
145
  const QString dir = QDir::cleanPath(m_dir);
70 ✔
146
  if (!QFileInfo(dir).isDir()) {
70 ✔
147
    return;
148
  }
149
  QStringList unlisted;
70 ✔
150
  const QStringList lists = Util::regularFilesUnder(
210 ✔
151
      dir, {QStringLiteral(".gpg-id")}, nullptr, true, &unlisted);
140 ✔
152
  const auto relative = [&dir](const QString &folder) {
10 ✔
153
    return QDir::toNativeSeparators(QDir(dir).relativeFilePath(folder));
20 ✔
154
  };
70 ✔
155
  QStringList nested;
70 ✔
156
  for (const QString &list : lists) {
129 ✔
157
    const QString folder = QFileInfo(list).path();
59 ✔
158
    if (QDir::cleanPath(folder) != dir) {
118 ✔
159
      nested << relative(folder);
18 ✔
160
    }
161
  }
162
  QStringList unread;
70 ✔
163
  for (const QString &folder : std::as_const(unlisted)) {
71 ✔
164
    unread << relative(folder);
2 ✔
165
  }
166
  constexpr qsizetype kMaxNamed = 5;
167
  const auto named = [](const QStringList &folders) {
5 ✔
168
    QString names = folders.mid(0, kMaxNamed).join(QStringLiteral(", "));
10 ✔
169
    if (folders.size() > kMaxNamed) {
5 ✔
170
      names += QStringLiteral(", …");
×
171
    }
172
    return names;
5 ✔
173
  };
174
  QStringList text;
70 ✔
175
  if (!nested.isEmpty()) {
70 ✔
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 "
4 ✔
179
               "saving here does not change: %1",
180
               nullptr, static_cast<int>(nested.size()))
181
                .arg(named(nested));
8 ✔
182
  }
183
  if (!unread.isEmpty()) {
70 ✔
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 "
1 ✔
187
               "they have their own recipients is unknown: %1",
188
               nullptr, static_cast<int>(unread.size()))
189
                .arg(named(unread));
2 ✔
190
  }
191
  if (!text.isEmpty()) {
70 ✔
192
    showRecipientWarning(text.join(QLatin1Char('\n')),
10 ✔
193
                         QStringLiteral("nestedListsWarning"));
5 ✔
194
  }
195
}
196

197
namespace {
198

199
/// A key ID as written anywhere: without a 0x prefix, upper case.
200
auto normalisedKeyId(const QString &id) -> QString {
436 ✔
201
  const QString trimmed = id.trimmed();
202
  return (trimmed.startsWith(QLatin1String("0x"), Qt::CaseInsensitive)
436 ✔
203
              ? trimmed.mid(2)
872 ✔
204
              : trimmed)
205
      .toUpper();
436 ✔
206
}
207

208
/// Whether two hex identifiers name the same key. v4 key IDs are fingerprint
209
/// suffixes; v5/v6 key IDs are the first 16 digits, with the short ID in the
210
/// following eight. Do not accept a v5/v6 fingerprint's tail as its key ID.
211
auto keyIdsMatch(const QString &first, const QString &second) -> bool {
218 ✔
212
  static const QRegularExpression hexId(QStringLiteral("^[0-9A-F]{8,}$"));
225 ✔
213
  const QString a = normalisedKeyId(first);
218 ✔
214
  const QString b = normalisedKeyId(second);
218 ✔
215
  if (!hexId.match(a).hasMatch() || !hexId.match(b).hasMatch()) {
436 ✔
216
    return false;
217
  }
218
  if (a.size() == 64) {
218 ✔
219
    return b == a || (b.size() == 16 && a.startsWith(b)) ||
16 ✔
220
           (b.size() == 8 && a.mid(8, 8) == b);
19 ✔
221
  }
222
  if (b.size() == 64) {
202 ✔
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);
202 ✔
227
}
228

229
/// The hex identifier a .gpg-id line names, without "0x" and a trailing
230
/// "!", when the line is one in the lengths gpg reads as a key ID or
231
/// fingerprint (8, 16, 40 or 64 digits); empty otherwise.
232
auto keyIdOfLine(const QString &recipient) -> QString {
18,360 ✔
233
  static const QRegularExpression hexLine(
234
      QStringLiteral("^(?:0[xX])?([0-9A-Fa-f]+)!?$"));
18,366 ✔
235
  const QRegularExpressionMatch match = hexLine.match(recipient.trimmed());
18,360 ✔
236
  if (!match.hasMatch()) {
18,360 ✔
237
    return {};
18,053 ✔
238
  }
239
  const QString digits = match.captured(1);
307 ✔
240
  const qsizetype size = digits.size();
241
  return size == 8 || size == 16 || size == 40 || size == 64 ? digits
307 ✔
242
                                                             : QString();
×
243
}
18,360 ✔
244

245
/// The text a .gpg-id line searches the user IDs for, after gpg's "=",
246
/// "<...>", "@" and "*" markers; empty when the line is not one of those
247
/// forms or a plain name.
248
auto nameTermOfLine(const QString &recipient) -> QString {
18,038 ✔
249
  const QString line = recipient.trimmed();
250
  if (line.isEmpty()) {
18,038 ✔
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(
1 ✔
258
      "^(?:0[xX]|[0-9A-Fa-f]+!?$|[0-9A-Fa-f]{4}(?:\\s+[0-9A-Fa-f]{4})+!?$)"));
18,040 ✔
259
  if (hexish.match(line).hasMatch() ||
36,076 ✔
260
      QStringLiteral(".+#&^/[:!\\").contains(line.front())) {
36,071 ✔
261
    return {};
17 ✔
262
  }
263
  QString term = line;
264
  if (term.startsWith(u'<')) {
18,021 ✔
265
    if (!term.endsWith(u'>')) {
2 ✔
266
      return {};
×
267
    }
268
    term = term.mid(1, term.size() - 2);
4 ✔
269
  } else if (term.startsWith(u'=') || term.startsWith(u'@') ||
36,038 ✔
270
             term.startsWith(u'*')) {
36,038 ✔
271
    term.remove(0, 1);
×
272
  }
273
  return term;
274
}
275

276
/// Whether answersTo() can judge @p recipient on its own: a key ID or
277
/// fingerprint in a length gpg reads as one, or a name. For those every key
278
/// gpg resolves the line to is one answersTo() matches, given the key's full
279
/// listing, so a line that matches no listed key names no key in the
280
/// keyring. Any other form (a fingerprint written with spaces or between
281
/// colons, a keygrip, "*" alone) needs gpg's own answer.
282
auto judgedLocally(const QString &recipient) -> bool {
6,119 ✔
283
  return !keyIdOfLine(recipient).isEmpty() ||
12,145 ✔
284
         !nameTermOfLine(recipient).isEmpty();
12,145 ✔
285
}
286

287
/// Whether @p recipient, a .gpg-id line judgedLocally() accepts, names
288
/// @p key the way gpg's -r resolves it: a key ID or fingerprint of the key
289
/// or of one of its subkeys (v4 key IDs are a fingerprint's tail, v5/v6 ones
290
/// its head), or else a name, matched case-insensitively as a substring of
291
/// any of its user IDs. That is as loose as gpg's substring search and
292
/// looser than its exact ("="), mailbox ("<...>") and domain ("@") ones, so
293
/// it may claim a key gpg would not, but never misses one gpg finds.
294
auto answersTo(const UserInfo &key, const QString &recipient) -> bool {
12,155 ✔
295
  const QString keyId = keyIdOfLine(recipient);
12,155 ✔
296
  if (!keyId.isEmpty()) {
12,155 ✔
297
    return keyIdsMatch(key.key_id, keyId) ||
143 ✔
298
           std::any_of(key.subkeys.cbegin(), key.subkeys.cend(),
103 ✔
299
                       [&keyId](const QString &subkey) {
300
                         return keyIdsMatch(subkey, keyId);
69 ✔
301
                       });
302
  }
303
  const QString term = nameTermOfLine(recipient);
12,012 ✔
304
  if (term.isEmpty()) {
12,012 ✔
305
    return false;
306
  }
307
  const auto holds = [&term](const QString &uid) {
24,022 ✔
308
    return uid.contains(term, Qt::CaseInsensitive);
24,022 ✔
309
  };
12,012 ✔
310
  return holds(key.name) ||
12,012 ✔
311
         std::any_of(key.uids.cbegin(), key.uids.cend(), holds);
12,009 ✔
312
}
313

314
/// @p listed with each line once, in first-seen order: a line listed twice
315
/// is one recipient, and one row.
316
auto uniqueLines(const QStringList &listed) -> QStringList {
47 ✔
317
  QStringList lines;
47 ✔
318
  QSet<QString> seen;
319
  for (const QString &line : listed) {
6,179 ✔
320
    if (!seen.contains(line)) {
6,132 ✔
321
      seen.insert(line);
6,131 ✔
322
      lines.append(line);
323
    }
324
  }
325
  return lines;
47 ✔
326
}
327

328
} // namespace
329

330
void UsersDialog::selectRecipients(const QStringList &listed) {
47 ✔
331
  QStringList recipients = uniqueLines(listed);
47 ✔
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)) {
47 ✔
339
    return;
340
  }
341
  const std::optional<QStringList> reached =
342
      m_pass->encryptionReaches(recipients);
46 ✔
343
  if (reached && !reached->isEmpty() && tickReached(*reached, recipients)) {
46 ✔
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)) {
42 ✔
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);
39 ✔
360
}
361

362
void UsersDialog::keepAsWritten(const QString &line, const QString &why) {
23 ✔
363
  UserInfo kept;
23 ✔
364
  kept.key_id = line;
23 ✔
365
  kept.enabled = true;
23 ✔
366
  kept.name = " ?? " + why;
23 ✔
367
  m_userList.append(kept);
23 ✔
368
}
23 ✔
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.
379
auto UsersDialog::tickReached(const QStringList &ids, const QStringList &lines)
6 ✔
380
    -> bool {
381
  bool shared = false;
382
  QSet<int> reachedRows;
383
  for (const QString &id : ids) {
12 ✔
384
    QList<int> rows;
6 ✔
385
    for (int row = 0; row < m_userList.size(); ++row) {
18 ✔
386
      if (answersTo(m_userList.at(row), id)) {
12 ✔
387
        rows << row;
388
      }
389
    }
390
    if (rows.isEmpty()) {
6 ✔
391
      return false;
392
    }
393
    shared = shared || rows.size() > 1;
6 ✔
394
    for (const int row : std::as_const(rows)) {
14 ✔
395
      reachedRows.insert(row);
8 ✔
396
    }
397
  }
398
  if (!shared) {
6 ✔
399
    for (const int row : std::as_const(reachedRows)) {
4 ✔
400
      m_userList[row].enabled = true;
4 ✔
401
    }
402
    return true;
4 ✔
403
  }
404
  for (const QString &line : lines) {
4 ✔
405
    const QString keyId = keyIdOfLine(line);
2 ✔
406
    bool ticked = false;
407
    if (!keyId.isEmpty()) {
2 ✔
408
      for (const int row : std::as_const(reachedRows)) {
2 ✔
409
        if (keyIdsMatch(m_userList.at(row).key_id, keyId)) {
2 ✔
410
          m_userList[row].enabled = true;
1 ✔
411
          ticked = true;
412
        }
413
      }
414
    }
415
    if (!ticked) {
1 ✔
416
      keepAsWritten(line, tr("Matches more than one key; kept as written"));
2 ✔
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.
427
auto UsersDialog::setAsideHeldTwice(QStringList *recipients) -> bool {
47 ✔
428
  if (const std::optional<QHash<QString, QStringList>> held =
429
          m_pass->keyLinesHeldTwice(*recipients);
47 ✔
430
      !held || !held->isEmpty()) {
47 ✔
431
    showRecipientWarning(Pass::describeKeyLinesHeldTwice(held),
2 ✔
432
                         QStringLiteral("heldTwiceWarning"));
1 ✔
433
    QStringList rest;
1 ✔
434
    for (const QString &line : std::as_const(*recipients)) {
2 ✔
435
      if (!held) {
1 ✔
436
        keepAsWritten(line, tr("Keys could not be checked; kept as written"));
×
437
      } else if (held->contains(line)) {
1 ✔
438
        keepAsWritten(line, tr("Held by more than one key; kept as written"));
2 ✔
439
      } else {
440
        rest << line;
441
      }
442
    }
443
    if (rest.isEmpty()) {
1 ✔
444
      return false;
445
    }
446
    *recipients = rest;
447
  }
448
  return true;
46 ✔
449
}
450

451
auto UsersDialog::probeEachLine(QStringList *recipients) -> bool {
7 ✔
452
  QStringList order;
7 ✔
453
  std::copy_if(recipients->cbegin(), recipients->cend(),
7 ✔
454
               std::back_inserter(order),
455
               [](const QString &line) { return keyIdOfLine(line).isEmpty(); });
42 ✔
456
  std::copy_if(
7 ✔
457
      recipients->cbegin(), recipients->cend(), std::back_inserter(order),
458
      [](const QString &line) { return !keyIdOfLine(line).isEmpty(); });
42 ✔
459
  constexpr int kMaxLineProbes = 10;
460
  QStringList unsure;
7 ✔
461
  int probes = 0;
462
  for (const QString &line : std::as_const(order)) {
49 ✔
463
    if (probes++ >= kMaxLineProbes) {
42 ✔
464
      keepAsWritten(line, tr("Not checked; kept as written"));
8 ✔
465
      continue;
8 ✔
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
34 ✔
470
                                : m_pass->encryptionReaches({line});
100 ✔
471
    if (!one) {
34 ✔
472
      keepAsWritten(line, tr("Key not found in keyring, or not usable"));
26 ✔
473
    } else if (one->isEmpty() || !tickReached(*one, {line})) {
27 ✔
474
      unsure << line;
475
    }
476
  }
477
  if (unsure.isEmpty()) {
7 ✔
478
    return false;
479
  }
480
  *recipients = unsure;
481
  return true;
4 ✔
482
}
483

484
void UsersDialog::searchKeyring(const QStringList &recipients) {
39 ✔
485
  // One gpg call resolves every recipient, by key ID or by email/UID.
486
  QList<UserInfo> resolved = m_pass->listKeys(recipients);
78 ✔
487
  if (resolved.isEmpty() && recipients.size() > 1) {
39 ✔
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;
2 ✔
494
    std::copy_if(recipients.cbegin(), recipients.cend(),
2 ✔
495
                 std::back_inserter(readable), judgedLocally);
496
    if (!readable.isEmpty() && readable.size() < recipients.size()) {
2 ✔
497
      resolved = m_pass->listKeys(readable);
4 ✔
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;
39 ✔
509
  QSet<QString> notLookedUp;
510
  for (const QString &recipient : std::as_const(recipients)) {
6,142 ✔
511
    if (judgedLocally(recipient)) {
6,103 ✔
512
      continue;
6,089 ✔
513
    }
514
    if (lookups++ >= kMaxLookups) {
15 ✔
515
      notLookedUp.insert(recipient);
1 ✔
516
      continue;
1 ✔
517
    }
518
    const QList<UserInfo> keys = m_pass->listKeys(recipient);
14 ✔
519
    perLineHasKey.insert(recipient, !keys.isEmpty());
14 ✔
520
    resolved += keys;
521
  }
522

523
  for (UserInfo &user : m_userList) {
122 ✔
524
    if (std::any_of(resolved.cbegin(), resolved.cend(),
83 ✔
525
                    [&user](const UserInfo &key) {
526
                      return key.key_id == user.key_id;
96 ✔
527
                    })) {
528
      user.enabled = true;
51 ✔
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)) {
6,142 ✔
537
    UserInfo missing;
6,103 ✔
538
    missing.key_id = recipient;
6,103 ✔
539
    if (notLookedUp.contains(recipient)) {
6,103 ✔
540
      missing.name = " ?? " + tr("Not looked up in keyring");
1 ✔
541
      m_notLookedUp.insert(recipient);
1 ✔
542
      m_userList.append(missing);
543
      continue;
544
    }
545
    const auto cached = perLineHasKey.constFind(recipient);
6,102 ✔
546
    const bool found = cached != perLineHasKey.constEnd()
547
                           ? cached.value()
14 ✔
548
                           : std::any_of(resolved.cbegin(), resolved.cend(),
6,088 ✔
549
                                         [&recipient](const UserInfo &key) {
550
                                           return answersTo(key, recipient);
12,143 ✔
551
                                         });
6,088 ✔
552
    if (!found) {
6,102 ✔
553
      missing.enabled = true;
6,057 ✔
554
      missing.name = " ?? " + tr("Key not found in keyring");
12,114 ✔
555
      m_userList.append(missing);
556
    }
557
  }
6,103 ✔
558
}
78 ✔
559

560
void UsersDialog::loadRecipients() {
70 ✔
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.
564
  if (m_preselect == Preselect::Nothing) {
70 ✔
565
    return;
4 ✔
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 =
570
      m_pass->recipientsForEditing(m_dir, m_passStore);
66 ✔
571
  m_listRead = true;
66 ✔
572
  m_readState = static_cast<int>(loaded.state);
66 ✔
573
  m_readRecipients = loaded.recipients;
574
  if (!loaded.warning.isEmpty()) {
66 ✔
575
    showRecipientWarning(loaded.warning);
16 ✔
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.
579
  if (loaded.state != Pass::RecipientsForEditing::State::Rejected &&
66 ✔
580
      !loaded.recipients.isEmpty()) {
581
    selectRecipients(loaded.recipients);
47 ✔
582
  }
583
}
584

585
UsersDialog::~UsersDialog() = default;
142 ✔
586

587
auto UsersDialog::listChangedSinceRead() const -> bool {
10 ✔
588
  const Pass::RecipientsForEditing now =
589
      m_pass->recipientsForEditing(m_dir, m_passStore);
10 ✔
590
  return static_cast<int>(now.state) != m_readState ||
10 ✔
591
         now.recipients != m_readRecipients;
10 ✔
592
}
593

594
void UsersDialog::accept() {
14 ✔
595
  if (!hasSelection()) {
14 ✔
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.
604
  if (m_listRead && listChangedSinceRead()) {
12 ✔
605
    QMessageBox::warning(
2 ✔
606
        this, tr("Recipients not changed"),
1 ✔
607
        tr("The recipient list of this folder changed while this dialog was "
1 ✔
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;
1 ✔
612
  }
613
  if (m_initOnAccept) {
11 ✔
614
    // The pass backend re-encrypts every entry itself: asked first when one
615
    // would gain a reader it does not have.
616
    if (!PlainMessageBox::confirmPassRun(this, m_passStore, [this] {
16 ✔
617
          return m_pass->entriesInitWouldWiden(m_dir, m_userList);
8 ✔
618
        })) {
619
      return;
620
    }
621
    if (m_listRead) {
7 ✔
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.
624
      Pass::RecipientsForEditing read;
7 ✔
625
      read.state = static_cast<Pass::RecipientsForEditing::State>(m_readState);
7 ✔
626
      read.recipients = m_readRecipients;
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.
630
      if (!m_pass->initIfUnchanged(m_dir, m_userList, m_dir, m_passStore,
7 ✔
631
                                   read)) {
632
        return;
633
      }
634
    } else {
635
      m_pass->Init(m_dir, m_userList);
×
636
    }
637
  }
638

639
  QDialog::accept();
9 ✔
640
}
641

642
auto UsersDialog::hasSelection() const -> bool {
132 ✔
643
  return std::any_of(m_userList.cbegin(), m_userList.cend(),
644
                     [](const UserInfo &user) { return user.enabled; });
198 ✔
645
}
646

647
void UsersDialog::updateOkButton() {
115 ✔
648
  if (auto *ok = ui->buttonBox->button(QDialogButtonBox::Ok)) {
115 ✔
649
    ok->setEnabled(hasSelection());
115 ✔
650
  }
651
}
115 ✔
652

653
void UsersDialog::keyPressEvent(QKeyEvent *event) {
1 ✔
654
  switch (event->key()) {
1 ✔
655
  case Qt::Key_Escape:
1 ✔
656
    ui->lineEdit->clear();
1 ✔
657
    break;
1 ✔
658
  default:
659
    break;
660
  }
661
}
1 ✔
662

663
void UsersDialog::itemChange(QListWidgetItem *item) {
21 ✔
664
  if (!item) {
21 ✔
665
    return;
1 ✔
666
  }
667
  bool ok = false;
21 ✔
668
  const int index = item->data(Qt::UserRole).toInt(&ok);
21 ✔
669
  if (!ok) {
21 ✔
UNCOV
670
    qCWarning(lcQtPass)
×
UNCOV
671
        << "UsersDialog::itemChange: invalid user index data for item";
×
UNCOV
672
    return;
×
673
  }
674
  if (index < 0 || index >= m_userList.size()) {
21 ✔
675
    qCWarning(lcQtPass) << "UsersDialog::itemChange: user index out of range:"
2 ✔
676
                        << index << "valid range is [0,"
1 ✔
677
                        << (m_userList.size() - 1) << "]";
1 ✔
678
    return;
1 ✔
679
  }
680
  m_userList[index].enabled = item->checkState() == Qt::Checked;
20 ✔
681
  updateOkButton();
20 ✔
682
}
683

684
void UsersDialog::populateList(const QString &filter) {
95 ✔
685
  // Invalidate cached datetime so expiry checks use fresh current time
686
  m_cachedDateTimeValid = false;
95 ✔
687

688
  QString patternString = "*" + filter + "*";
95 ✔
689
  if (m_cachedPatternString != patternString) {
95 ✔
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(
172 ✔
695
            patternString, QRegularExpression::NonPathWildcardConversion),
696
        QRegularExpression::CaseInsensitiveOption);
86 ✔
697
    if (re.isValid()) {
86 ✔
698
      m_cachedNameFilter = re;
86 ✔
699
      m_cachedPatternString = patternString;
86 ✔
700
    }
701
  }
86 ✔
702
  const QRegularExpression &nameFilter = m_cachedNameFilter;
95 ✔
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);
95 ✔
707
  ui->listWidget->clear();
95 ✔
708

709
  for (int i = 0; i < m_userList.size(); ++i) {
6,375 ✔
710
    const auto &user = m_userList.at(i);
711
    if (!passesFilter(user, filter, nameFilter)) {
6,280 ✔
712
      continue;
27 ✔
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));
6,253 ✔
719
    applyUserStyling(item, user);
6,253 ✔
720
    item->setCheckState(user.enabled ? Qt::Checked : Qt::Unchecked);
6,348 ✔
721
    item->setData(Qt::UserRole, QVariant::fromValue(i));
6,253 ✔
722
    ui->listWidget->addItem(item);
6,253 ✔
723
  }
724
  // setSortingEnabled() only sets the flag; sortItems() sorts.
725
  ui->listWidget->sortItems();
95 ✔
726
  ui->listWidget->setSortingEnabled(true);
95 ✔
727
  updateOkButton();
95 ✔
728
}
95 ✔
729

730
bool UsersDialog::passesFilter(const UserInfo &user, const QString &filter,
6,280 ✔
731
                               const QRegularExpression &nameFilter) const {
732
  if (!filter.isEmpty() && !nameFilter.match(user.name).hasMatch()) {
6,294 ✔
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() ||
6,266 ✔
740
      m_notLookedUp.contains(user.key_id)) {
99 ✔
741
    return true;
6,168 ✔
742
  }
743
  return user.isValid() && !isUserExpired(user);
90 ✔
744
}
745

746
auto UsersDialog::isUserExpired(const UserInfo &user) const -> bool {
6,343 ✔
747
  if (!m_cachedDateTimeValid) {
6,343 ✔
748
    m_cachedCurrentDateTime = QDateTime::currentDateTime();
92 ✔
749
    m_cachedDateTimeValid = true;
92 ✔
750
  }
751
  // gpg marks a key it already judged expired with validity 'e'.
752
  return user.validity == 'e' ||
12,684 ✔
753
         (user.expiry.isValid() && m_cachedCurrentDateTime > user.expiry);
6,350 ✔
754
}
755

756
namespace {
757
/**
758
 * @brief Text cut to a length a list row can draw at once.
759
 *
760
 * A .gpg-id line no key answers to is shown as written, up to the 1 MiB the
761
 * list may hold: Qt elided such a row on every paint in time quadratic in
762
 * its tabs and script changes, and the dialog hung for minutes. No user ID
763
 * or key ID is this long.
764
 * @param text A user ID or key ID.
765
 * @return The text, or its first 256 characters followed by an ellipsis;
766
 *         a surrogate pair is never split.
767
 */
768
auto shortened(const QString &text) -> QString {
12,506 ✔
769
  constexpr qsizetype kMaxShown = 256;
770
  if (text.size() <= kMaxShown) {
12,506 ✔
771
    return text;
772
  }
773
  qsizetype cut = kMaxShown;
774
  if (text.at(cut - 1).isHighSurrogate()) {
1 ✔
775
    --cut;
776
  }
777
  return text.left(cut) + QChar(0x2026);
2 ✔
778
}
779
} // namespace
780

781
QString UsersDialog::buildUserText(const UserInfo &user) const {
6,253 ✔
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" +
12,506 ✔
787
                 Util::displayable(shortened(user.key_id), false);
12,506 ✔
788
  if (user.created.isValid()) {
6,253 ✔
789
    text += " " + tr("created") + " " +
342 ✔
790
            QLocale::system().toString(user.created, QLocale::ShortFormat);
513 ✔
791
  }
792
  if (user.expiry.isValid()) {
6,253 ✔
793
    text += " " + tr("expires") + " " +
12 ✔
794
            QLocale::system().toString(user.expiry, QLocale::ShortFormat);
18 ✔
795
  }
796
  return text;
6,253 ✔
797
}
798

799
void UsersDialog::applyUserStyling(QListWidgetItem *item,
6,253 ✔
800
                                   const UserInfo &user) const {
801
  const QString originalText = item->text();
6,253 ✔
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)) {
6,253 ✔
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);
6 ✔
811
    item->setForeground(Qt::white);
6 ✔
812
    item->setText(tr("[EXPIRED] ") + originalText);
12 ✔
813
  } else if (!user.isValid()) {
814
    item->setBackground(Qt::darkRed);
6,085 ✔
815
    item->setForeground(Qt::white);
6,085 ✔
816
    item->setText(tr("[INVALID] ") + originalText);
12,170 ✔
817
  } else if (!user.fullyValid()) {
162 ✔
818
    item->setBackground(Qt::darkYellow);
7 ✔
819
    item->setForeground(Qt::white);
7 ✔
820
    item->setText(tr("[PARTIAL] ") + originalText);
14 ✔
821
  } else {
822
    item->setText(originalText);
155 ✔
823
    badged = false;
824
  }
825
  if (user.have_secret) {
6,253 ✔
826
    if (!badged) {
9 ✔
827
      item->setForeground(QApplication::palette().color(QPalette::Link));
18 ✔
828
    }
829
    QFont font = item->font();
9 ✔
830
    font.setBold(true);
831
    item->setFont(font);
9 ✔
832
  }
9 ✔
833
}
6,253 ✔
834

835
void UsersDialog::on_lineEdit_textChanged(const QString &filter) {
14 ✔
836
  populateList(filter);
14 ✔
837
}
14 ✔
838

839
void UsersDialog::on_checkBox_clicked() { populateList(ui->lineEdit->text()); }
18 ✔
840

841
void UsersDialog::selectImportedKey(const QString &importedKey) {
2 ✔
842
  // The stored key_id, not the item text.
843
  for (int i = 0; i < ui->listWidget->count(); ++i) {
4 ✔
844
    QListWidgetItem *item = ui->listWidget->item(i);
4 ✔
845
    bool ok = false;
4 ✔
846
    const int idx = item != nullptr ? item->data(Qt::UserRole).toInt(&ok) : -1;
4 ✔
847
    if (ok && idx >= 0 && idx < m_userList.size() &&
8 ✔
848
        !m_userList[idx].key_id.isEmpty() &&
8 ✔
849
        keyIdsMatch(m_userList[idx].key_id, importedKey)) {
4 ✔
850
      ui->listWidget->setCurrentItem(item);
2 ✔
851
      return;
2 ✔
852
    }
853
  }
854
}
855

856
void UsersDialog::on_importKeyButton_clicked() {
3 ✔
857
  ImportKeyDialog dialog(m_gpgExe, this);
3 ✔
858
  if (dialog.exec() != QDialog::Accepted) {
3 ✔
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();
2 ✔
865
  if (importedKey.isEmpty()) {
2 ✔
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;
2 ✔
874
  for (const UserInfo &user : std::as_const(m_userList)) {
4 ✔
875
    if (user.enabled) {
2 ✔
876
      selected.append(user.key_id);
2 ✔
877
    }
878
  }
879

880
  if (!loadGpgKeys()) {
2 ✔
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;
2 ✔
893
  for (const QString &keyId : std::as_const(selected)) {
4 ✔
894
    bool matched = false;
895
    for (UserInfo &user : m_userList) {
6 ✔
896
      if (user.key_id == keyId) {
4 ✔
897
        user.enabled = true;
2 ✔
898
        matched = true;
899
      }
900
    }
901
    if (!matched) {
2 ✔
902
      unresolved.append(keyId);
903
    }
904
  }
905
  if (!unresolved.isEmpty()) {
2 ✔
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);
2 ✔
913
    ui->lineEdit->clear();
2 ✔
914
  }
2 ✔
915
  populateList(QString());
2 ✔
916

917
  selectImportedKey(importedKey);
2 ✔
918
}
3 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc