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

IJHack / QtPass / 44081359370

17 Nov 2026 12:14PM UTC coverage: 96.369% (-0.05%) from 96.422%
44081359370

push

github

web-flow
Add folder: inherit the parent's recipients, name nested lists (#2248)

* Add folder: inherit the parent's recipients, name nested lists

"Add folder" copied the parent's recipients into the new folder's own
.gpg-id when no signing key was set (#1688). A later removal above it
did not reach that copy, so the folder's entries stayed encrypted to the
person removed, while the users dialog suggested subfolders were
covered. The folder now gets no .gpg-id and uses its parent's list, as
with pass and as QtPass already did with a signing key; the users dialog
gives it its own. Pass::seedGpgIdFile() and its tests go.

Copies made by earlier versions stay, so the users dialog names the
folders below the edited one that have a list of their own, which saving
there does not change.

Scan finding ANT-2026-3I1PV36T.

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

* CHANGELOG: with a signing key, save a nested copy, do not delete it

From the #2248 review: a list this device accepted is not replaced by
the parent's when deleted; saving into that folder then stops with
"Recipient list missing". Deleting a copy is the advice only for a store
without a signing key.

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

* CHANGELOG: untick removed recipients before saving a nested copy

From the #2248 review: the users dialog opens with the copy's list
ticked, so saving it unchanged keeps whoever was removed above.

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

* CHANGELOG: rewrap the Add folder upgrade note

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

* CHANGELOG: re-encrypt the folder after removing a nested copy

From the #2248 review: removing an unsigned copy changes which list new
entries use, not the ciphertext o... (continued)

19 of 20 new or added lines in 1 file covered. (95.0%)

7 existing lines in 2 files now uncovered.

8972 of 9310 relevant lines covered (96.37%)

756.22 hits per line

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

98.11
/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 <QSet>
31
#include <QSignalBlocker>
32
#include <QWidget>
33
#include <algorithm>
34
#include <utility>
35

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

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

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

55
  loadRecipients();
45 ✔
56
  showNestedLists();
45 ✔
57
  populateList();
45 ✔
58

59
  connectSignals();
45 ✔
60
}
×
61

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

71
  ui->lineEdit->setClearButtonEnabled(true);
45 ✔
72
}
45 ✔
73

74
void UsersDialog::restoreDialogState() {
46 ✔
75
  WindowStateStore::attach(*this, QStringLiteral("usersDialog"));
92 ✔
76
}
46 ✔
77

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

87
  markSecretKeys(users);
46 ✔
88

89
  m_userList = users;
90
  return true;
46 ✔
91
}
92

93
void UsersDialog::markSecretKeys(QList<UserInfo> &users) {
46 ✔
94
  QList<UserInfo> secret_keys = m_pass->listKeys("", true);
92 ✔
95
  QSet<QString> secretKeyIds;
96
  for (const UserInfo &sec : secret_keys) {
51 ✔
97
    secretKeyIds.insert(sec.key_id);
5 ✔
98
  }
99
  for (auto &user : users) {
138 ✔
100
    if (secretKeyIds.contains(user.key_id)) {
92 ✔
101
      user.have_secret = true;
5 ✔
102
    }
103
  }
104
}
46 ✔
105

106
void UsersDialog::showRecipientWarning(const QString &text,
9 ✔
107
                                       const QString &name) {
108
  // Plain text before the text is set: it can quote the store's recipient
109
  // list, which as rich text could make Qt load a file (<img src=...>).
110
  auto *banner = new QLabel(this);
9 ✔
111
  banner->setTextFormat(Qt::PlainText);
9 ✔
112
  banner->setText(text);
9 ✔
113
  banner->setObjectName(name);
9 ✔
114
  banner->setWordWrap(true);
9 ✔
115
  // Palette, not a stylesheet colour, so it reads on dark themes too; red as
116
  // ProcessOutputPanel paints error lines.
117
  QFont bold = banner->font();
9 ✔
118
  bold.setBold(true);
119
  banner->setFont(bold);
9 ✔
120
  QPalette palette = banner->palette();
9 ✔
121
  palette.setColor(QPalette::WindowText, QColor(Qt::red));
9 ✔
122
  banner->setPalette(palette);
9 ✔
123
  banner->setContentsMargins(4, 4, 4, 4);
9 ✔
124
  ui->verticalLayout->insertWidget(1, banner);
9 ✔
125
}
9 ✔
126

