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

IJHack / QtPass / 46165298070

28 Nov 2026 04:27PM UTC coverage: 94.471% (+0.03%) from 94.442%
46165298070

push

github

web-flow
Refuse a recipient key that another key also holds (#2383)

gpg resolves a .gpg-id fingerprint or key ID among primary keys and
subkeys, and anyone can bind another person's public key to their own
as a subkey. After the user imported such an update of a colleague's
key, every entry saved or re-encrypted for the person the line names
was encrypted to the colleague instead, silently, with no access to
the store needed.

Pass::keyLinesHeldTwice() lists the keyring once, in the store's
environment, and finds every key ID or fingerprint line (grouped with
spaces too) that more than one key block holds. Such a line is
refused, naming both keys:

- native backend: Insert(), Init() and each folder of a re-encryption
  run;
- pass backend: insert, init and move/copy, right before pass runs and
  including every folder's own list below that pass re-encrypts to;
- the Users dialog keeps such a line as written, with a warning, and
  does not probe or search it;
- "Export my public key" refuses, and exports in the store's keyring.

A gpg that starts but cannot list its keyring refuses too; one that
does not start fails as before. Each check runs after the existing
refusals. Lost convenience: such a folder cannot be saved to until the
key that claims someone else's is deleted.

Tests: the listing parser (fingerprints, key IDs, "!", grouped lines,
v5 naming); ImitatePass refuses Insert() and re-encryption with nothing
encrypted, and a keyring that cannot be listed; RealPass refuses insert
and an init with a child list held twice (also past a decoy x.gpg
folder); the Users dialog keeps the line; export refuses. Each guard
was reverted once and its test failed.

Scan finding ANT-2026-ZQIJE21W.

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

164 of 170 new or added lines in 6 files covered. (96.47%)

10764 of 11394 relevant lines covered (94.47%)

24513.83 hits per line

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

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

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

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

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

61
  connectSignals();
68 ✔
62
}
×
63

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

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

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

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

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

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

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

