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

IJHack / QtPass / 45519765640

25 Nov 2026 12:39AM UTC coverage: 94.876% (+0.06%) from 94.819%
45519765640

push

github

web-flow
Users dialog: no OK over a list that changed while it was open (#2329)

UsersDialog read the folder's recipient list once, in the constructor,
and accept() handed the whole selection to Init(). A newer list that
arrived while the dialog was open (a pull the 30 s watchdog let run on
under it, a sync, a pull in a terminal) was overwritten by the old one
plus the user's change: someone just removed became a recipient again,
signed as the next generation and committed on top of the removal.

loadRecipients() now keeps the state and recipients it read, and
accept() reads the list again and refuses, with a message to reopen
the dialog, when either differs. Pass::initIfUnchanged() hands the
list as read down to Init(), and each backend compares it again at
the last point before the write: ImitatePass right before
writeGpgIdFile(), RealPass right before it queues pass init, and only
with nothing else queued so pass init starts at once. When the backend
refuses there, the dialog stays open with its selection.
ImitatePass::Init() also refuses while a pull is queued, as
RealPass::Init() already did.

Scan: ANT-2026-W7W7B1M9

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

39 of 40 new or added lines in 4 files covered. (97.5%)

9962 of 10500 relevant lines covered (94.88%)

21976.51 hits per line

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

96.94
/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,
59 ✔
40
                         QWidget *parent)
59 ✔
41
    : UsersDialog(pass, s, std::move(dir), Preselect::FromList, parent) {}
118 ✔
42

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

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

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

61
  connectSignals();
62 ✔
62
}
×
63

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

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

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