127
void UsersDialog::showNestedLists() {
45 ✔
128
  // The walk re-encryption takes: hidden folders and links are not entered.
129
  const QString dir = QDir::cleanPath(m_dir);
45 ✔
130
  if (!QFileInfo(dir).isDir()) {
45 ✔
131
    return;
132
  }
133
  QStringList nested;
45 ✔
134
  const QStringList lists =
135
      Util::regularFilesUnder(dir, {QStringLiteral(".gpg-id")}, nullptr, true);
135 ✔
136
  for (const QString &list : lists) {
75 ✔
137
    const QString folder = QFileInfo(list).path();
30 ✔
138
    if (QDir::cleanPath(folder) != dir) {
60 ✔
139
      nested << QDir::toNativeSeparators(QDir(dir).relativeFilePath(folder));
6 ✔
140
    }
141
  }
142
  if (nested.isEmpty()) {
45 ✔
143
    return;
144
  }
145
  constexpr qsizetype kMaxNamed = 5;
146
  QString names = nested.mid(0, kMaxNamed).join(QStringLiteral(", "));
4 ✔
147
  if (nested.size() > kMaxNamed) {
2 ✔
NEW
148
    names += QStringLiteral(", …");
×
149
  }
150
  //: %1 lists folders, such as "work, work/bank". Shown when changing the
151
  //: recipients of a folder that has folders with their own list below it.
152
  showRecipientWarning(
2 ✔
153
      tr("%n folder(s) below this one have their own recipients, which "
2 ✔
154
         "saving here does not change: %1",
155
         nullptr, static_cast<int>(nested.size()))
156
          .arg(names),
4 ✔
157
      QStringLiteral("nestedListsWarning"));
2 ✔
158
}
159

160
namespace {
161

162
/// A key ID as written anywhere: without a 0x prefix, upper case.
163
auto normalisedKeyId(const QString &id) -> QString {
84 ✔
164
  const QString trimmed = id.trimmed();
165
  return (trimmed.startsWith(QLatin1String("0x"), Qt::CaseInsensitive)
84 ✔
166
              ? trimmed.mid(2)
168 ✔
167
              : trimmed)
168
      .toUpper();
84 ✔
169
}
170

171
/// Whether @p recipient, as a .gpg-id lists it, names @p key the way gpg's
172
/// -r resolves it: a key ID in any length gpg accepts (the key carries its
173
/// fingerprint, the list may carry a long or short ID, a suffix of it, or
174
/// the fingerprint; eight characters is the shortest), or else a name,
175
/// matched case-insensitively as a substring of the UID after gpg's
176
/// "=", "<...>", "@" and "*" markers.
177
auto answersTo(const UserInfo &key, const QString &recipient) -> bool {
47 ✔
178
  static const QRegularExpression hexId(
179
      QStringLiteral("^(0x)?[0-9A-Fa-f]{8,}$"));
50 ✔
180
  if (hexId.match(recipient.trimmed()).hasMatch()) {
94 ✔
181
    const QString id = normalisedKeyId(recipient);
42 ✔
182
    const QString keyId = normalisedKeyId(key.key_id);
42 ✔
183
    return keyId.endsWith(id) || (keyId.size() >= 8 && id.endsWith(keyId));
42 ✔
184
  }
185
  QString term = recipient.trimmed();
186
  if (term.startsWith(u'=') || term.startsWith(u'@') || term.startsWith(u'*')) {
5 ✔
187
    term.remove(0, 1);
×
188
  } else if (term.startsWith(u'<') && term.endsWith(u'>')) {
5 ✔
189
    term = term.mid(1, term.size() - 2);
2 ✔
190
  }
191
  return !term.isEmpty() && key.name.contains(term, Qt::CaseInsensitive);
5 ✔
192
}
193

194
} // namespace
195

