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

IJHack / QtPass / 45377372884

24 Nov 2026 10:42AM UTC coverage: 94.735% (-0.009%) from 94.744%
45377372884

push

github

web-flow
Users dialog: tick the key a subkey or second user ID line names (#2314)

The Users dialog now reads the full key listing: every user ID (revoked
ones too, colon escapes decoded) and each subkey's ID and fingerprint. A
.gpg-id line naming a member's subkey or second user ID ticks that member
instead of becoming a separate ticked "Key not found" row that survives
unticking the member, so the store stays encrypted to it.

Key IDs in the lengths gpg reads and the name forms are judged from one
batched listing. Lines gpg reads in its own way (a fingerprint with spaces
or between colons, a keygrip, other search modes) get one gpg call each,
up to ten; past that a line is listed unticked as "Not looked up in
keyring" rather than kept unseen. The retry after an unreadable line is
one call, and a duplicate line is one row.

Scan ANT-2026-G4QELVPH.

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

79 of 83 new or added lines in 2 files covered. (95.18%)

1 existing line in 1 file now uncovered.

9771 of 10314 relevant lines covered (94.74%)

18367.76 hits per line

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

97.09
/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 "qtpasssettings.h"
12
#include "ui_usersdialog.h"
13
#include "util.h"
14
#include "windowstatestore.h"
15
#include <QApplication>
16
#include <QDateTime>
17
#include <QDialogButtonBox>
18
#include <QDir>
19
#include <QFileInfo>
20
#include <QFont>
21
#include <QHash>
22
#include <QKeyEvent>
23
#include <QLabel>
24
#include <QLineEdit>
25
#include <QListWidget>
26
#include <QMessageBox>
27
#include <QPalette>
28
#include <QPushButton>
29
#include <QRegularExpression>
30
#include <QScrollArea>
31
#include <QSet>
32
#include <QSignalBlocker>
33
#include <QWidget>
34
#include <algorithm>
35
#include <iterator>
36
#include <utility>
37

38
#include "qtpasslogging.h"
39
UsersDialog::UsersDialog(Pass *pass, const AppSettings &s, QString dir,
56 ✔
40
                         QWidget *parent)
56 ✔
41
    : UsersDialog(pass, s, std::move(dir), Preselect::FromList, parent) {}
112 ✔
42

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

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

57
  loadRecipients();
59 ✔
58
  showNestedLists();
59 ✔
59
  populateList();
59 ✔
60

61
  connectSignals();
59 ✔
62
}
×
63

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

73
  ui->lineEdit->setClearButtonEnabled(true);
59 ✔
74
}
59 ✔
75

76
void UsersDialog::restoreDialogState() {
60 ✔
77
  WindowStateStore::attach(*this, QStringLiteral("usersDialog"));
120 ✔
78
}
60 ✔
79

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

89
  markSecretKeys(users);
61 ✔
90

91
  m_userList = users;
92
  return true;
61 ✔
93
}
94

95
void UsersDialog::markSecretKeys(QList<UserInfo> &users) {
61 ✔
96
  QList<UserInfo> secret_keys = m_pass->listKeys("", true);
122 ✔
97
  QSet<QString> secretKeyIds;
98
  for (const UserInfo &sec : secret_keys) {
66 ✔
99
    secretKeyIds.insert(sec.key_id);
5 ✔
100
  }
101
  for (auto &user : users) {
178 ✔
102
    if (secretKeyIds.contains(user.key_id)) {
117 ✔
103
      user.have_secret = true;
5 ✔
104
    }
105
  }
106
}
61 ✔
107