80
auto UsersDialog::loadGpgKeys() -> bool {
65 ✔
81
  QList<UserInfo> users = m_pass->listKeys();
65 ✔
82
  if (users.isEmpty()) {
65 ✔
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);
64 ✔
90

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

95
void UsersDialog::markSecretKeys(QList<UserInfo> &users) {
64 ✔
96
  QList<UserInfo> secret_keys = m_pass->listKeys("", true);
128 ✔
97
  QSet<QString> secretKeyIds;
98
  for (const UserInfo &sec : secret_keys) {
69 ✔
99
    secretKeyIds.insert(sec.key_id);
5 ✔
100
  }
101
  for (auto &user : users) {
187 ✔
102
    if (secretKeyIds.contains(user.key_id)) {
123 ✔
103
      user.have_secret = true;
5 ✔
104
    }
105
  }
106
}
64 ✔
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() {
62 ✔
143
  // The walk re-encryption takes: hidden folders and links are not entered.
144
  const QString dir = QDir::cleanPath(m_dir);
62 ✔
145
  if (!QFileInfo(dir).isDir()) {
62 ✔
146
    return;
147
  }
148
  QStringList unlisted;
62 ✔
149
  const QStringList lists = Util::regularFilesUnder(
186 ✔
150
      dir, {QStringLiteral(".gpg-id")}, nullptr, true, &unlisted);
124 ✔
151
  const auto relative = [&dir](const QString &folder) {
10 ✔
152
    return QDir::toNativeSeparators(QDir(dir).relativeFilePath(folder));
20 ✔
153
  };
62 ✔
154
  QStringList nested;
62 ✔
155
  for (const QString &list : lists) {
113 ✔
156
    const QString folder = QFileInfo(list).path();
51 ✔
157
    if (QDir::cleanPath(folder) != dir) {
102 ✔
158
      nested << relative(folder);
18 ✔
159
    }
160
  }
161
  QStringList unread;
62 ✔
162
  for (const QString &folder : std::as_const(unlisted)) {
63 ✔
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;
62 ✔
174
  if (!nested.isEmpty()) {
62 ✔
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()) {
62 ✔
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()) {
62 ✔
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 {
394 ✔
200
  const QString trimmed = id.trimmed();
201
  return (trimmed.startsWith(QLatin1String("0x"), Qt::CaseInsensitive)
394 ✔
202
              ? trimmed.mid(2)
788 ✔
203
              : trimmed)
204
      .toUpper();
394 ✔
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 {
197 ✔
211
  static const QRegularExpression hexId(QStringLiteral("^[0-9A-F]{8,}$"));
204 ✔
212
  const QString a = normalisedKeyId(first);
197 ✔
213
  const QString b = normalisedKeyId(second);
197 ✔
214
  if (!hexId.match(a).hasMatch() || !hexId.match(b).hasMatch()) {
394 ✔
215
    return false;
216
  }
217
  if (a.size() == 64) {
197 ✔
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) {
181 ✔
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);
181 ✔
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,281 ✔
232
  static const QRegularExpression hexLine(
233
      QStringLiteral("^(?:0[xX])?([0-9A-Fa-f]+)!?$"));
18,287 ✔
234
  const QRegularExpressionMatch match = hexLine.match(recipient.trimmed());
18,281 ✔
235
  if (!match.hasMatch()) {
18,281 ✔
236
    return {};
18,042 ✔
237
  }
238
  const QString digits = match.captured(1);
239 ✔
239
  const qsizetype size = digits.size();
240
  return size == 8 || size == 16 || size == 40 || size == 64 ? digits
239 ✔
241
                                                             : QString();
×
242
}
18,281 ✔
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 ✔
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 ✔
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 ✔
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,138 ✔
282
  return !keyIdOfLine(recipient).isEmpty() ||
12,168 ✔
283
         !nameTermOfLine(recipient).isEmpty();
12,168 ✔
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,143 ✔
294
  const QString keyId = keyIdOfLine(recipient);
12,143 ✔
295
  if (!keyId.isEmpty()) {
12,143 ✔
296
    return keyIdsMatch(key.key_id, keyId) ||
131 ✔
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) {
39 ✔
316
  // A line listed twice is one recipient, and one row.
317
  QStringList recipients;
39 ✔
318
  QSet<QString> seen;
319
  for (const QString &line : listed) {
6,151 ✔
320
    if (!seen.contains(line)) {
6,112 ✔
321
      seen.insert(line);
6,111 ✔
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);
78 ✔
328
  if (resolved.isEmpty() && recipients.size() > 1) {
39 ✔
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;
39 ✔
350
  QSet<QString> notLookedUp;
351
  for (const QString &recipient : std::as_const(recipients)) {
6,150 ✔
352
    if (judgedLocally(recipient)) {
6,111 ✔
353
      continue;
6,095 ✔
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) {
114 ✔
365
    if (std::any_of(resolved.cbegin(), resolved.cend(),
75 ✔
366
                    [&user](const UserInfo &key) {
367
                      return key.key_id == user.key_id;
93 ✔
368
                    })) {
369
      user.enabled = true;
51 ✔
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,150 ✔
378
    UserInfo missing;
6,111 ✔
379
    missing.key_id = recipient;
6,111 ✔
380
    if (notLookedUp.contains(recipient)) {
6,111 ✔
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,110 ✔
387
    const bool found = cached != perLineHasKey.constEnd()
388
                           ? cached.value()
16 ✔
389
                           : std::any_of(resolved.cbegin(), resolved.cend(),
6,094 ✔
390
                                         [&recipient](const UserInfo &key) {
391
                                           return answersTo(key, recipient);
12,143 ✔
392
                                         });
6,094 ✔
393
    if (!found) {
6,110 ✔
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,111 ✔
399
}
78 ✔
400

401
void UsersDialog::loadRecipients() {
62 ✔
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) {
62 ✔
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);
58 ✔
412
  m_listRead = true;
58 ✔
413
  m_readState = static_cast<int>(loaded.state);
58 ✔
414
  m_readRecipients = loaded.recipients;
415
  if (!loaded.warning.isEmpty()) {
58 ✔
416
    showRecipientWarning(loaded.warning);
16 ✔
417
  }
418
  // A folder without .gpg-id (new store, new profile) has no recipients yet;
419
  // listKeys() with no filter would return the whole keyring, preselected.
420
  if (loaded.state != Pass::RecipientsForEditing::State::Rejected &&
58 ✔
421
      !loaded.recipients.isEmpty()) {
422
    selectRecipients(loaded.recipients);
39 ✔
423
  }
424
}
425

426
UsersDialog::~UsersDialog() = default;
126 ✔
427

428
auto UsersDialog::listChangedSinceRead() const -> bool {
8 ✔
429
  const Pass::RecipientsForEditing now =
430
      m_pass->recipientsForEditing(m_dir, m_passStore);
8 ✔
431
  return static_cast<int>(now.state) != m_readState ||
8 ✔
432
         now.recipients != m_readRecipients;
8 ✔
433
}
434

435
void UsersDialog::accept() {
12 ✔
436
  if (!hasSelection()) {
12 ✔
437
    // Nothing to encrypt to: an empty .gpg-id would make every insert fail
438
    // and the wizard never offers this dialog again once the file exists.
439
    return;
440
  }
441
  // OK writes the whole selection, ticked from the list as it was read. A
442
  // newer list that arrived meanwhile (a pull the watchdog let run on under
443
  // the dialog, a sync) would be overwritten by the old one plus the user's
444
  // change: someone just removed came back, signed as the next generation.
445
  if (m_listRead && listChangedSinceRead()) {
10 ✔
446
    QMessageBox::warning(
2 ✔
447
        this, tr("Recipients not changed"),
1 ✔
448
        tr("The recipient list of this folder changed while this dialog was "
1 ✔
449
           "open, for example through an update from Git. OK would have "
450
           "written the old list back. Close this dialog and open it again "
451
           "to see the new list."));
452
    return;
1 ✔
453
  }
454
  if (m_initOnAccept) {
9 ✔
455
    if (m_listRead) {
6 ✔
456
      // Compared again by the backend at the last point before it writes:
457
      // a pull in a terminal can still land between here and there.
458
      Pass::RecipientsForEditing read;
6 ✔
459
      read.state = static_cast<Pass::RecipientsForEditing::State>(m_readState);
6 ✔
460
      read.recipients = m_readRecipients;
461
      // Refused there (changed after all, or another operation runs): the
462
      // dialog stays open with the selection, as the message asks to save
463
      // again.
464
      if (!m_pass->initIfUnchanged(m_dir, m_userList, m_dir, m_passStore,
6 ✔
465
                                   read)) {
466
        return;
467
      }
468
    } else {
NEW
469
      m_pass->Init(m_dir, m_userList);
×
470
    }
471
  }
472

473
  QDialog::accept();
8 ✔
474
}
475

476
auto UsersDialog::hasSelection() const -> bool {
161 ✔
477
  return std::any_of(m_userList.cbegin(), m_userList.cend(),
478
                     [](const UserInfo &user) { return user.enabled; });
240 ✔
479
}
480

481
void UsersDialog::updateOkButton() {
146 ✔
482
  if (auto *ok = ui->buttonBox->button(QDialogButtonBox::Ok)) {
146 ✔
483
    ok->setEnabled(hasSelection());
146 ✔
484
  }
485
}
146 ✔
486

487
void UsersDialog::keyPressEvent(QKeyEvent *event) {
1 ✔
488
  switch (event->key()) {
1 ✔
489
  case Qt::Key_Escape:
1 ✔
490
    ui->lineEdit->clear();
1 ✔
491
    break;
1 ✔
492
  default:
493
    break;
494
  }
495
}
1 ✔
496

497
void UsersDialog::itemChange(QListWidgetItem *item) {
139 ✔
498
  if (!item) {
139 ✔
499
    return;
80 ✔
500
  }
501
  bool ok = false;
139 ✔
502
  const int index = item->data(Qt::UserRole).toInt(&ok);
139 ✔
503
  if (!ok) {
139 ✔
504
    qCWarning(lcQtPass)
158 ✔
505
        << "UsersDialog::itemChange: invalid user index data for item";
79 ✔
506
    return;
79 ✔
507
  }
508
  if (index < 0 || index >= m_userList.size()) {
60 ✔
509
    qCWarning(lcQtPass) << "UsersDialog::itemChange: user index out of range:"
2 ✔
510
                        << index << "valid range is [0,"
1 ✔
511
                        << (m_userList.size() - 1) << "]";
1 ✔
512
    return;
1 ✔
513
  }
514
  m_userList[index].enabled = item->checkState() == Qt::Checked;
59 ✔
515
  updateOkButton();
59 ✔
516
}
517

518
void UsersDialog::populateList(const QString &filter) {
87 ✔
519
  // Invalidate cached datetime so expiry checks use fresh current time
520
  m_cachedDateTimeValid = false;
87 ✔
521

522
  QString patternString = "*" + filter + "*";
87 ✔
523
  if (m_cachedPatternString != patternString) {
87 ✔
524
    // A user ID is not a path: "*" and "?" must match a "/" as well, or a
525
    // key named "ACME A/S" or "(dev/ops)" drops out of the search and stays
526
    // ticked unseen while the listed rows are unticked.
527
    QRegularExpression re(
528
        QRegularExpression::wildcardToRegularExpression(
156 ✔
529
            patternString, QRegularExpression::NonPathWildcardConversion),
530
        QRegularExpression::CaseInsensitiveOption);
78 ✔
531
    if (re.isValid()) {
78 ✔
532
      m_cachedNameFilter = re;
78 ✔
533
      m_cachedPatternString = patternString;
78 ✔
534
    }
535
  }
78 ✔
536
  const QRegularExpression &nameFilter = m_cachedNameFilter;
87 ✔
537
  // Sorted once at the end: with sorting on, each badge and tick below
538
  // re-sorted every row added so far, and a .gpg-id of thousands of
539
  // unknown recipients kept the dialog from opening for minutes.
540
  ui->listWidget->setSortingEnabled(false);
87 ✔
541
  ui->listWidget->clear();
87 ✔
542

543
  for (int i = 0; i < m_userList.size(); ++i) {
6,336 ✔
544
    const auto &user = m_userList.at(i);
545
    if (!passesFilter(user, filter, nameFilter)) {
6,249 ✔
546
      continue;
27 ✔
547
    }
548

549
    auto *item = new QListWidgetItem(buildUserText(user), ui->listWidget);
6,222 ✔
550
    applyUserStyling(item, user);
6,222 ✔
551
    item->setCheckState(user.enabled ? Qt::Checked : Qt::Unchecked);
6,306 ✔
552
    item->setData(Qt::UserRole, QVariant::fromValue(i));
6,222 ✔
553
    ui->listWidget->addItem(item);
6,222 ✔
554
  }
555
  // setSortingEnabled() only sets the flag; sortItems() sorts.
556
  ui->listWidget->sortItems();
87 ✔
557
  ui->listWidget->setSortingEnabled(true);
87 ✔
558
  updateOkButton();
87 ✔
559
}
87 ✔
560

561
bool UsersDialog::passesFilter(const UserInfo &user, const QString &filter,
6,249 ✔
562
                               const QRegularExpression &nameFilter) const {
563
  if (!filter.isEmpty() && !nameFilter.match(user.name).hasMatch()) {
6,263 ✔
564
    return false;
565
  }
566
  // A ticked key is one the folder is encrypted to: it is shown whatever
567
  // its state, or an expired or missing recipient stays in .gpg-id unseen and
568
  // cannot be unticked. "Show unusable keys" is about keys to add. A line
569
  // listed unticked without a lookup is shown too: OK would drop it unseen.
570
  if (user.enabled || ui->checkBox->isChecked() ||
6,235 ✔
571
      m_notLookedUp.contains(user.key_id)) {
88 ✔
572
    return true;
6,148 ✔
573
  }
574
  return user.isValid() && !isUserExpired(user);
79 ✔
575
}
576

577
auto UsersDialog::isUserExpired(const UserInfo &user) const -> bool {
6,301 ✔
578
  if (!m_cachedDateTimeValid) {
6,301 ✔
579
    m_cachedCurrentDateTime = QDateTime::currentDateTime();
84 ✔
580
    m_cachedDateTimeValid = true;
84 ✔
581
  }
582
  // gpg marks a key it already judged expired with validity 'e'.
583
  return user.validity == 'e' ||
12,600 ✔
584
         (user.expiry.isValid() && m_cachedCurrentDateTime > user.expiry);
6,308 ✔
585
}
586

587
namespace {
588
/**
589
 * @brief Text cut to a length a list row can draw at once.
590
 *
591
 * A .gpg-id line no key answers to is shown as written, up to the 1 MiB the
592
 * list may hold: Qt elided such a row on every paint in time quadratic in
593
 * its tabs and script changes, and the dialog hung for minutes. No user ID
594
 * or key ID is this long.
595
 * @param text A user ID or key ID.
596
 * @return The text, or its first 256 characters followed by an ellipsis;
597
 *         a surrogate pair is never split.
598
 */
599
auto shortened(const QString &text) -> QString {
12,444 ✔
600
  constexpr qsizetype kMaxShown = 256;
601
  if (text.size() <= kMaxShown) {
12,444 ✔
602
    return text;
603
  }
604
  qsizetype cut = kMaxShown;
605
  if (text.at(cut - 1).isHighSurrogate()) {
1 ✔
606
    --cut;
607
  }
608
  return text.left(cut) + QChar(0x2026);
2 ✔
609
}
610
} // namespace
611

612
QString UsersDialog::buildUserText(const UserInfo &user) const {
6,222 ✔
613
  // One line for the user ID: a line separator in it (gpg escapes only
614
  // ASCII) drew a line that looked like the key's fingerprint.
615
  // The key ID too: a recipient no key answers to is the .gpg-id line as
616
  // written, which may hold the same separators.
617
  QString text = Util::displayable(shortened(user.name), false) + "\n" +
12,444 ✔
618
                 Util::displayable(shortened(user.key_id), false);
12,444 ✔
619
  if (user.created.isValid()) {
6,222 ✔
620
    text += " " + tr("created") + " " +
310 ✔
621
            QLocale::system().toString(user.created, QLocale::ShortFormat);
465 ✔
622
  }
623
  if (user.expiry.isValid()) {
6,222 ✔
624
    text += " " + tr("expires") + " " +
12 ✔
625
            QLocale::system().toString(user.expiry, QLocale::ShortFormat);
18 ✔
626
  }
627
  return text;
6,222 ✔
628
}
629

630
void UsersDialog::applyUserStyling(QListWidgetItem *item,
6,222 ✔
631
                                   const UserInfo &user) const {
632
  const QString originalText = item->text();
6,222 ✔
633
  // Status badge first: an own key can be expired too, and then the marker
634
  // matters more than the "you can decrypt with this" colour.
635
  bool badged = true;
636
  // Expired before invalid: gpg gives an expired key validity 'e', which is
637
  // not a valid one, and "expired" says what to do about it.
638
  if (isUserExpired(user)) {
6,222 ✔
639
    // A lone dark-red foreground is unreadable on dark themes, and gpg
640
    // refuses to encrypt to expired keys anyway.
641
    item->setBackground(Qt::darkRed);
6 ✔
642
    item->setForeground(Qt::white);
6 ✔
643
    item->setText(tr("[EXPIRED] ") + originalText);
12 ✔
644
  } else if (!user.isValid()) {
645
    item->setBackground(Qt::darkRed);
6,070 ✔
646
    item->setForeground(Qt::white);
6,070 ✔
647
    item->setText(tr("[INVALID] ") + originalText);
12,140 ✔
648
  } else if (!user.fullyValid()) {
146 ✔
649
    item->setBackground(Qt::darkYellow);
7 ✔
650
    item->setForeground(Qt::white);
7 ✔
651
    item->setText(tr("[PARTIAL] ") + originalText);
14 ✔
652
  } else {
653
    item->setText(originalText);
139 ✔
654
    badged = false;
655
  }
656
  if (user.have_secret) {
6,222 ✔
657
    if (!badged) {
7 ✔
658
      item->setForeground(QApplication::palette().color(QPalette::Link));
14 ✔
659
    }
660
    QFont font = item->font();
7 ✔
661
    font.setBold(true);
662
    item->setFont(font);
7 ✔
663
  }
7 ✔
664
}
6,222 ✔
665

666
void UsersDialog::on_lineEdit_textChanged(const QString &filter) {
14 ✔
667
  populateList(filter);
14 ✔
668
}
14 ✔
669

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

672
void UsersDialog::selectImportedKey(const QString &importedKey) {
2 ✔
673
  // The stored key_id, not the item text.
674
  for (int i = 0; i < ui->listWidget->count(); ++i) {
4 ✔
675
    QListWidgetItem *item = ui->listWidget->item(i);
4 ✔
676
    bool ok = false;
4 ✔
677
    const int idx = item != nullptr ? item->data(Qt::UserRole).toInt(&ok) : -1;
4 ✔
678
    if (ok && idx >= 0 && idx < m_userList.size() &&
8 ✔
679
        !m_userList[idx].key_id.isEmpty() &&
8 ✔
680
        keyIdsMatch(m_userList[idx].key_id, importedKey)) {
4 ✔
681
      ui->listWidget->setCurrentItem(item);
2 ✔
682
      return;
2 ✔
683
    }
684
  }
685
}
686

687
void UsersDialog::on_importKeyButton_clicked() {
3 ✔
688
  ImportKeyDialog dialog(m_gpgExe, this);
3 ✔
689
  if (dialog.exec() != QDialog::Accepted) {
3 ✔
690
    return;
691
  }
692

693
  // Non-empty after Accepted, but an empty id would make the endsWith()
694
  // below match the first listed key.
695
  const QString importedKey = dialog.importedKeyId();
2 ✔
696
  if (importedKey.isEmpty()) {
2 ✔
697
    return;
698
  }
699

700
  // loadGpgKeys() rebuilds the key list from the keyring and drops every tick.
701
  // Remember which recipients were selected (the .gpg-id list and the user's
702
  // own ticks, including any "key not found" rows) and re-apply them after, so
703
  // importing a key does not silently remove the other recipients.
704
  QStringList selected;
2 ✔
705
  for (const UserInfo &user : std::as_const(m_userList)) {
4 ✔
706
    if (user.enabled) {
2 ✔
707
      selected.append(user.key_id);
2 ✔
708
    }
709
  }
710

711
  if (!loadGpgKeys()) {
2 ✔
712
    return;
713
  }
714

715
  // Re-apply the remembered selection. Most saved identifiers are a key ID that
716
  // is in the rebuilt list, so match those exactly first (no gpg lookup). An
717
  // identifier that does not match a row is one that was listed as "key not
718
  // found" - a short ID or email that gpg could not resolve, or whose key has
719
  // just been imported and now shows under its fingerprint. Hand those to
720
  // selectRecipients(), which resolves each against the refreshed keyring,
721
  // ticks the matching row, and re-adds a "key not found" row for any that
722
  // still does not resolve.
723
  QStringList unresolved;
2 ✔
724
  for (const QString &keyId : std::as_const(selected)) {
4 ✔
725
    bool matched = false;
726
    for (UserInfo &user : m_userList) {
6 ✔
727
      if (user.key_id == keyId) {
4 ✔
728
        user.enabled = true;
2 ✔
729
        matched = true;
730
      }
731
    }
732
    if (!matched) {
2 ✔
733
      unresolved.append(keyId);
734
    }
735
  }
736
  if (!unresolved.isEmpty()) {
2 ✔
737
    selectRecipients(unresolved);
×
738
  }
739

740
  // Clear the filter so the just-imported key is visible. setText("") still
741
  // emits textChanged once, so don't double-populate.
742
  {
743
    const QSignalBlocker blocker(ui->lineEdit);
2 ✔
744
    ui->lineEdit->clear();
2 ✔
745
  }
2 ✔
746
  populateList(QString());
2 ✔
747

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