196
void UsersDialog::selectRecipients(const QStringList &recipients) {
24 ✔
197
  // Each per-line gpg lookup is a blocking call on the dialog's way up, so a
198
  // store with many keys missing from the keyring (a fresh clone, a team
199
  // store) is capped at this many across both the fallback below and the
200
  // missing-key check; the rest resolve by the batched call or stay unchecked.
201
  constexpr int kMaxLookups = 10;
202
  int lookups = 0;
203
  // Remembers the per-line lookups the fallback already ran, so the
204
  // missing-key loop below reuses them instead of asking gpg a second time.
205
  QHash<QString, bool> perLineHasKey;
24 ✔
206

207
  // One gpg call resolves every recipient, by key ID or by email/UID.
208
  QList<UserInfo> resolved = m_pass->listKeys(recipients);
48 ✔
209
  if (resolved.isEmpty() && recipients.size() > 1) {
24 ✔
210
    // One line gpg cannot read as a key search ("0x", a fingerprint one
211
    // digit short) aborts that whole call with exit code 2, so nothing is
212
    // listed for the other lines, whose keys are in the keyring all the same.
213
    // Asked for one by one they still resolve; only the unreadable line is
214
    // reported missing by the loop below, as an unknown key already is.
215
    for (const QString &recipient : recipients) {
25 ✔
216
      if (lookups++ >= kMaxLookups) {
22 ✔
217
        break;
218
      }
219
      const QList<UserInfo> keys = m_pass->listKeys(recipient);
21 ✔
220
      perLineHasKey.insert(recipient, !keys.isEmpty());
21 ✔
221
      resolved += keys;
222
    }
223
  }
224
  for (UserInfo &user : m_userList) {
72 ✔
225
    if (std::any_of(resolved.cbegin(), resolved.cend(),
48 ✔
226
                    [&user](const UserInfo &key) {
227
                      return key.key_id == user.key_id;
61 ✔
228
                    })) {
229
      user.enabled = true;
35 ✔
230
    }
231
  }
232
  // Only what gpg itself cannot find is reported missing. The fallback's
233
  // per-line answer, when it has one, is gpg's own verdict for that line and
234
  // decides it outright. Otherwise the heuristic match is a fast path (a
235
  // secondary UID or a subkey ID resolves in gpg without showing in what it
236
  // lists), and a per-line gpg call settles anything it does not catch. Taking
237
  // the cached answer first also keeps a genuinely unreadable line ("0x")
238
  // reported missing even when a resolved key's UID happens to contain it, so
239
  // the heuristic answersTo() would otherwise match.
240
  for (const QString &recipient : recipients) {
80 ✔
241
    bool found = false;
242
    const auto cached = perLineHasKey.constFind(recipient);
56 ✔
243
    if (cached != perLineHasKey.constEnd()) {
244
      found = cached.value();
21 ✔
245
    } else {
246
      found = std::any_of(resolved.cbegin(), resolved.cend(),
35 ✔
247
                          [&recipient](const UserInfo &key) {
248
                            return answersTo(key, recipient);
47 ✔
249
                          });
250
      if (!found && lookups++ < kMaxLookups) {
35 ✔
251
        found = !m_pass->listKeys(recipient).isEmpty();
8 ✔
252
      }
253
    }
254
    if (!found) {
56 ✔
255
      UserInfo missing;
26 ✔
256
      missing.enabled = true;
26 ✔
257
      missing.key_id = recipient;
26 ✔
258
      missing.name = " ?? " + tr("Key not found in keyring");
52 ✔
259
      m_userList.append(missing);
260
    }
26 ✔
261
  }
262
}
24 ✔
263

264
void UsersDialog::loadRecipients() {
45 ✔
265
  // A store that had no list when it was chosen (a new profile): a list
266
  // that appeared since is nobody's choice, and was read under the active
267
  // backend's signing policy, not the new profile's.
268
  if (m_preselect == Preselect::Nothing) {
45 ✔
269
    return;
3 ✔
270
  }
271
  // Through the backend: with a signing key only a verified list may be
272
  // preselected, since OK signs whatever is selected.
273
  const Pass::RecipientsForEditing loaded =
274
      m_pass->recipientsForEditing(m_dir, m_passStore);
42 ✔
275
  if (!loaded.warning.isEmpty()) {
42 ✔
276
    showRecipientWarning(loaded.warning);
14 ✔
277
  }
278
  // A folder without .gpg-id (new store, new profile) has no recipients yet;
279
  // listKeys() with no filter would return the whole keyring, preselected.
280
  if (loaded.state != Pass::RecipientsForEditing::State::Rejected &&
42 ✔
281
      !loaded.recipients.isEmpty()) {
282
    selectRecipients(loaded.recipients);
24 ✔
283
  }
284
}
285