108
void UsersDialog::showRecipientWarning(const QString &text,
13 ✔
109
                                       const QString &name) {
110
  // Plain text before the text is set: it can quote the store's recipient
111
  // list, which as rich text could make Qt load a file (<img src=...>).
112
  auto *banner = new QLabel(this);
13 ✔
113
  banner->setTextFormat(Qt::PlainText);
13 ✔
114
  // And with nothing in it that changes how the rest reads: a folder name
115
  // with a bidi override mirrored the warning after it.
116
  banner->setText(Util::displayable(text));
13 ✔
117
  banner->setObjectName(name);
13 ✔
118
  banner->setWordWrap(true);
13 ✔
119
  // Palette, not a stylesheet colour, so it reads on dark themes too; red as
120
  // ProcessOutputPanel paints error lines.
121
  QFont bold = banner->font();
13 ✔
122
  bold.setBold(true);
123
  banner->setFont(bold);
13 ✔
124
  QPalette palette = banner->palette();
13 ✔
125
  palette.setColor(QPalette::WindowText, QColor(Qt::red));
13 ✔
126
  banner->setPalette(palette);
13 ✔
127
  banner->setContentsMargins(4, 4, 4, 4);
13 ✔
128
  // In a scroll area of a few lines: the text quotes folder paths a
129
  // co-writer chose, and a word-wrapped label is as wide as its longest
130
  // run without a space and as tall as its lines. Unscrolled it sized the
131
  // dialog to tens of thousands of pixels; a scroll area asks for at most
132
  // a bounded size, and all of the text can still be read.
133
  auto *area = new QScrollArea(this);
13 ✔
134
  area->setWidget(banner);
13 ✔
135
  area->setWidgetResizable(true);
13 ✔
136
  area->setFrameShape(QFrame::NoFrame);
13 ✔
137
  area->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
13 ✔
138
  area->setMaximumHeight(banner->fontMetrics().lineSpacing() * 8 + 8);
13 ✔
139
  ui->verticalLayout->insertWidget(1, area);
13 ✔
140
}
13 ✔
141

142
void UsersDialog::showNestedLists() {
59 ✔
143
  // The walk re-encryption takes: hidden folders and links are not entered.
144
  const QString dir = QDir::cleanPath(m_dir);
59 ✔
145
  if (!QFileInfo(dir).isDir()) {
59 ✔
146
    return;
147
  }
148
  QStringList unlisted;
59 ✔
149
  const QStringList lists = Util::regularFilesUnder(
177 ✔
150
      dir, {QStringLiteral(".gpg-id")}, nullptr, true, &unlisted);
118 ✔
151
  const auto relative = [&dir](const QString &folder) {
10 ✔
152
    return QDir::toNativeSeparators(QDir(dir).relativeFilePath(folder));
20 ✔
153
  };
59 ✔
154
  QStringList nested;
59 ✔
155
  for (const QString &list : lists) {
107 ✔
156
    const QString folder = QFileInfo(list).path();
48 ✔
157
    if (QDir::cleanPath(folder) != dir) {
96 ✔
158
      nested << relative(folder);
18 ✔
159
    }
160
  }
161
  QStringList unread;
59 ✔
162
  for (const QString &folder : std::as_const(unlisted)) {
60 ✔
163
    unread << relative(folder);
2 ✔
164
  }
165
  constexpr qsizetype kMaxNamed = 5;
166
  const auto named = [](const QStringList &folders) {
5 ✔
167
    QString names = folders.mid(0, kMaxNamed).join(QStringLiteral(", "));
10 ✔
168
    if (folders.size() > kMaxNamed) {
5 ✔
169
      names += QStringLiteral(", …");
×
170
    }
171
    return names;
5 ✔
172
  };
173
  QStringList text;
59 ✔
174
  if (!nested.isEmpty()) {
59 ✔
175
    //: %1 lists folders, such as "work, work/bank". Shown when changing the
176
    //: recipients of a folder that has folders with their own list below it.
177
    text << tr("%n folder(s) below this one have their own recipients, which "
4 ✔
178
               "saving here does not change: %1",
179
               nullptr, static_cast<int>(nested.size()))
180
                .arg(named(nested));
8 ✔
181
  }
182
  if (!unread.isEmpty()) {
59 ✔
183
    //: %1 lists folders, such as "work, work/bank", that QtPass could not
184
    //: read: no permission, or a name in them that is not valid UTF-8.
185
    text << tr("%n folder(s) below this one could not be read, so whether "
1 ✔
186
               "they have their own recipients is unknown: %1",
187
               nullptr, static_cast<int>(unread.size()))
188
                .arg(named(unread));
2 ✔
189
  }
190
  if (!text.isEmpty()) {
59 ✔
191
    showRecipientWarning(text.join(QLatin1Char('\n')),
10 ✔
192
                         QStringLiteral("nestedListsWarning"));
5 ✔
193
  }
194
}
195

