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

IJHack / QtPass / 43511974237

13 Nov 2026 09:34PM UTC coverage: 92.717% (-0.001%) from 92.718%
43511974237

push

github

web-flow
Users dialog: keep the recipient selection when importing a key (#2145)

* Users dialog: keep the recipient selection when importing a key

"Import key..." in the Users dialog reloaded the key list with loadGpgKeys(),
which rebuilds it from the keyring and drops every tick - the .gpg-id
recipients and the user's own ticks alike. If the user then ticked only the
imported key and pressed OK, the saved .gpg-id named that key alone and the
other recipients (including the user's own key) lost access.

on_importKeyButton_clicked() now remembers the selected recipients before the
reload and re-applies them by exact key ID afterwards, re-adding any that are
no longer in the keyring as a "key not found" row. Importing only adds the new
key's row; it still does not tick it.

The existing import test is updated: it ticks a recipient before importing and
checks the tick survives (it failed before the change).

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

* Users dialog: resolve short-id/email recipients when re-applying on import

Per review: a .gpg-id recipient named by a short key ID or email that gpg
could not resolve is stored verbatim as a "key not found" row; importing its
key makes the refreshed row carry the fingerprint, which an exact match
misses. Match saved identifiers by key ID first, then hand any that do not
match to selectRecipients(), which resolves them against the refreshed
keyring and ticks the now-present row (or re-adds a not-found row).

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

---------

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

11 of 12 new or added lines in 1 file covered. (91.67%)

10477 of 11300 relevant lines covered (92.72%)

406.7 hits per line

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

98.31
/src/usersdialog.cpp
1
// SPDX-FileCopyrightText: 2015 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
#include "usersdialog.h"
4
#include "importkeydialog.h"
5
#include "pass.h"
6
#include "qtpasssettings.h"
7
#include "ui_usersdialog.h"
8
#include "windowstatestore.h"
9
#include <QApplication>
10
#include <QDateTime>
11
#include <QDialogButtonBox>
12
#include <QFont>
13
#include <QKeyEvent>
14
#include <QLabel>
15
#include <QLineEdit>
16
#include <QListWidget>
17
#include <QMessageBox>
18
#include <QPalette>
19
#include <QPushButton>
20
#include <QRegularExpression>
21
#include <QSet>
22
#include <QSignalBlocker>
23
#include <QWidget>
24
#include <algorithm>
25
#include <utility>
26

27
#include "qtpasslogging.h"
28
UsersDialog::UsersDialog(Pass *pass, const AppSettings &s, QString dir,
35 ✔
29
                         QWidget *parent)
35 ✔
30
    : UsersDialog(pass, s, std::move(dir), Preselect::FromList, parent) {}
70 ✔
31

32
UsersDialog::UsersDialog(Pass *pass, const AppSettings &s, QString dir,
38 ✔
33
                         Preselect preselect, QWidget *parent)
38 ✔
34
    : QDialog(parent), ui(new Ui::UsersDialog), m_pass(pass),
38 ✔
35
      m_passStore(s.passStore), m_gpgExe(s.gpgExecutable),
36
      m_dir(std::move(dir)), m_preselect(preselect) {
76 ✔
37
  Q_ASSERT(pass);
38
  ui->setupUi(this);
38 ✔
39

40
  restoreDialogState();
38 ✔
41
  if (!loadGpgKeys()) {
38 ✔
42
    connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
1 ✔
43
    return;
1 ✔
44
  }
45

46
  loadRecipients();
37 ✔
47
  populateList();
37 ✔
48

49
  connectSignals();
37 ✔
50
}
×
51

52
void UsersDialog::connectSignals() {
37 ✔
53
  connect(ui->buttonBox, &QDialogButtonBox::accepted, this,
37 ✔
54
          &UsersDialog::accept);
37 ✔
55
  connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
37 ✔
56
  connect(ui->listWidget, &QListWidget::itemChanged, this,
37 ✔
57
          &UsersDialog::itemChange);
74 ✔
58
  // importKeyButton is wired via Qt's automatic on_<name>_<signal> mechanism
59
  // already triggered by setupUi().
60

61
  ui->lineEdit->setClearButtonEnabled(true);
37 ✔
62
}
37 ✔
63

64
void UsersDialog::restoreDialogState() {
38 ✔
65
  WindowStateStore::attach(*this, QStringLiteral("usersDialog"));
76 ✔
66
}
38 ✔
67

68
auto UsersDialog::loadGpgKeys() -> bool {
39 ✔
69
  QList<UserInfo> users = m_pass->listKeys();
39 ✔
70
  if (users.isEmpty()) {
39 ✔
71
    QMessageBox::critical(parentWidget(), tr("Keylist missing"),
3 ✔
72
                          tr("Could not fetch list of available GPG keys"));
×
73
    reject();
1 ✔
74
    return false;
75
  }
76

77
  markSecretKeys(users);
38 ✔
78

79
  m_userList = users;
80
  return true;
38 ✔
81
}
82

83
void UsersDialog::markSecretKeys(QList<UserInfo> &users) {
38 ✔
84
  QList<UserInfo> secret_keys = m_pass->listKeys("", true);
76 ✔
85
  QSet<QString> secretKeyIds;
86
  for (const UserInfo &sec : secret_keys) {
43 ✔
87
    secretKeyIds.insert(sec.key_id);
5 ✔
88
  }
89
  for (auto &user : users) {
114 ✔
90
    if (secretKeyIds.contains(user.key_id)) {
76 ✔
91
      user.have_secret = true;
5 ✔
92
    }
93
  }
94
}
38 ✔
95

96
void UsersDialog::showRecipientWarning(const QString &text) {
7 ✔
97
  // Plain text before the text is set: it can quote the store's recipient
98
  // list, which as rich text could make Qt load a file (<img src=...>).
99
  auto *banner = new QLabel(this);
7 ✔
100
  banner->setTextFormat(Qt::PlainText);
7 ✔
101
  banner->setText(text);
7 ✔
102
  banner->setObjectName(QStringLiteral("recipientWarning"));
14 ✔
103
  banner->setWordWrap(true);
7 ✔
104
  // Palette, not a stylesheet colour, so it reads on dark themes too; red as
105
  // ProcessOutputPanel paints error lines.
106
  QFont bold = banner->font();
7 ✔
107
  bold.setBold(true);
108
  banner->setFont(bold);
7 ✔
109
  QPalette palette = banner->palette();
7 ✔
110
  palette.setColor(QPalette::WindowText, QColor(Qt::red));
7 ✔
111
  banner->setPalette(palette);
7 ✔
112
  banner->setContentsMargins(4, 4, 4, 4);
7 ✔
113
  ui->verticalLayout->insertWidget(1, banner);
7 ✔
114
}
7 ✔
115

116
namespace {
117

118
/// A key ID as written anywhere: without a 0x prefix, upper case.
119
auto normalisedKeyId(const QString &id) -> QString {
60 ✔
120
  const QString trimmed = id.trimmed();
121
  return (trimmed.startsWith(QLatin1String("0x"), Qt::CaseInsensitive)
60 ✔
122
              ? trimmed.mid(2)
120 ✔
123
              : trimmed)
124
      .toUpper();
60 ✔
125
}
126

127
/// Whether @p recipient, as a .gpg-id lists it, names @p key the way gpg's
128
/// -r resolves it: a key ID in any length gpg accepts (the key carries its
129
/// fingerprint, the list may carry a long or short ID, a suffix of it, or
130
/// the fingerprint; eight characters is the shortest), or else a name,
131
/// matched case-insensitively as a substring of the UID after gpg's
132
/// "=", "<...>", "@" and "*" markers.
133
auto answersTo(const UserInfo &key, const QString &recipient) -> bool {
35 ✔
134
  static const QRegularExpression hexId(
135
      QStringLiteral("^(0x)?[0-9A-Fa-f]{8,}$"));
38 ✔
136
  if (hexId.match(recipient.trimmed()).hasMatch()) {
70 ✔
137
    const QString id = normalisedKeyId(recipient);
30 ✔
138
    const QString keyId = normalisedKeyId(key.key_id);
30 ✔
139
    return keyId.endsWith(id) || (keyId.size() >= 8 && id.endsWith(keyId));
30 ✔
140
  }
141
  QString term = recipient.trimmed();
142
  if (term.startsWith(u'=') || term.startsWith(u'@') || term.startsWith(u'*')) {
5 ✔
143
    term.remove(0, 1);
×
144
  } else if (term.startsWith(u'<') && term.endsWith(u'>')) {
5 ✔
145
    term = term.mid(1, term.size() - 2);
2 ✔
146
  }
147
  return !term.isEmpty() && key.name.contains(term, Qt::CaseInsensitive);
5 ✔
148
}
149

150
} // namespace
151

152
void UsersDialog::selectRecipients(const QStringList &recipients) {
16 ✔
153
  // One gpg call resolves every recipient, by key ID or by email/UID.
154
  const QList<UserInfo> resolved = m_pass->listKeys(recipients);
16 ✔
155
  for (UserInfo &user : m_userList) {
48 ✔
156
    if (std::any_of(resolved.cbegin(), resolved.cend(),
32 ✔
157
                    [&user](const UserInfo &key) {
158
                      return key.key_id == user.key_id;
45 ✔
159
                    })) {
160
      user.enabled = true;
26 ✔
161
    }
162
  }
163
  // The match is a fast path, not gpg's resolution: a secondary UID or a
164
  // subkey ID resolves in gpg without showing in what it lists. Only what gpg
165
  // itself cannot find is reported missing. Each such check is a blocking gpg
166
  // call on the dialog's way up, so a store with many keys missing from the
167
  // keyring gets a few, and the rest are reported missing unchecked.
168
  constexpr int kMaxLookups = 10;
169
  int lookups = 0;
170
  for (const QString &recipient : recipients) {
39 ✔
171
    const bool found =
172
        std::any_of(resolved.cbegin(), resolved.cend(),
23 ✔
173
                    [&recipient](const UserInfo &key) {
174
                      return answersTo(key, recipient);
35 ✔
175
                    }) ||
23 ✔
176
        (lookups++ < kMaxLookups && !m_pass->listKeys(recipient).isEmpty());
5 ✔
177
    if (!found) {
23 ✔
178
      UserInfo missing;
2 ✔
179
      missing.enabled = true;
2 ✔
180
      missing.key_id = recipient;
2 ✔
181
      missing.name = " ?? " + tr("Key not found in keyring");
4 ✔
182
      m_userList.append(missing);
183
    }
2 ✔
184
  }
185
}
16 ✔
186

187
void UsersDialog::loadRecipients() {
37 ✔
188
  // A store that had no list when it was chosen (a new profile): a list
189
  // that appeared since is nobody's choice, and was read under the active
190
  // backend's signing policy, not the new profile's.
191
  if (m_preselect == Preselect::Nothing) {
37 ✔
192
    return;
3 ✔
193
  }
194
  // Through the backend: with a signing key only a verified list may be
195
  // preselected, since OK signs whatever is selected.
196
  const Pass::RecipientsForEditing loaded =
197
      m_pass->recipientsForEditing(m_dir, m_passStore);
34 ✔
198
  if (!loaded.warning.isEmpty()) {
199
    showRecipientWarning(loaded.warning);
7 ✔
200
  }
201
  // A folder without .gpg-id (new store, new profile) has no recipients yet;
202
  // listKeys() with no filter would return the whole keyring, preselected.
203
  if (loaded.state != Pass::RecipientsForEditing::State::Rejected &&
34 ✔
204
      !loaded.recipients.isEmpty()) {
205
    selectRecipients(loaded.recipients);
16 ✔
206
  }
207
}
208

209
UsersDialog::~UsersDialog() = default;
76 ✔
210

211
void UsersDialog::accept() {
8 ✔
212
  if (!hasSelection()) {
8 ✔
213
    // Nothing to encrypt to: an empty .gpg-id would make every insert fail
214
    // and the wizard never offers this dialog again once the file exists.
215
    return;
216
  }
217
  if (m_initOnAccept) {
6 ✔
218
    m_pass->Init(m_dir, m_userList);
6 ✔
219
  }
220

221
  QDialog::accept();
6 ✔
222
}
223

224
auto UsersDialog::hasSelection() const -> bool {
118 ✔
225
  return std::any_of(m_userList.cbegin(), m_userList.cend(),
226
                     [](const UserInfo &user) { return user.enabled; });
181 ✔
227
}
228

229
void UsersDialog::updateOkButton() {
107 ✔
230
  if (auto *ok = ui->buttonBox->button(QDialogButtonBox::Ok)) {
107 ✔
231
    ok->setEnabled(hasSelection());
107 ✔
232
  }
233
}
107 ✔
234

235
void UsersDialog::keyPressEvent(QKeyEvent *event) {
1 ✔
236
  switch (event->key()) {
1 ✔
237
  case Qt::Key_Escape:
1 ✔
238
    ui->lineEdit->clear();
1 ✔
239
    break;
1 ✔
240
  default:
241
    break;
242
  }
243
}
1 ✔
244

245
void UsersDialog::itemChange(QListWidgetItem *item) {
123 ✔
246
  if (!item) {
123 ✔
247
    return;
74 ✔
248
  }
249
  bool ok = false;
123 ✔
250
  const int index = item->data(Qt::UserRole).toInt(&ok);
123 ✔
251
  if (!ok) {
123 ✔
252
    qCWarning(lcQtPass)
146 ✔
253
        << "UsersDialog::itemChange: invalid user index data for item";
73 ✔
254
    return;
73 ✔
255
  }
256
  if (index < 0 || index >= m_userList.size()) {
50 ✔
257
    qCWarning(lcQtPass) << "UsersDialog::itemChange: user index out of range:"
2 ✔
258
                        << index << "valid range is [0,"
1 ✔
259
                        << (m_userList.size() - 1) << "]";
1 ✔
260
    return;
1 ✔
261
  }
262
  m_userList[index].enabled = item->checkState() == Qt::Checked;
49 ✔
263
  updateOkButton();
49 ✔
264
}
265

266
void UsersDialog::populateList(const QString &filter) {
58 ✔
267
  // Invalidate cached datetime so expiry checks use fresh current time
268
  m_cachedDateTimeValid = false;
58 ✔
269

270
  QString patternString = "*" + filter + "*";
58 ✔
271
  if (m_cachedPatternString != patternString) {
58 ✔
272
    QRegularExpression re(
273
        QRegularExpression::wildcardToRegularExpression(patternString),
96 ✔
274
        QRegularExpression::CaseInsensitiveOption);
48 ✔
275
    if (re.isValid()) {
48 ✔
276
      m_cachedNameFilter = re;
48 ✔
277
      m_cachedPatternString = patternString;
48 ✔
278
    }
279
  }
48 ✔
280
  const QRegularExpression &nameFilter = m_cachedNameFilter;
58 ✔
281
  ui->listWidget->clear();
58 ✔
282

283
  for (int i = 0; i < m_userList.size(); ++i) {
188 ✔
284
    const auto &user = m_userList.at(i);
285
    if (!passesFilter(user, filter, nameFilter)) {
130 ✔
286
      continue;
23 ✔
287
    }
288

289
    auto *item = new QListWidgetItem(buildUserText(user), ui->listWidget);
107 ✔
290
    applyUserStyling(item, user);
107 ✔
291
    item->setCheckState(user.enabled ? Qt::Checked : Qt::Unchecked);
169 ✔
292
    item->setData(Qt::UserRole, QVariant::fromValue(i));
107 ✔
293
    ui->listWidget->addItem(item);
107 ✔
294
  }
295
  updateOkButton();
58 ✔
296
}
58 ✔
297

298
bool UsersDialog::passesFilter(const UserInfo &user, const QString &filter,
130 ✔
299
                               const QRegularExpression &nameFilter) const {
300
  if (!filter.isEmpty() && !nameFilter.match(user.name).hasMatch()) {
140 ✔
301
    return false;
302
  }
303
  // A ticked key is one the folder is encrypted to: it is shown whatever
304
  // its state, or an expired or missing recipient stays in .gpg-id unseen and
305
  // cannot be unticked. "Show unusable keys" is about keys to add.
306
  if (user.enabled || ui->checkBox->isChecked()) {
120 ✔
307
    return true;
54 ✔
308
  }
309
  return user.isValid() && !isUserExpired(user);
58 ✔
310
}
311

312
auto UsersDialog::isUserExpired(const UserInfo &user) const -> bool {
165 ✔
313
  if (!m_cachedDateTimeValid) {
165 ✔
314
    m_cachedCurrentDateTime = QDateTime::currentDateTime();
56 ✔
315
    m_cachedDateTimeValid = true;
56 ✔
316
  }
317
  // gpg marks a key it already judged expired with validity 'e'.
318
  return user.validity == 'e' ||
328 ✔
319
         (user.expiry.isValid() && m_cachedCurrentDateTime > user.expiry);
172 ✔
320
}
321

322
QString UsersDialog::buildUserText(const UserInfo &user) const {
107 ✔
323
  QString text = user.name + "\n" + user.key_id;
107 ✔
324
  if (user.created.isValid()) {
107 ✔
325
    text += " " + tr("created") + " " +
208 ✔
326
            QLocale::system().toString(user.created, QLocale::ShortFormat);
312 ✔
327
  }
328
  if (user.expiry.isValid()) {
107 ✔
329
    text += " " + tr("expires") + " " +
12 ✔
330
            QLocale::system().toString(user.expiry, QLocale::ShortFormat);
18 ✔
331
  }
332
  return text;
107 ✔
333
}
334

335
void UsersDialog::applyUserStyling(QListWidgetItem *item,
107 ✔
336
                                   const UserInfo &user) const {
337
  const QString originalText = item->text();
107 ✔
338
  // Status badge first: an own key can be expired too, and then the marker
339
  // matters more than the "you can decrypt with this" colour.
340
  bool badged = true;
341
  // Expired before invalid: gpg gives an expired key validity 'e', which is
342
  // not a valid one, and "expired" says what to do about it.
343
  if (isUserExpired(user)) {
107 ✔
344
    // A lone dark-red foreground is unreadable on dark themes, and gpg
345
    // refuses to encrypt to expired keys anyway.
346
    item->setBackground(Qt::darkRed);
6 ✔
347
    item->setForeground(Qt::white);
6 ✔
348
    item->setText(tr("[EXPIRED] ") + originalText);
12 ✔
349
  } else if (!user.isValid()) {
350
    item->setBackground(Qt::darkRed);
6 ✔
351
    item->setForeground(Qt::white);
6 ✔
352
    item->setText(tr("[INVALID] ") + originalText);
12 ✔
353
  } else if (!user.fullyValid()) {
95 ✔
354
    item->setBackground(Qt::darkYellow);
7 ✔
355
    item->setForeground(Qt::white);
7 ✔
356
    item->setText(tr("[PARTIAL] ") + originalText);
14 ✔
357
  } else {
358
    item->setText(originalText);
88 ✔
359
    badged = false;
360
  }
361
  if (user.have_secret) {
107 ✔
362
    if (!badged) {
7 ✔
363
      item->setForeground(QApplication::palette().color(QPalette::Link));
14 ✔
364
    }
365
    QFont font = item->font();
7 ✔
366
    font.setBold(true);
367
    item->setFont(font);
7 ✔
368
  }
7 ✔
369
}
107 ✔
370

371
void UsersDialog::on_lineEdit_textChanged(const QString &filter) {
10 ✔
372
  populateList(filter);
10 ✔
373
}
10 ✔
374

375
void UsersDialog::on_checkBox_clicked() { populateList(ui->lineEdit->text()); }
20 ✔
376

377
void UsersDialog::selectImportedKey(const QString &importedKey) {
1 ✔
378
  // Suffixes shorter than 16 characters would give false positives.
379
  const auto sameKey = [&importedKey](const QString &keyId) {
2 ✔
380
    return (keyId.length() >= 16 &&
2 ✔
381
            importedKey.endsWith(keyId, Qt::CaseInsensitive)) ||
3 ✔
382
           (importedKey.length() >= 16 &&
2 ✔
383
            keyId.endsWith(importedKey, Qt::CaseInsensitive));
1 ✔
384
  };
1 ✔
385
  // The stored key_id, not the item text.
386
  for (int i = 0; i < ui->listWidget->count(); ++i) {
2 ✔
387
    QListWidgetItem *item = ui->listWidget->item(i);
2 ✔
388
    bool ok = false;
2 ✔
389
    const int idx = item != nullptr ? item->data(Qt::UserRole).toInt(&ok) : -1;
2 ✔
390
    if (ok && idx >= 0 && idx < m_userList.size() &&
4 ✔
391
        !m_userList[idx].key_id.isEmpty() && sameKey(m_userList[idx].key_id)) {
4 ✔
392
      ui->listWidget->setCurrentItem(item);
1 ✔
393
      return;
1 ✔
394
    }
395
  }
396
}
397

398
void UsersDialog::on_importKeyButton_clicked() {
2 ✔
399
  ImportKeyDialog dialog(m_gpgExe, this);
2 ✔
400
  if (dialog.exec() != QDialog::Accepted) {
2 ✔
401
    return;
402
  }
403

404
  // Non-empty after Accepted, but an empty id would make the endsWith()
405
  // below match the first listed key.
406
  const QString importedKey = dialog.importedKeyId();
1 ✔
407
  if (importedKey.isEmpty()) {
1 ✔
408
    return;
409
  }
410

411
  // loadGpgKeys() rebuilds the key list from the keyring and drops every tick.
412
  // Remember which recipients were selected (the .gpg-id list and the user's
413
  // own ticks, including any "key not found" rows) and re-apply them after, so
414
  // importing a key does not silently remove the other recipients.
415
  QStringList selected;
1 ✔
416
  for (const UserInfo &user : std::as_const(m_userList)) {
2 ✔
417
    if (user.enabled) {
1 ✔
418
      selected.append(user.key_id);
1 ✔
419
    }
420
  }
421

422
  if (!loadGpgKeys()) {
1 ✔
423
    return;
424
  }
425

426
  // Re-apply the remembered selection. Most saved identifiers are a key ID that
427
  // is in the rebuilt list, so match those exactly first (no gpg lookup). An
428
  // identifier that does not match a row is one that was listed as "key not
429
  // found" - a short ID or email that gpg could not resolve, or whose key has
430
  // just been imported and now shows under its fingerprint. Hand those to
431
  // selectRecipients(), which resolves each against the refreshed keyring,
432
  // ticks the matching row, and re-adds a "key not found" row for any that
433
  // still does not resolve.
434
  QStringList unresolved;
1 ✔
435
  for (const QString &keyId : std::as_const(selected)) {
2 ✔
436
    bool matched = false;
437
    for (UserInfo &user : m_userList) {
3 ✔
438
      if (user.key_id == keyId) {
2 ✔
439
        user.enabled = true;
1 ✔
440
        matched = true;
441
      }
442
    }
443
    if (!matched) {
1 ✔
444
      unresolved.append(keyId);
445
    }
446
  }
447
  if (!unresolved.isEmpty()) {
1 ✔
NEW
448
    selectRecipients(unresolved);
×
449
  }
450

451
  // Clear the filter so the just-imported key is visible. setText("") still
452
  // emits textChanged once, so don't double-populate.
453
  {
454
    const QSignalBlocker blocker(ui->lineEdit);
1 ✔
455
    ui->lineEdit->clear();
1 ✔
456
  }
1 ✔
457
  populateList(QString());
1 ✔
458

459
  selectImportedKey(importedKey);
1 ✔
460
}
2 ✔
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