286
UsersDialog::~UsersDialog() = default;
92 ✔
287

288
void UsersDialog::accept() {
9 ✔
289
  if (!hasSelection()) {
9 ✔
290
    // Nothing to encrypt to: an empty .gpg-id would make every insert fail
291
    // and the wizard never offers this dialog again once the file exists.
292
    return;
293
  }
294
  if (m_initOnAccept) {
7 ✔
295
    m_pass->Init(m_dir, m_userList);
8 ✔
296
  }
297

298
  QDialog::accept();
7 ✔
299
}
300

301
auto UsersDialog::hasSelection() const -> bool {
138 ✔
302
  return std::any_of(m_userList.cbegin(), m_userList.cend(),
303
                     [](const UserInfo &user) { return user.enabled; });
210 ✔
304
}
305

306
void UsersDialog::updateOkButton() {
126 ✔
307
  if (auto *ok = ui->buttonBox->button(QDialogButtonBox::Ok)) {
126 ✔
308
    ok->setEnabled(hasSelection());
126 ✔
309
  }
310
}
126 ✔
311

312
void UsersDialog::keyPressEvent(QKeyEvent *event) {
1 ✔
313
  switch (event->key()) {
1 ✔
314
  case Qt::Key_Escape:
1 ✔
315
    ui->lineEdit->clear();
1 ✔
316
    break;
1 ✔
317
  default:
318
    break;
319
  }
320
}
1 ✔
321

322
void UsersDialog::itemChange(QListWidgetItem *item) {
137 ✔
323
  if (!item) {
137 ✔
324
    return;
80 ✔
325
  }
326
  bool ok = false;
137 ✔
327
  const int index = item->data(Qt::UserRole).toInt(&ok);
137 ✔
328
  if (!ok) {
137 ✔
329
    qCWarning(lcQtPass)
158 ✔
330
        << "UsersDialog::itemChange: invalid user index data for item";
79 ✔
331
    return;
79 ✔
332
  }
333
  if (index < 0 || index >= m_userList.size()) {
58 ✔
334
    qCWarning(lcQtPass) << "UsersDialog::itemChange: user index out of range:"
2 ✔
335
                        << index << "valid range is [0,"
1 ✔
336
                        << (m_userList.size() - 1) << "]";
1 ✔
337
    return;
1 ✔
338
  }
339
  m_userList[index].enabled = item->checkState() == Qt::Checked;
57 ✔
340
  updateOkButton();
57 ✔
341
}
342

343
void UsersDialog::populateList(const QString &filter) {
69 ✔
344
  // Invalidate cached datetime so expiry checks use fresh current time
345
  m_cachedDateTimeValid = false;
69 ✔
346

347
  QString patternString = "*" + filter + "*";
69 ✔
348
  if (m_cachedPatternString != patternString) {
69 ✔
349
    // A user ID is not a path: "*" and "?" must match a "/" as well, or a
350
    // key named "ACME A/S" or "(dev/ops)" drops out of the search and stays
351
    // ticked unseen while the listed rows are unticked.
352
    QRegularExpression re(
353
        QRegularExpression::wildcardToRegularExpression(
118 ✔
354
            patternString, QRegularExpression::NonPathWildcardConversion),
355
        QRegularExpression::CaseInsensitiveOption);
59 ✔
356
    if (re.isValid()) {
59 ✔
357
      m_cachedNameFilter = re;
59 ✔
358
      m_cachedPatternString = patternString;
59 ✔
359
    }
360
  }
59 ✔
361
  const QRegularExpression &nameFilter = m_cachedNameFilter;
69 ✔
362
  ui->listWidget->clear();
69 ✔
363

364
  for (int i = 0; i < m_userList.size(); ++i) {
248 ✔
365
    const auto &user = m_userList.at(i);
366
    if (!passesFilter(user, filter, nameFilter)) {
179 ✔
367
      continue;
26 ✔
368
    }
369

370
    auto *item = new QListWidgetItem(buildUserText(user), ui->listWidget);
153 ✔
371
    applyUserStyling(item, user);
153 ✔
372
    item->setCheckState(user.enabled ? Qt::Checked : Qt::Unchecked);
222 ✔
373
    item->setData(Qt::UserRole, QVariant::fromValue(i));
153 ✔
374
    ui->listWidget->addItem(item);
153 ✔
375
  }
376
  updateOkButton();
69 ✔
377
}
69 ✔
378