196
namespace {
197

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

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

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

244
/// The text a .gpg-id line searches the user IDs for, after gpg's "=",
245
/// "<...>", "@" and "*" markers; empty when the line is not one of those
246
/// forms or a plain name.
247
auto nameTermOfLine(const QString &recipient) -> QString {
18,042 ✔
248
  const QString line = recipient.trimmed();
249
  if (line.isEmpty()) {
18,042 ✔
NEW
250
    return {};
×
251
  }
252
  // A leading 0x, digits only, or groups of four digits split by spaces (a
253
  // fingerprint as gpg prints it) is a key ID gpg reads in its own way
254
  // (keyIdOfLine() takes the lengths it accepts); ".", "+", "#", "&", "^",
255
  // "/", "[" and ":" start search modes this dialog does not model.
256
  static const QRegularExpression hexish(QStringLiteral(
1 ✔
257
      "^(?:0[xX]|[0-9A-Fa-f]+!?$|[0-9A-Fa-f]{4}(?:\\s+[0-9A-Fa-f]{4})+!?$)"));
18,044 ✔
258
  if (hexish.match(line).hasMatch() ||
36,084 ✔
259
      QStringLiteral(".+#&^/[:!\\").contains(line.front())) {
36,075 ✔
260
    return {};
21 ✔
261
  }
262
  QString term = line;
263
  if (term.startsWith(u'<')) {
18,021 ✔
264
    if (!term.endsWith(u'>')) {
2 ✔
NEW
265
      return {};
×
266
    }
267
    term = term.mid(1, term.size() - 2);
4 ✔
268
  } else if (term.startsWith(u'=') || term.startsWith(u'@') ||
36,038 ✔
269
             term.startsWith(u'*')) {
36,038 ✔
NEW
270
    term.remove(0, 1);
×
271
  }
272
  return term;
273
}
274

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

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

313
} // namespace
314

315
void UsersDialog::selectRecipients(const QStringList &listed) {
36 ✔
316
  // A line listed twice is one recipient, and one row.
317
  QStringList recipients;
36 ✔
318
  QSet<QString> seen;
319
  for (const QString &line : listed) {
6,145 ✔
320
    if (!seen.contains(line)) {
6,109 ✔
321
      seen.insert(line);
6,108 ✔
322
      recipients.append(line);
323
    }
324
  }
325

326
  // One gpg call resolves every recipient, by key ID or by email/UID.
327
  QList<UserInfo> resolved = m_pass->listKeys(recipients);
72 ✔
328
  if (resolved.isEmpty() && recipients.size() > 1) {
36 ✔
329
    // One line gpg cannot read as a key search ("0x", a fingerprint one
330
    // digit short) aborts that whole call with exit code 2, so nothing is
331
    // listed for the other lines, whose keys are in the keyring all the same.
332
    // Every form judgedLocally() accepts gpg reads, so ask again for those;
333
    // the rest get a call of their own below.
334
    QStringList readable;
4 ✔
335
    std::copy_if(recipients.cbegin(), recipients.cend(),
4 ✔
336
                 std::back_inserter(readable), judgedLocally);
337
    if (!readable.isEmpty() && readable.size() < recipients.size()) {
4 ✔
338
      resolved = m_pass->listKeys(readable);
8 ✔
339
    }
340
  }
341

342
  // A line answersTo() cannot judge gets gpg's own verdict, one blocking
343
  // call each on the dialog's way up. Only unusual forms need it, so a few
344
  // are asked; past that a line is listed unticked as not looked up, so it
345
  // does not stay in the list unseen (a member could otherwise hide behind
346
  // it a key the user unticks).
347
  constexpr int kMaxLookups = 10;
348
  int lookups = 0;
349
  QHash<QString, bool> perLineHasKey;
36 ✔
350
  QSet<QString> notLookedUp;
351
  for (const QString &recipient : std::as_const(recipients)) {
6,144 ✔
352
    if (judgedLocally(recipient)) {
6,108 ✔
353
      continue;
6,092 ✔
354
    }
355
    if (lookups++ >= kMaxLookups) {
17 ✔
356
      notLookedUp.insert(recipient);
1 ✔
357
      continue;
1 ✔
358
    }
359
    const QList<UserInfo> keys = m_pass->listKeys(recipient);
16 ✔
360
    perLineHasKey.insert(recipient, !keys.isEmpty());
16 ✔
361
    resolved += keys;
362
  }
363

364
  for (UserInfo &user : m_userList) {
105 ✔
365
    if (std::any_of(resolved.cbegin(), resolved.cend(),
69 ✔
366
                    [&user](const UserInfo &key) {
367
                      return key.key_id == user.key_id;
87 ✔
368
                    })) {
369
      user.enabled = true;
48 ✔
370
    }
371
  }
372
  // Only what gpg itself cannot find is reported missing. A per-line answer
373
  // is gpg's own verdict for that line and decides it outright; that also
374
  // keeps a genuinely unreadable line ("0x") reported missing. Any other
375
  // line is missing when no key gpg resolved answers to it: the full listing
376
  // carries every user ID and subkey, so nothing is left for gpg to add.
377
  for (const QString &recipient : std::as_const(recipients)) {
6,144 ✔
378
    UserInfo missing;
6,108 ✔
379
    missing.key_id = recipient;
6,108 ✔
380
    if (notLookedUp.contains(recipient)) {
6,108 ✔
381
      missing.name = " ?? " + tr("Not looked up in keyring");
1 ✔
382
      m_notLookedUp.insert(recipient);
1 ✔
383
      m_userList.append(missing);
384
      continue;
385
    }
386
    const auto cached = perLineHasKey.constFind(recipient);
6,107 ✔
387
    const bool found = cached != perLineHasKey.constEnd()
388
                           ? cached.value()
16 ✔
389
                           : std::any_of(resolved.cbegin(), resolved.cend(),
6,091 ✔
390
                                         [&recipient](const UserInfo &key) {
391
                                           return answersTo(key, recipient);
12,140 ✔
392
                                         });
6,091 ✔
393
    if (!found) {
6,107 ✔
394
      missing.enabled = true;
6,065 ✔
395
      missing.name = " ?? " + tr("Key not found in keyring");
12,130 ✔
396
      m_userList.append(missing);
397
    }
398
  }
6,108 ✔
399
}
72 ✔
400