142
void UsersDialog::showNestedLists() {
68 ✔
143
  // The walk re-encryption takes: hidden folders and links are not entered.
144
  const QString dir = QDir::cleanPath(m_dir);
68 ✔
145
  if (!QFileInfo(dir).isDir()) {
68 ✔
146
    return;
147
  }
148
  QStringList unlisted;
68 ✔
149
  const QStringList lists = Util::regularFilesUnder(
204 ✔
150
      dir, {QStringLiteral(".gpg-id")}, nullptr, true, &unlisted);
136 ✔
151
  const auto relative = [&dir](const QString &folder) {
10 ✔
152
    return QDir::toNativeSeparators(QDir(dir).relativeFilePath(folder));
20 ✔
153
  };
68 ✔
154
  QStringList nested;
68 ✔
155
  for (const QString &list : lists) {
125 ✔
156
    const QString folder = QFileInfo(list).path();
57 ✔
157
    if (QDir::cleanPath(folder) != dir) {
114 ✔
158
      nested << relative(folder);
18 ✔
159
    }
160
  }
161
  QStringList unread;
68 ✔
162
  for (const QString &folder : std::as_const(unlisted)) {
69 ✔
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;
68 ✔
174
  if (!nested.isEmpty()) {
68 ✔
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()) {
68 ✔
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()) {
68 ✔
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 {
434 ✔
200
  const QString trimmed = id.trimmed();
201
  return (trimmed.startsWith(QLatin1String("0x"), Qt::CaseInsensitive)
434 ✔
202
              ? trimmed.mid(2)
868 ✔
203
              : trimmed)
204
      .toUpper();
434 ✔
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 {
217 ✔
211
  static const QRegularExpression hexId(QStringLiteral("^[0-9A-F]{8,}$"));
224 ✔
212
  const QString a = normalisedKeyId(first);
217 ✔
213
  const QString b = normalisedKeyId(second);
217 ✔
214
  if (!hexId.match(a).hasMatch() || !hexId.match(b).hasMatch()) {
434 ✔
215
    return false;
216
  }
217
  if (a.size() == 64) {
217 ✔
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) {
201 ✔
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);
201 ✔
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,356 ✔
232
  static const QRegularExpression hexLine(
233
      QStringLiteral("^(?:0[xX])?([0-9A-Fa-f]+)!?$"));
18,362 ✔
234
  const QRegularExpressionMatch match = hexLine.match(recipient.trimmed());
18,356 ✔
235
  if (!match.hasMatch()) {
18,356 ✔
236
    return {};
18,051 ✔
237
  }
238
  const QString digits = match.captured(1);
305 ✔
239
  const qsizetype size = digits.size();
240
  return size == 8 || size == 16 || size == 40 || size == 64 ? digits
305 ✔
241
                                                             : QString();
×
242
}
18,356 ✔
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,038 ✔
248
  const QString line = recipient.trimmed();
249
  if (line.isEmpty()) {
18,038 ✔
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,040 ✔
258
  if (hexish.match(line).hasMatch() ||
36,076 ✔
259
      QStringLiteral(".+#&^/[:!\\").contains(line.front())) {
36,071 ✔
260
    return {};
17 ✔
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,118 ✔
282
  return !keyIdOfLine(recipient).isEmpty() ||
12,144 ✔
283
         !nameTermOfLine(recipient).isEmpty();
12,144 ✔
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,154 ✔
294
  const QString keyId = keyIdOfLine(recipient);
12,154 ✔
295
  if (!keyId.isEmpty()) {
12,154 ✔
296
    return keyIdsMatch(key.key_id, keyId) ||
142 ✔
297
           std::any_of(key.subkeys.cbegin(), key.subkeys.cend(),
103 ✔
298
                       [&keyId](const QString &subkey) {
299
                         return keyIdsMatch(subkey, keyId);
69 ✔
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) {
45 ✔
316
  // A line listed twice is one recipient, and one row.
317
  QStringList recipients;
45 ✔
318
  QSet<QString> seen;
319
  for (const QString &line : listed) {
6,175 ✔
320
    if (!seen.contains(line)) {
6,130 ✔
321
      seen.insert(line);
6,129 ✔
322
      recipients.append(line);
323
    }
324
  }
325

326
  // OK saves what is ticked, so the ticks are the keys gpg's -r reaches for
327
  // the list, found by a throwaway encryption. A keyring search would also
328
  // find keys that only resemble a recipient: a user ID containing its
329
  // address, a subkey bound to its key, which whoever made the key decides.
330
  // Every reached key must have a row, or OK would drop it.
331
  const auto keepAsWritten = [this](const QString &line, const QString &why) {
22 ✔
332
    UserInfo kept;
22 ✔
333
    kept.key_id = line;
22 ✔
334
    kept.enabled = true;
22 ✔
335
    kept.name = " ?? " + why;
22 ✔
336
    m_userList.append(kept);
22 ✔
337
  };
22 ✔
338
  // Ticks the rows @p ids (what a probe of @p lines reached) belong to;
339
  // false, ticking nothing, when one has no row. A long key ID is a line
340
  // answersTo() judges as gpg does: the key's or one of its subkeys'. An
341
  // ID on more than one row is a subkey bound to several keys, where the
342
  // probe cannot tell which key gpg chose: only a line naming a reached
343
  // key's own primary key ticks its row, and any other line is kept as
344
  // written, so OK neither adds the key that shares the subkey nor drops
345
  // the recipient the line meant. Ticks are only added: after a key import
346
  // the rows ticked before stay.
347
  const auto tickReached = [this, &keepAsWritten](const QStringList &ids,
6 ✔
348
                                                  const QStringList &lines) {
349
    bool shared = false;
350
    QSet<int> reachedRows;
351
    for (const QString &id : ids) {
12 ✔
352
      QList<int> rows;
6 ✔
353
      for (int row = 0; row < m_userList.size(); ++row) {
18 ✔
354
        if (answersTo(m_userList.at(row), id)) {
12 ✔
355
          rows << row;
356
        }
357
      }
358
      if (rows.isEmpty()) {
6 ✔
359
        return false;
360
      }
361
      shared = shared || rows.size() > 1;
6 ✔
362
      for (const int row : std::as_const(rows)) {
14 ✔
363
        reachedRows.insert(row);
8 ✔
364
      }
365
    }
366
    if (!shared) {
6 ✔
367
      for (const int row : std::as_const(reachedRows)) {
4 ✔
368
        m_userList[row].enabled = true;
4 ✔
369
      }
370
      return true;
4 ✔
371
    }
372
    for (const QString &line : lines) {
4 ✔
373
      const QString keyId = keyIdOfLine(line);
2 ✔
374
      bool ticked = false;
375
      if (!keyId.isEmpty()) {
2 ✔
376
        for (const int row : std::as_const(reachedRows)) {
2 ✔
377
          if (keyIdsMatch(m_userList.at(row).key_id, keyId)) {
2 ✔
378
            m_userList[row].enabled = true;
1 ✔
379
            ticked = true;
380
          }
381
        }
382
      }
383
      if (!ticked) {
1 ✔
384
        keepAsWritten(line, tr("Matches more than one key; kept as written"));
2 ✔
385
      }
386
    }
387
    return true;
388
  };
45 ✔
389
  // A key ID or fingerprint that two key blocks hold (someone bound another
390
  // person's key to their own as a subkey) may encrypt to either: kept as
391
  // written and named, and not looked up, which would tick the other key.
392
  // A keyring that cannot be listed leaves every line untold: all kept as
393
  // written, nothing probed.
394
  if (const std::optional<QHash<QString, QStringList>> held =
395
          m_pass->keyLinesHeldTwice(recipients);
45 ✔
396
      !held || !held->isEmpty()) {
45 ✔
397
    showRecipientWarning(Pass::describeKeyLinesHeldTwice(held),
2 ✔
398
                         QStringLiteral("heldTwiceWarning"));
1 ✔
399
    QStringList rest;
1 ✔
400
    for (const QString &line : std::as_const(recipients)) {
2 ✔
401
      if (!held) {
1 ✔
NEW
402
        keepAsWritten(line, tr("Keys could not be checked; kept as written"));
×
403
      } else if (held->contains(line)) {
1 ✔
404
        keepAsWritten(line, tr("Held by more than one key; kept as written"));
2 ✔
405
      } else {
406
        rest << line;
407
      }
408
    }
409
    if (rest.isEmpty()) {
1 ✔
410
      return;
411
    }
412
    recipients = rest;
413
  }
414
  const std::optional<QStringList> reached =
415
      m_pass->encryptionReaches(recipients);
44 ✔
416
  if (reached && !reached->isEmpty() && tickReached(*reached, recipients)) {
44 ✔
417
    return;
418
  }
419
  if (!reached) {
40 ✔
420
    // gpg refused the list as a whole: one line it cannot encrypt to (a
421
    // key gone, expired or revoked), as in a list edited after someone
422
    // left. Each line on its own, so the others still tick only what they
423
    // reach, and a line gpg cannot encrypt to is kept as written. Address
424
    // and name lines first, where look-alike keys come from: a key ID or
425
    // fingerprint reaches the same key by probe or search. A line past the
426
    // few probed is kept as written too, so OK writes it back and adds no
427
    // key; only a line whose probe names no one goes to the search below.
428
    QStringList order;
6 ✔
429
    std::copy_if(
6 ✔
430
        recipients.cbegin(), recipients.cend(), std::back_inserter(order),
431
        [](const QString &line) { return keyIdOfLine(line).isEmpty(); });
41 ✔
432
    std::copy_if(
6 ✔
433
        recipients.cbegin(), recipients.cend(), std::back_inserter(order),
434
        [](const QString &line) { return !keyIdOfLine(line).isEmpty(); });
41 ✔
435
    constexpr int kMaxLineProbes = 10;
436
    QStringList unsure;
6 ✔
437
    int probes = 0;
438
    for (const QString &line : std::as_const(order)) {
47 ✔
439
      if (probes++ >= kMaxLineProbes) {
41 ✔
440
        keepAsWritten(line, tr("Not checked; kept as written"));
8 ✔
441
        continue;
8 ✔
442
      }
443
      // A one-line list: the probe that failed was this line's own.
444
      const std::optional<QStringList> one =
445
          recipients.size() == 1 ? std::nullopt
33 ✔
446
                                 : m_pass->encryptionReaches({line});
99 ✔
447
      if (!one) {
33 ✔
448
        keepAsWritten(line, tr("Key not found in keyring, or not usable"));
24 ✔
449
      } else if (one->isEmpty() || !tickReached(*one, {line})) {
27 ✔
450
        unsure << line;
451
      }
452
    }
453
    if (unsure.isEmpty()) {
6 ✔
454
      return;
455
    }
456
    recipients = unsure;
457
  }
458
  // What a probe could not settle: gpg encrypted but did not say whom, or
459
  // reached a key without a row. The keyring search below, as before.
460

461
  // One gpg call resolves every recipient, by key ID or by email/UID.
462
  QList<UserInfo> resolved = m_pass->listKeys(recipients);
76 ✔
463
  if (resolved.isEmpty() && recipients.size() > 1) {
38 ✔
464
    // One line gpg cannot read as a key search ("0x", a fingerprint one
465
    // digit short) aborts that whole call with exit code 2, so nothing is
466
    // listed for the other lines, whose keys are in the keyring all the same.
467
    // Every form judgedLocally() accepts gpg reads, so ask again for those;
468
    // the rest get a call of their own below.
469
    QStringList readable;
2 ✔
470
    std::copy_if(recipients.cbegin(), recipients.cend(),
2 ✔
471
                 std::back_inserter(readable), judgedLocally);
472
    if (!readable.isEmpty() && readable.size() < recipients.size()) {
2 ✔
473
      resolved = m_pass->listKeys(readable);
4 ✔
474
    }
475
  }
476

477
  // A line answersTo() cannot judge gets gpg's own verdict, one blocking
478
  // call each on the dialog's way up. Only unusual forms need it, so a few
479
  // are asked; past that a line is listed unticked as not looked up, so it
480
  // does not stay in the list unseen (a member could otherwise hide behind
481
  // it a key the user unticks).
482
  constexpr int kMaxLookups = 10;
483
  int lookups = 0;
484
  QHash<QString, bool> perLineHasKey;
38 ✔
485
  QSet<QString> notLookedUp;
486
  for (const QString &recipient : std::as_const(recipients)) {
6,140 ✔
487
    if (judgedLocally(recipient)) {
6,102 ✔
488
      continue;
6,088 ✔
489
    }
490
    if (lookups++ >= kMaxLookups) {
15 ✔
491
      notLookedUp.insert(recipient);
1 ✔
492
      continue;
1 ✔
493
    }
494
    const QList<UserInfo> keys = m_pass->listKeys(recipient);
14 ✔
495
    perLineHasKey.insert(recipient, !keys.isEmpty());
14 ✔
496
    resolved += keys;
497
  }
498

499
  for (UserInfo &user : m_userList) {
119 ✔
500
    if (std::any_of(resolved.cbegin(), resolved.cend(),
81 ✔
501
                    [&user](const UserInfo &key) {
502
                      return key.key_id == user.key_id;
94 ✔
503
                    })) {
504
      user.enabled = true;
50 ✔
505
    }
506
  }
507
  // Only what gpg itself cannot find is reported missing. A per-line answer
508
  // is gpg's own verdict for that line and decides it outright; that also
509
  // keeps a genuinely unreadable line ("0x") reported missing. Any other
510
  // line is missing when no key gpg resolved answers to it: the full listing
511
  // carries every user ID and subkey, so nothing is left for gpg to add.
512
  for (const QString &recipient : std::as_const(recipients)) {
6,140 ✔
513
    UserInfo missing;
6,102 ✔
514
    missing.key_id = recipient;
6,102 ✔
515
    if (notLookedUp.contains(recipient)) {
6,102 ✔
516
      missing.name = " ?? " + tr("Not looked up in keyring");
1 ✔
517
      m_notLookedUp.insert(recipient);
1 ✔
518
      m_userList.append(missing);
519
      continue;
520
    }
521
    const auto cached = perLineHasKey.constFind(recipient);
6,101 ✔
522
    const bool found = cached != perLineHasKey.constEnd()
523
                           ? cached.value()
14 ✔
524
                           : std::any_of(resolved.cbegin(), resolved.cend(),
6,087 ✔
525
                                         [&recipient](const UserInfo &key) {
526
                                           return answersTo(key, recipient);
12,142 ✔
527
                                         });
6,087 ✔
528
    if (!found) {
6,101 ✔
529
      missing.enabled = true;
6,057 ✔
530
      missing.name = " ?? " + tr("Key not found in keyring");
12,114 ✔
531
      m_userList.append(missing);
532
    }
533
  }
6,102 ✔
534
}
38 ✔
535

536
void UsersDialog::loadRecipients() {
68 ✔
537
  // A store that had no list when it was chosen (a new profile): a list
538
  // that appeared since is nobody's choice, and was read under the active
539
  // backend's signing policy, not the new profile's.
540
  if (m_preselect == Preselect::Nothing) {
68 ✔
541
    return;
4 ✔
542
  }
543
  // Through the backend: with a signing key only a verified list may be
544
  // preselected, since OK signs whatever is selected.
545
  const Pass::RecipientsForEditing loaded =
546
      m_pass->recipientsForEditing(m_dir, m_passStore);
64 ✔
547
  m_listRead = true;
64 ✔
548
  m_readState = static_cast<int>(loaded.state);
64 ✔
549
  m_readRecipients = loaded.recipients;
550
  if (!loaded.warning.isEmpty()) {
64 ✔
551
    showRecipientWarning(loaded.warning);
16 ✔
552
  }
553
  // A folder without .gpg-id (new store, new profile) has no recipients yet;
554
  // listKeys() with no filter would return the whole keyring, preselected.
555
  if (loaded.state != Pass::RecipientsForEditing::State::Rejected &&
64 ✔
556
      !loaded.recipients.isEmpty()) {
557
    selectRecipients(loaded.recipients);
45 ✔
558
  }
559
}
560

561
UsersDialog::~UsersDialog() = default;
138 ✔
562

563
auto UsersDialog::listChangedSinceRead() const -> bool {
8 ✔
564
  const Pass::RecipientsForEditing now =
565
      m_pass->recipientsForEditing(m_dir, m_passStore);
8 ✔
566
  return static_cast<int>(now.state) != m_readState ||
8 ✔
567
         now.recipients != m_readRecipients;
8 ✔
568
}
569

570
void UsersDialog::accept() {
12 ✔
571
  if (!hasSelection()) {
12 ✔
572
    // Nothing to encrypt to: an empty .gpg-id would make every insert fail
573
    // and the wizard never offers this dialog again once the file exists.
574
    return;
575
  }
576
  // OK writes the whole selection, ticked from the list as it was read. A
577
  // newer list that arrived meanwhile (a pull the watchdog let run on under
578
  // the dialog, a sync) would be overwritten by the old one plus the user's
579
  // change: someone just removed came back, signed as the next generation.
580
  if (m_listRead && listChangedSinceRead()) {
10 ✔
581
    QMessageBox::warning(
2 ✔
582
        this, tr("Recipients not changed"),
1 ✔
583
        tr("The recipient list of this folder changed while this dialog was "
1 ✔
584
           "open, for example through an update from Git. OK would have "
585
           "written the old list back. Close this dialog and open it again "
586
           "to see the new list."));
587
    return;
1 ✔
588
  }
589
  if (m_initOnAccept) {
9 ✔
590
    if (m_listRead) {
6 ✔
591
      // Compared again by the backend at the last point before it writes:
592
      // a pull in a terminal can still land between here and there.
593
      Pass::RecipientsForEditing read;
6 ✔
594
      read.state = static_cast<Pass::RecipientsForEditing::State>(m_readState);
6 ✔
595
      read.recipients = m_readRecipients;
596
      // Refused there (changed after all, or another operation runs): the
597
      // dialog stays open with the selection, as the message asks to save
598
      // again.
599
      if (!m_pass->initIfUnchanged(m_dir, m_userList, m_dir, m_passStore,
6 ✔
600
                                   read)) {
601
        return;
602
      }
603
    } else {
604
      m_pass->Init(m_dir, m_userList);
×
605
    }
606
  }
607

608
  QDialog::accept();
8 ✔
609
}
610

611
auto UsersDialog::hasSelection() const -> bool {
167 ✔
612
  return std::any_of(m_userList.cbegin(), m_userList.cend(),
613
                     [](const UserInfo &user) { return user.enabled; });
250 ✔
614
}
615

616
void UsersDialog::updateOkButton() {
152 ✔
617
  if (auto *ok = ui->buttonBox->button(QDialogButtonBox::Ok)) {
152 ✔
618
    ok->setEnabled(hasSelection());
152 ✔
619
  }
620
}
152 ✔
621

622
void UsersDialog::keyPressEvent(QKeyEvent *event) {
1 ✔
623
  switch (event->key()) {
1 ✔
624
  case Qt::Key_Escape:
1 ✔
625
    ui->lineEdit->clear();
1 ✔
626
    break;
1 ✔
627
  default:
628
    break;
629
  }
630
}
1 ✔
631

632
void UsersDialog::itemChange(QListWidgetItem *item) {
139 ✔
633
  if (!item) {
139 ✔
634
    return;
80 ✔
635
  }
636
  bool ok = false;
139 ✔
637
  const int index = item->data(Qt::UserRole).toInt(&ok);
139 ✔
638
  if (!ok) {
139 ✔
639
    qCWarning(lcQtPass)
158 ✔
640
        << "UsersDialog::itemChange: invalid user index data for item";
79 ✔
641
    return;
79 ✔
642
  }
643
  if (index < 0 || index >= m_userList.size()) {
60 ✔
644
    qCWarning(lcQtPass) << "UsersDialog::itemChange: user index out of range:"
2 ✔
645
                        << index << "valid range is [0,"
1 ✔
646
                        << (m_userList.size() - 1) << "]";
1 ✔
647
    return;
1 ✔
648
  }
649
  m_userList[index].enabled = item->checkState() == Qt::Checked;
59 ✔
650
  updateOkButton();
59 ✔
651
}
652

653
void UsersDialog::populateList(const QString &filter) {
93 ✔
654
  // Invalidate cached datetime so expiry checks use fresh current time
655
  m_cachedDateTimeValid = false;
93 ✔
656

657
  QString patternString = "*" + filter + "*";
93 ✔
658
  if (m_cachedPatternString != patternString) {
93 ✔
659
    // A user ID is not a path: "*" and "?" must match a "/" as well, or a
660
    // key named "ACME A/S" or "(dev/ops)" drops out of the search and stays
661
    // ticked unseen while the listed rows are unticked.
662
    QRegularExpression re(
663
        QRegularExpression::wildcardToRegularExpression(
168 ✔
664
            patternString, QRegularExpression::NonPathWildcardConversion),
665
        QRegularExpression::CaseInsensitiveOption);
84 ✔
666
    if (re.isValid()) {
84 ✔
667
      m_cachedNameFilter = re;
84 ✔
668
      m_cachedPatternString = patternString;
84 ✔
669
    }
670
  }
84 ✔
671
  const QRegularExpression &nameFilter = m_cachedNameFilter;
93 ✔
672
  // Sorted once at the end: with sorting on, each badge and tick below
673
  // re-sorted every row added so far, and a .gpg-id of thousands of
674
  // unknown recipients kept the dialog from opening for minutes.
675
  ui->listWidget->setSortingEnabled(false);
93 ✔
676
  ui->listWidget->clear();
93 ✔
677

678
  for (int i = 0; i < m_userList.size(); ++i) {
6,368 ✔
679
    const auto &user = m_userList.at(i);
680
    if (!passesFilter(user, filter, nameFilter)) {
6,275 ✔
681
      continue;
27 ✔
682
    }
683

684
    auto *item = new QListWidgetItem(buildUserText(user), ui->listWidget);
6,248 ✔
685
    applyUserStyling(item, user);
6,248 ✔
686
    item->setCheckState(user.enabled ? Qt::Checked : Qt::Unchecked);
6,340 ✔
687
    item->setData(Qt::UserRole, QVariant::fromValue(i));
6,248 ✔
688
    ui->listWidget->addItem(item);
6,248 ✔
689
  }
690
  // setSortingEnabled() only sets the flag; sortItems() sorts.
691
  ui->listWidget->sortItems();
93 ✔
692
  ui->listWidget->setSortingEnabled(true);
93 ✔
693
  updateOkButton();
93 ✔
694
}
93 ✔
695

696
bool UsersDialog::passesFilter(const UserInfo &user, const QString &filter,
6,275 ✔
697
                               const QRegularExpression &nameFilter) const {
698
  if (!filter.isEmpty() && !nameFilter.match(user.name).hasMatch()) {
6,289 ✔
699
    return false;
700
  }
701
  // A ticked key is one the folder is encrypted to: it is shown whatever
702
  // its state, or an expired or missing recipient stays in .gpg-id unseen and
703
  // cannot be unticked. "Show unusable keys" is about keys to add. A line
704
  // listed unticked without a lookup is shown too: OK would drop it unseen.
705
  if (user.enabled || ui->checkBox->isChecked() ||
6,261 ✔
706
      m_notLookedUp.contains(user.key_id)) {
96 ✔
707
    return true;
6,166 ✔
708
  }
709
  return user.isValid() && !isUserExpired(user);
87 ✔
710
}
711

712
auto UsersDialog::isUserExpired(const UserInfo &user) const -> bool {
6,335 ✔
713
  if (!m_cachedDateTimeValid) {
6,335 ✔
714
    m_cachedCurrentDateTime = QDateTime::currentDateTime();
90 ✔
715
    m_cachedDateTimeValid = true;
90 ✔
716
  }
717
  // gpg marks a key it already judged expired with validity 'e'.
718
  return user.validity == 'e' ||
12,668 ✔
719
         (user.expiry.isValid() && m_cachedCurrentDateTime > user.expiry);
6,342 ✔
720
}
721

722
namespace {
723
/**
724
 * @brief Text cut to a length a list row can draw at once.
725
 *
726
 * A .gpg-id line no key answers to is shown as written, up to the 1 MiB the
727
 * list may hold: Qt elided such a row on every paint in time quadratic in
728
 * its tabs and script changes, and the dialog hung for minutes. No user ID
729
 * or key ID is this long.
730
 * @param text A user ID or key ID.
731
 * @return The text, or its first 256 characters followed by an ellipsis;
732
 *         a surrogate pair is never split.
733
 */
734
auto shortened(const QString &text) -> QString {
12,496 ✔
735
  constexpr qsizetype kMaxShown = 256;
736
  if (text.size() <= kMaxShown) {
12,496 ✔
737
    return text;
738
  }
739
  qsizetype cut = kMaxShown;
740
  if (text.at(cut - 1).isHighSurrogate()) {
1 ✔
741
    --cut;
742
  }
743
  return text.left(cut) + QChar(0x2026);
2 ✔
744
}
745
} // namespace
746

747
QString UsersDialog::buildUserText(const UserInfo &user) const {
6,248 ✔
748
  // One line for the user ID: a line separator in it (gpg escapes only
749
  // ASCII) drew a line that looked like the key's fingerprint.
750
  // The key ID too: a recipient no key answers to is the .gpg-id line as
751
  // written, which may hold the same separators.
752
  QString text = Util::displayable(shortened(user.name), false) + "\n" +
12,496 ✔
753
                 Util::displayable(shortened(user.key_id), false);
12,496 ✔
754
  if (user.created.isValid()) {
6,248 ✔
755
    text += " " + tr("created") + " " +
334 ✔
756
            QLocale::system().toString(user.created, QLocale::ShortFormat);
501 ✔
757
  }
758
  if (user.expiry.isValid()) {
6,248 ✔
759
    text += " " + tr("expires") + " " +
12 ✔
760
            QLocale::system().toString(user.expiry, QLocale::ShortFormat);
18 ✔
761
  }
762
  return text;
6,248 ✔
763
}
764

765
void UsersDialog::applyUserStyling(QListWidgetItem *item,
6,248 ✔
766
                                   const UserInfo &user) const {
767
  const QString originalText = item->text();
6,248 ✔
768
  // Status badge first: an own key can be expired too, and then the marker
769
  // matters more than the "you can decrypt with this" colour.
770
  bool badged = true;
771
  // Expired before invalid: gpg gives an expired key validity 'e', which is
772
  // not a valid one, and "expired" says what to do about it.
773
  if (isUserExpired(user)) {
6,248 ✔
774
    // A lone dark-red foreground is unreadable on dark themes, and gpg
775
    // refuses to encrypt to expired keys anyway.
776
    item->setBackground(Qt::darkRed);
6 ✔
777
    item->setForeground(Qt::white);
6 ✔
778
    item->setText(tr("[EXPIRED] ") + originalText);
12 ✔
779
  } else if (!user.isValid()) {
780
    item->setBackground(Qt::darkRed);
6,084 ✔
781
    item->setForeground(Qt::white);
6,084 ✔
782
    item->setText(tr("[INVALID] ") + originalText);
12,168 ✔
783
  } else if (!user.fullyValid()) {
158 ✔
784
    item->setBackground(Qt::darkYellow);
7 ✔
785
    item->setForeground(Qt::white);
7 ✔
786
    item->setText(tr("[PARTIAL] ") + originalText);
14 ✔
787
  } else {
788
    item->setText(originalText);
151 ✔
789
    badged = false;
790
  }
791
  if (user.have_secret) {
6,248 ✔
792
    if (!badged) {
7 ✔
793
      item->setForeground(QApplication::palette().color(QPalette::Link));
14 ✔
794
    }
795
    QFont font = item->font();
7 ✔
796
    font.setBold(true);
797
    item->setFont(font);
7 ✔
798
  }
7 ✔
799
}
6,248 ✔
800

801
void UsersDialog::on_lineEdit_textChanged(const QString &filter) {
14 ✔
802
  populateList(filter);
14 ✔
803
}
14 ✔
804

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

807
void UsersDialog::selectImportedKey(const QString &importedKey) {
2 ✔
808
  // The stored key_id, not the item text.
809
  for (int i = 0; i < ui->listWidget->count(); ++i) {
4 ✔
810
    QListWidgetItem *item = ui->listWidget->item(i);
4 ✔
811
    bool ok = false;
4 ✔
812
    const int idx = item != nullptr ? item->data(Qt::UserRole).toInt(&ok) : -1;
4 ✔
813
    if (ok && idx >= 0 && idx < m_userList.size() &&
8 ✔
814
        !m_userList[idx].key_id.isEmpty() &&
8 ✔
815
        keyIdsMatch(m_userList[idx].key_id, importedKey)) {
4 ✔
816
      ui->listWidget->setCurrentItem(item);
2 ✔
817
      return;
2 ✔
818
    }
819
  }
820
}
821

822
void UsersDialog::on_importKeyButton_clicked() {
3 ✔
823
  ImportKeyDialog dialog(m_gpgExe, this);
3 ✔
824
  if (dialog.exec() != QDialog::Accepted) {
3 ✔
825
    return;
826
  }
827

828
  // Non-empty after Accepted, but an empty id would make the endsWith()
829
  // below match the first listed key.
830
  const QString importedKey = dialog.importedKeyId();
2 ✔
831
  if (importedKey.isEmpty()) {
2 ✔
832
    return;
833
  }
834

835
  // loadGpgKeys() rebuilds the key list from the keyring and drops every tick.
836
  // Remember which recipients were selected (the .gpg-id list and the user's
837
  // own ticks, including any "key not found" rows) and re-apply them after, so
838
  // importing a key does not silently remove the other recipients.
839
  QStringList selected;
2 ✔
840
  for (const UserInfo &user : std::as_const(m_userList)) {
4 ✔
841
    if (user.enabled) {
2 ✔
842
      selected.append(user.key_id);
2 ✔
843
    }
844
  }
845

846
  if (!loadGpgKeys()) {
2 ✔
847
    return;
848
  }
849

850
  // Re-apply the remembered selection. Most saved identifiers are a key ID that
851
  // is in the rebuilt list, so match those exactly first (no gpg lookup). An
852
  // identifier that does not match a row is one that was listed as "key not
853
  // found" - a short ID or email that gpg could not resolve, or whose key has
854
  // just been imported and now shows under its fingerprint. Hand those to
855
  // selectRecipients(), which resolves each against the refreshed keyring,
856
  // ticks the matching row, and re-adds a "key not found" row for any that
857
  // still does not resolve.
858
  QStringList unresolved;
2 ✔
859
  for (const QString &keyId : std::as_const(selected)) {
4 ✔
860
    bool matched = false;
861
    for (UserInfo &user : m_userList) {
6 ✔
862
      if (user.key_id == keyId) {
4 ✔
863
        user.enabled = true;
2 ✔
864
        matched = true;
865
      }
866
    }
867
    if (!matched) {
2 ✔
868
      unresolved.append(keyId);
869
    }
870
  }
871
  if (!unresolved.isEmpty()) {
2 ✔
872
    selectRecipients(unresolved);
×
873
  }
874

875
  // Clear the filter so the just-imported key is visible. setText("") still
876
  // emits textChanged once, so don't double-populate.
877
  {
878
    const QSignalBlocker blocker(ui->lineEdit);
2 ✔
879
    ui->lineEdit->clear();
2 ✔
880
  }
2 ✔
881
  populateList(QString());
2 ✔
882

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