379
bool UsersDialog::passesFilter(const UserInfo &user, const QString &filter,
179 ✔
380
                               const QRegularExpression &nameFilter) const {
381
  if (!filter.isEmpty() && !nameFilter.match(user.name).hasMatch()) {
192 ✔
382
    return false;
383
  }
384
  // A ticked key is one the folder is encrypted to: it is shown whatever
385
  // its state, or an expired or missing recipient stays in .gpg-id unseen and
386
  // cannot be unticked. "Show unusable keys" is about keys to add.
387
  if (user.enabled || ui->checkBox->isChecked()) {
166 ✔
388
    return true;
93 ✔
389
  }
390
  return user.isValid() && !isUserExpired(user);
65 ✔
391
}
392

393
auto UsersDialog::isUserExpired(const UserInfo &user) const -> bool {
218 ✔
394
  if (!m_cachedDateTimeValid) {
218 ✔
395
    m_cachedCurrentDateTime = QDateTime::currentDateTime();
67 ✔
396
    m_cachedDateTimeValid = true;
67 ✔
397
  }
398
  // gpg marks a key it already judged expired with validity 'e'.
399
  return user.validity == 'e' ||
434 ✔
400
         (user.expiry.isValid() && m_cachedCurrentDateTime > user.expiry);
225 ✔
401
}
402

403
QString UsersDialog::buildUserText(const UserInfo &user) const {
153 ✔
404
  QString text = user.name + "\n" + user.key_id;
153 ✔
405
  if (user.created.isValid()) {
153 ✔
406
    text += " " + tr("created") + " " +
252 ✔
407
            QLocale::system().toString(user.created, QLocale::ShortFormat);
378 ✔
408
  }
409
  if (user.expiry.isValid()) {
153 ✔
410
    text += " " + tr("expires") + " " +
12 ✔
411
            QLocale::system().toString(user.expiry, QLocale::ShortFormat);
18 ✔
412
  }
413
  return text;
153 ✔
414
}
415

416
void UsersDialog::applyUserStyling(QListWidgetItem *item,
153 ✔
417
                                   const UserInfo &user) const {
418
  const QString originalText = item->text();
153 ✔
419
  // Status badge first: an own key can be expired too, and then the marker
420
  // matters more than the "you can decrypt with this" colour.
421
  bool badged = true;
422
  // Expired before invalid: gpg gives an expired key validity 'e', which is
423
  // not a valid one, and "expired" says what to do about it.
424
  if (isUserExpired(user)) {
153 ✔
425
    // A lone dark-red foreground is unreadable on dark themes, and gpg
426
    // refuses to encrypt to expired keys anyway.
427
    item->setBackground(Qt::darkRed);
6 ✔
428
    item->setForeground(Qt::white);
6 ✔
429
    item->setText(tr("[EXPIRED] ") + originalText);
12 ✔
430
  } else if (!user.isValid()) {
431
    item->setBackground(Qt::darkRed);
30 ✔
432
    item->setForeground(Qt::white);
30 ✔
433
    item->setText(tr("[INVALID] ") + originalText);
60 ✔
434
  } else if (!user.fullyValid()) {
117 ✔
435
    item->setBackground(Qt::darkYellow);
7 ✔
436
    item->setForeground(Qt::white);
7 ✔
437
    item->setText(tr("[PARTIAL] ") + originalText);
14 ✔
438
  } else {
439
    item->setText(originalText);
110 ✔
440
    badged = false;
441
  }
442
  if (user.have_secret) {
153 ✔
443
    if (!badged) {
7 ✔
444
      item->setForeground(QApplication::palette().color(QPalette::Link));
14 ✔
445
    }
446
    QFont font = item->font();
7 ✔
447
    font.setBold(true);
448
    item->setFont(font);
7 ✔
449
  }
7 ✔
450
}
153 ✔
451