401
void UsersDialog::loadRecipients() {
59 ✔
402
  // A store that had no list when it was chosen (a new profile): a list
403
  // that appeared since is nobody's choice, and was read under the active
404
  // backend's signing policy, not the new profile's.
405
  if (m_preselect == Preselect::Nothing) {
59 ✔
406
    return;
4 ✔
407
  }
408
  // Through the backend: with a signing key only a verified list may be
409
  // preselected, since OK signs whatever is selected.
410
  const Pass::RecipientsForEditing loaded =
411
      m_pass->recipientsForEditing(m_dir, m_passStore);
55 ✔
412
  if (!loaded.warning.isEmpty()) {
55 ✔
413
    showRecipientWarning(loaded.warning);
16 ✔
414
  }
415
  // A folder without .gpg-id (new store, new profile) has no recipients yet;
416
  // listKeys() with no filter would return the whole keyring, preselected.
417
  if (loaded.state != Pass::RecipientsForEditing::State::Rejected &&
55 ✔
418
      !loaded.recipients.isEmpty()) {
419
    selectRecipients(loaded.recipients);
36 ✔
420
  }
421
}
422

423
UsersDialog::~UsersDialog() = default;
120 ✔
424

425
void UsersDialog::accept() {
9 ✔
426
  if (!hasSelection()) {
9 ✔
427
    // Nothing to encrypt to: an empty .gpg-id would make every insert fail
428
    // and the wizard never offers this dialog again once the file exists.
429
    return;
430
  }
431
  if (m_initOnAccept) {
7 ✔
432
    m_pass->Init(m_dir, m_userList);
8 ✔
433
  }
434

435
  QDialog::accept();
7 ✔
436
}
437

438
auto UsersDialog::hasSelection() const -> bool {
155 ✔
439
  return std::any_of(m_userList.cbegin(), m_userList.cend(),
440
                     [](const UserInfo &user) { return user.enabled; });
230 ✔
441
}
442

443
void UsersDialog::updateOkButton() {
143 ✔
444
  if (auto *ok = ui->buttonBox->button(QDialogButtonBox::Ok)) {
143 ✔
445
    ok->setEnabled(hasSelection());
143 ✔
446
  }
447
}
143 ✔
448

449
void UsersDialog::keyPressEvent(QKeyEvent *event) {
1 ✔
450
  switch (event->key()) {
1 ✔
451
  case Qt::Key_Escape:
1 ✔
452
    ui->lineEdit->clear();
1 ✔
453
    break;
1 ✔
454
  default:
455
    break;
456
  }
457
}
1 ✔
458

459
void UsersDialog::itemChange(QListWidgetItem *item) {
139 ✔
460
  if (!item) {
139 ✔
461
    return;
80 ✔
462
  }
463
  bool ok = false;
139 ✔
464
  const int index = item->data(Qt::UserRole).toInt(&ok);
139 ✔
465
  if (!ok) {
139 ✔
466
    qCWarning(lcQtPass)
158 ✔
467
        << "UsersDialog::itemChange: invalid user index data for item";
79 ✔
468
    return;
79 ✔
469
  }
470
  if (index < 0 || index >= m_userList.size()) {
60 ✔
471
    qCWarning(lcQtPass) << "UsersDialog::itemChange: user index out of range:"
2 ✔
472
                        << index << "valid range is [0,"
1 ✔
473
                        << (m_userList.size() - 1) << "]";
1 ✔
474
    return;
1 ✔
475
  }
476
  m_userList[index].enabled = item->checkState() == Qt::Checked;
59 ✔
477
  updateOkButton();
59 ✔
478
}
479

480
void UsersDialog::populateList(const QString &filter) {
84 ✔
481
  // Invalidate cached datetime so expiry checks use fresh current time
482
  m_cachedDateTimeValid = false;
84 ✔
483

484
  QString patternString = "*" + filter + "*";
84 ✔
485
  if (m_cachedPatternString != patternString) {
84 ✔
486
    // A user ID is not a path: "*" and "?" must match a "/" as well, or a
487
    // key named "ACME A/S" or "(dev/ops)" drops out of the search and stays
488
    // ticked unseen while the listed rows are unticked.
489
    QRegularExpression re(
490
        QRegularExpression::wildcardToRegularExpression(
150 ✔
491
            patternString, QRegularExpression::NonPathWildcardConversion),
492
        QRegularExpression::CaseInsensitiveOption);
75 ✔
493
    if (re.isValid()) {
75 ✔
494
      m_cachedNameFilter = re;
75 ✔
495
      m_cachedPatternString = patternString;
75 ✔
496
    }
497
  }
75 ✔
498
  const QRegularExpression &nameFilter = m_cachedNameFilter;
84 ✔
499
  // Sorted once at the end: with sorting on, each badge and tick below
500
  // re-sorted every row added so far, and a .gpg-id of thousands of
501
  // unknown recipients kept the dialog from opening for minutes.
502
  ui->listWidget->setSortingEnabled(false);
84 ✔
503
  ui->listWidget->clear();
84 ✔
504

505
  for (int i = 0; i < m_userList.size(); ++i) {
6,327 ✔
506
    const auto &user = m_userList.at(i);
507
    if (!passesFilter(user, filter, nameFilter)) {
6,243 ✔
508
      continue;
27 ✔
509
    }
510

511
    auto *item = new QListWidgetItem(buildUserText(user), ui->listWidget);
6,216 ✔
512
    applyUserStyling(item, user);
6,216 ✔
513
    item->setCheckState(user.enabled ? Qt::Checked : Qt::Unchecked);
6,297 ✔
514
    item->setData(Qt::UserRole, QVariant::fromValue(i));
6,216 ✔
515
    ui->listWidget->addItem(item);
6,216 ✔
516
  }
517
  // setSortingEnabled() only sets the flag; sortItems() sorts.
518
  ui->listWidget->sortItems();
84 ✔
519
  ui->listWidget->setSortingEnabled(true);
84 ✔
520
  updateOkButton();
84 ✔
521
}
84 ✔
522

523
bool UsersDialog::passesFilter(const UserInfo &user, const QString &filter,
6,243 ✔
524
                               const QRegularExpression &nameFilter) const {
525
  if (!filter.isEmpty() && !nameFilter.match(user.name).hasMatch()) {
6,257 ✔
526
    return false;
527
  }
528
  // A ticked key is one the folder is encrypted to: it is shown whatever
529
  // its state, or an expired or missing recipient stays in .gpg-id unseen and
530
  // cannot be unticked. "Show unusable keys" is about keys to add. A line
531
  // listed unticked without a lookup is shown too: OK would drop it unseen.
532
  if (user.enabled || ui->checkBox->isChecked() ||
6,229 ✔
533
      m_notLookedUp.contains(user.key_id)) {
85 ✔
534
    return true;
6,145 ✔
535
  }
536
  return user.isValid() && !isUserExpired(user);
76 ✔
537
}
538