452
void UsersDialog::on_lineEdit_textChanged(const QString &filter) {
13 ✔
453
  populateList(filter);
13 ✔
454
}
13 ✔
455

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

458
void UsersDialog::selectImportedKey(const QString &importedKey) {
1 ✔
459
  // Suffixes shorter than 16 characters would give false positives.
460
  const auto sameKey = [&importedKey](const QString &keyId) {
2 ✔
461
    return (keyId.length() >= 16 &&
2 ✔
462
            importedKey.endsWith(keyId, Qt::CaseInsensitive)) ||
3 ✔
463
           (importedKey.length() >= 16 &&
2 ✔
464
            keyId.endsWith(importedKey, Qt::CaseInsensitive));
1 ✔
465
  };
1 ✔
466
  // The stored key_id, not the item text.
467
  for (int i = 0; i < ui->listWidget->count(); ++i) {
2 ✔
468
    QListWidgetItem *item = ui->listWidget->item(i);
2 ✔
469
    bool ok = false;
2 ✔
470
    const int idx = item != nullptr ? item->data(Qt::UserRole).toInt(&ok) : -1;
2 ✔
471
    if (ok && idx >= 0 && idx < m_userList.size() &&
4 ✔
472
        !m_userList[idx].key_id.isEmpty() && sameKey(m_userList[idx].key_id)) {
4 ✔
473
      ui->listWidget->setCurrentItem(item);
1 ✔
474
      return;
1 ✔
475
    }
476
  }
477
}
478

479
void UsersDialog::on_importKeyButton_clicked() {
2 ✔
480
  ImportKeyDialog dialog(m_gpgExe, this);
2 ✔
481
  if (dialog.exec() != QDialog::Accepted) {
2 ✔
482
    return;
483
  }
484

485
  // Non-empty after Accepted, but an empty id would make the endsWith()
486
  // below match the first listed key.
487
  const QString importedKey = dialog.importedKeyId();
1 ✔
488
  if (importedKey.isEmpty()) {
1 ✔
489
    return;
490
  }
491

492
  // loadGpgKeys() rebuilds the key list from the keyring and drops every tick.
493
  // Remember which recipients were selected (the .gpg-id list and the user's
494
  // own ticks, including any "key not found" rows) and re-apply them after, so
495
  // importing a key does not silently remove the other recipients.
496
  QStringList selected;
1 ✔
497
  for (const UserInfo &user : std::as_const(m_userList)) {
2 ✔
498
    if (user.enabled) {
1 ✔
499
      selected.append(user.key_id);
1 ✔
500
    }
501
  }
502

503
  if (!loadGpgKeys()) {
1 ✔
504
    return;
505
  }
506

507
  // Re-apply the remembered selection. Most saved identifiers are a key ID that
508
  // is in the rebuilt list, so match those exactly first (no gpg lookup). An
509
  // identifier that does not match a row is one that was listed as "key not
510
  // found" - a short ID or email that gpg could not resolve, or whose key has
511
  // just been imported and now shows under its fingerprint. Hand those to
512
  // selectRecipients(), which resolves each against the refreshed keyring,
513
  // ticks the matching row, and re-adds a "key not found" row for any that
514
  // still does not resolve.
515
  QStringList unresolved;
1 ✔
516
  for (const QString &keyId : std::as_const(selected)) {
2 ✔
517
    bool matched = false;
518
    for (UserInfo &user : m_userList) {
3 ✔
519
      if (user.key_id == keyId) {
2 ✔
520
        user.enabled = true;
1 ✔
521
        matched = true;
522
      }
523
    }
524
    if (!matched) {
1 ✔
525
      unresolved.append(keyId);
526
    }
527
  }
528
  if (!unresolved.isEmpty()) {
1 ✔
529
    selectRecipients(unresolved);
×
530
  }
531

532
  // Clear the filter so the just-imported key is visible. setText("") still
533
  // emits textChanged once, so don't double-populate.
534
  {
535
    const QSignalBlocker blocker(ui->lineEdit);
1 ✔
536
    ui->lineEdit->clear();
1 ✔
537
  }
1 ✔
538
  populateList(QString());
1 ✔
539

540
  selectImportedKey(importedKey);
1 ✔
541
}
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