539
auto UsersDialog::isUserExpired(const UserInfo &user) const -> bool {
6,292 ✔
540
  if (!m_cachedDateTimeValid) {
6,292 ✔
541
    m_cachedCurrentDateTime = QDateTime::currentDateTime();
81 ✔
542
    m_cachedDateTimeValid = true;
81 ✔
543
  }
544
  // gpg marks a key it already judged expired with validity 'e'.
545
  return user.validity == 'e' ||
12,582 ✔
546
         (user.expiry.isValid() && m_cachedCurrentDateTime > user.expiry);
6,299 ✔
547
}
548

549
namespace {
550
/**
551
 * @brief Text cut to a length a list row can draw at once.
552
 *
553
 * A .gpg-id line no key answers to is shown as written, up to the 1 MiB the
554
 * list may hold: Qt elided such a row on every paint in time quadratic in
555
 * its tabs and script changes, and the dialog hung for minutes. No user ID
556
 * or key ID is this long.
557
 * @param text A user ID or key ID.
558
 * @return The text, or its first 256 characters followed by an ellipsis;
559
 *         a surrogate pair is never split.
560
 */
561
auto shortened(const QString &text) -> QString {
12,432 ✔
562
  constexpr qsizetype kMaxShown = 256;
563
  if (text.size() <= kMaxShown) {
12,432 ✔
564
    return text;
565
  }
566
  qsizetype cut = kMaxShown;
567
  if (text.at(cut - 1).isHighSurrogate()) {
1 ✔
568
    --cut;
569
  }
570
  return text.left(cut) + QChar(0x2026);
2 ✔
571
}
572
} // namespace
573

574
QString UsersDialog::buildUserText(const UserInfo &user) const {
6,216 ✔
575
  // One line for the user ID: a line separator in it (gpg escapes only
576
  // ASCII) drew a line that looked like the key's fingerprint.
577
  // The key ID too: a recipient no key answers to is the .gpg-id line as
578
  // written, which may hold the same separators.
579
  QString text = Util::displayable(shortened(user.name), false) + "\n" +
12,432 ✔
580
                 Util::displayable(shortened(user.key_id), false);
12,432 ✔
581
  if (user.created.isValid()) {
6,216 ✔
582
    text += " " + tr("created") + " " +
298 ✔
583
            QLocale::system().toString(user.created, QLocale::ShortFormat);
447 ✔
584
  }
585
  if (user.expiry.isValid()) {
6,216 ✔
586
    text += " " + tr("expires") + " " +
12 ✔
587
            QLocale::system().toString(user.expiry, QLocale::ShortFormat);
18 ✔
588
  }
589
  return text;
6,216 ✔
590
}
591

592
void UsersDialog::applyUserStyling(QListWidgetItem *item,
6,216 ✔
593
                                   const UserInfo &user) const {
594
  const QString originalText = item->text();
6,216 ✔
595
  // Status badge first: an own key can be expired too, and then the marker
596
  // matters more than the "you can decrypt with this" colour.
597
  bool badged = true;
598
  // Expired before invalid: gpg gives an expired key validity 'e', which is
599
  // not a valid one, and "expired" says what to do about it.
600
  if (isUserExpired(user)) {
6,216 ✔
601
    // A lone dark-red foreground is unreadable on dark themes, and gpg
602
    // refuses to encrypt to expired keys anyway.
603
    item->setBackground(Qt::darkRed);
6 ✔
604
    item->setForeground(Qt::white);
6 ✔
605
    item->setText(tr("[EXPIRED] ") + originalText);
12 ✔
606
  } else if (!user.isValid()) {
607
    item->setBackground(Qt::darkRed);
6,070 ✔
608
    item->setForeground(Qt::white);
6,070 ✔
609
    item->setText(tr("[INVALID] ") + originalText);
12,140 ✔
610
  } else if (!user.fullyValid()) {
140 ✔
611
    item->setBackground(Qt::darkYellow);
7 ✔
612
    item->setForeground(Qt::white);
7 ✔
613
    item->setText(tr("[PARTIAL] ") + originalText);
14 ✔
614
  } else {
615
    item->setText(originalText);
133 ✔
616
    badged = false;
617
  }
618
  if (user.have_secret) {
6,216 ✔
619
    if (!badged) {
7 ✔
620
      item->setForeground(QApplication::palette().color(QPalette::Link));
14 ✔
621
    }
622
    QFont font = item->font();
7 ✔
623
    font.setBold(true);
624
    item->setFont(font);
7 ✔
625
  }
7 ✔
626
}
6,216 ✔
627

628
void UsersDialog::on_lineEdit_textChanged(const QString &filter) {
14 ✔
629
  populateList(filter);
14 ✔
630
}
14 ✔
631

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

634
void UsersDialog::selectImportedKey(const QString &importedKey) {
2 ✔
635
  // The stored key_id, not the item text.
636
  for (int i = 0; i < ui->listWidget->count(); ++i) {
4 ✔
637
    QListWidgetItem *item = ui->listWidget->item(i);
4 ✔
638
    bool ok = false;
4 ✔
639
    const int idx = item != nullptr ? item->data(Qt::UserRole).toInt(&ok) : -1;
4 ✔
640
    if (ok && idx >= 0 && idx < m_userList.size() &&
8 ✔
641
        !m_userList[idx].key_id.isEmpty() &&
8 ✔
642
        keyIdsMatch(m_userList[idx].key_id, importedKey)) {
4 ✔
643
      ui->listWidget->setCurrentItem(item);
2 ✔
644
      return;
2 ✔
645
    }
646
  }
647
}
648

649
void UsersDialog::on_importKeyButton_clicked() {
3 ✔
650
  ImportKeyDialog dialog(m_gpgExe, this);
3 ✔
651
  if (dialog.exec() != QDialog::Accepted) {
3 ✔
652
    return;
653
  }
654

655
  // Non-empty after Accepted, but an empty id would make the endsWith()
656
  // below match the first listed key.
657
  const QString importedKey = dialog.importedKeyId();
2 ✔
658
  if (importedKey.isEmpty()) {
2 ✔
659
    return;
660
  }
661

662
  // loadGpgKeys() rebuilds the key list from the keyring and drops every tick.
663
  // Remember which recipients were selected (the .gpg-id list and the user's
664
  // own ticks, including any "key not found" rows) and re-apply them after, so
665
  // importing a key does not silently remove the other recipients.
666
  QStringList selected;
2 ✔
667
  for (const UserInfo &user : std::as_const(m_userList)) {
4 ✔
668
    if (user.enabled) {
2 ✔
669
      selected.append(user.key_id);
2 ✔
670
    }
671
  }
672

673
  if (!loadGpgKeys()) {
2 ✔
674
    return;
675
  }
676

677
  // Re-apply the remembered selection. Most saved identifiers are a key ID that
678
  // is in the rebuilt list, so match those exactly first (no gpg lookup). An
679
  // identifier that does not match a row is one that was listed as "key not
680
  // found" - a short ID or email that gpg could not resolve, or whose key has
681
  // just been imported and now shows under its fingerprint. Hand those to
682
  // selectRecipients(), which resolves each against the refreshed keyring,
683
  // ticks the matching row, and re-adds a "key not found" row for any that
684
  // still does not resolve.
685
  QStringList unresolved;
2 ✔
686
  for (const QString &keyId : std::as_const(selected)) {
4 ✔
687
    bool matched = false;
688
    for (UserInfo &user : m_userList) {
6 ✔
689
      if (user.key_id == keyId) {
4 ✔
690
        user.enabled = true;
2 ✔
691
        matched = true;
692
      }
693
    }
694
    if (!matched) {
2 ✔
695
      unresolved.append(keyId);
696
    }
697
  }
698
  if (!unresolved.isEmpty()) {
2 ✔
699
    selectRecipients(unresolved);
×
700
  }
701

702
  // Clear the filter so the just-imported key is visible. setText("") still
703
  // emits textChanged once, so don't double-populate.
704
  {
705
    const QSignalBlocker blocker(ui->lineEdit);
2 ✔
706
    ui->lineEdit->clear();
2 ✔
707
  }
2 ✔
708
  populateList(QString());
2 ✔
709

710
  selectImportedKey(importedKey);
2 ✔
711
}
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