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

IJHack / QtPass / 46145082501

28 Nov 2026 12:31PM UTC coverage: 94.435% (+0.05%) from 94.384%
46145082501

push

github

web-flow
Users dialog: tick the keys the list encrypts to, not search matches (#2380)

The Users dialog ticked every key `gpg --list-keys` returned for a
folder's .gpg-id lines, and OK saves what is ticked. That search also
finds keys that only resemble a recipient, decided by whoever made the
key: a user ID containing a recipient's address, or a recipient's
subkey bound to another key. After importing such an update, OK without
looking added that key to the folder's signed list.

Pass::encryptionReaches() does a throwaway encryption to the lines
(outside the store, --no-throw-keyids, --no-auto-key-locate) and reads
back the key IDs it went to; the dialog ticks exactly those rows. A
reached ID that matches more than one row (a shared subkey) ticks only
a row whose primary key a line names; any other line is kept as
written. When gpg cannot encrypt to the list as a whole, does not say
whom it encrypted to, or reaches a key without a row, the search is
used as before.

Tests: a look-alike user ID is listed but not ticked; a shared subkey
ticks only the key a fingerprint line names and keeps an address line
as written. Each fails with its guard disabled.

Scan finding ANT-2026-8Z9SUHAD.

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

63 of 66 new or added lines in 2 files covered. (95.45%)

1 existing line in 1 file now uncovered.

10572 of 11195 relevant lines covered (94.44%)

24930.09 hits per line

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

95.84
/src/pass.cpp
1
// SPDX-FileCopyrightText: 2016 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
/**
4
 * @file
5
 * @brief Implements what both backends share: the environment the store's
6
 * processes run in, the refusals for links and paths outside the store, `.gpg-
7
 * id` lookup, and Pass::finished(), which routes each finished process to its
8
 * signal.
9
 */
10
#include "pass.h"
11

12
#include "gpgidgeneration.h"
13
#include "gpgidsigner.h"
14
#include "gpgkeystate.h"
15
#include "pathvalidator.h"
16
#include "processinfo.h"
17
#include "util.h"
18
#include <QCoreApplication>
19
#include <QDebug>
20
#include <QDir>
21
#include <QFile>
22
#include <QFileInfo>
23
#include <QHash>
24
#include <QLocale>
25
#include <QProcess>
26
#include <QRandomGenerator>
27
#include <QRegularExpression>
28
#include <QSaveFile>
29
#include <QScopeGuard>
30
#include <QTemporaryDir>
31
#include <QTextStream>
32
#include <algorithm>
33
#include <array>
34
#include <optional>
35
#include <utility>
36

37
#include "qtpasslogging.h"
38

39
using Enums::GIT_INIT;
40
using Enums::GIT_PULL;
41
using Enums::GIT_PUSH;
42
using Enums::GPG_GENKEYS;
43
using Enums::PASS_COPY;
44
using Enums::PASS_INIT;
45
using Enums::PASS_INSERT;
46
using Enums::PASS_MOVE;
47
using Enums::PASS_REMOVE;
48
using Enums::PASS_SHOW;
49

50
namespace {
51
auto fallbackCharset(const QString &input, const QString &fallback) -> QString {
52
  return input.isEmpty() ? fallback : input;
1,682 ✔
53
}
54

55
auto effectiveCharset(const PasswordConfiguration &passConfig) -> QString {
475 ✔
56
  int sel = passConfig.selected;
475 ✔
57
  if (sel < 0 || sel >= PasswordConfiguration::CHARSETS_COUNT)
475 ✔
58
    sel = PasswordConfiguration::ALLCHARS;
59
  return fallbackCharset(
60
      passConfig.Characters[sel],
475 ✔
61
      passConfig.Characters[PasswordConfiguration::ALLCHARS]);
475 ✔
62
}
63

64
/**
65
 * @brief Add @p names to WSLENV in @p env, keeping its entries and adding no
66
 * duplicate.
67
 * @param env The environment to amend.
68
 * @param names WSLENV entries, each a variable name with its flags.
69
 */
70
void mergeIntoWslenv(QProcessEnvironment &env, const QStringList &names) {
937 ✔
71
  QStringList parts = env.value(QStringLiteral("WSLENV"))
1,874 ✔
72
                          .split(QLatin1Char(':'), Qt::SkipEmptyParts);
937 ✔
73
  for (const QString &name : names) {
5,596 ✔
74
    if (!parts.contains(name)) {
4,659 ✔
75
      parts.append(name);
76
    }
77
  }
78
  env.insert(QStringLiteral("WSLENV"), parts.join(QLatin1Char(':')));
1,874 ✔
79
}
937 ✔
80
} // namespace
81

82
Pass::Pass() : env(QProcessEnvironment::systemEnvironment()) {
462 ✔
83
  connect(&exec, &Executor::finished, this, &Pass::finished);
462 ✔
84
  connect(&exec, &Executor::error, this, &Pass::finished);
462 ✔
85

86
  connect(&exec, &Executor::starting, this, &Pass::startingExecuteWrapper);
462 ✔
87
  connect(&exec, &Executor::drained, this, [this] {
462 ✔
88
    // Idle means the queue is empty and nothing runs, so no insert is in
89
    // flight: force the pending count to zero. A report that never arrived
90
    // (the "No such transaction" path in ImitatePass::finished(), or any
91
    // later change that drops an insert without reporting) would otherwise
92
    // leave the count one too high for the rest of the session, and every
93
    // later dialog would take its own report for an earlier one and wait for
94
    // ever. Idle cannot fall between a dialog's insertsPending() read and its
95
    // own report, since that insert keeps the executor busy.
96
    m_insertsPending = 0;
133 ✔
97
    m_insertedEntries.clear();
133 ✔
98
    emit idle();
133 ✔
99
  });
133 ✔
100
  // Each queued process starts in the environment as the store is then:
101
  // the Git pin is judged at that moment (dequeuing() comes just before the
102
  // start, on this thread).
103
  connect(&exec, &Executor::dequeuing, this, [this](int, bool completes) {
462 ✔
104
    if (completes) {
371 ✔
105
      exec.setEnvironment(withCurrentGitPin(env));
363 ✔
106
    }
107
  });
371 ✔
108
  // Merge our vars into WSLENV rather than blindly appending a duplicate
109
  // entry. WSLENV flags: /p translates the path, /u forwards from Windows
110
  // into WSL only; /w would be the other direction, from WSL out, and leaves
111
  // pass inside WSL without the value. Everything updateEnv() sets for pass
112
  // has to cross, the signing key above all: without it pass does not check
113
  // the .gpg-id signature.
114
  const QStringList wslenvVars = {
115
      QStringLiteral("PASSWORD_STORE_DIR/p"),
924 ✔
116
      QStringLiteral("PASSWORD_STORE_SIGNING_KEY/u"),
462 ✔
117
      QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH/u"),
462 ✔
118
      QStringLiteral("PASSWORD_STORE_CHARACTER_SET/u"),
462 ✔
119
      QStringLiteral("PASSWORD_STORE_GPG_OPTS/u"),
462 ✔
120
      QStringLiteral("GIT_CEILING_DIRECTORIES/p"),
462 ✔
121
      QStringLiteral("GIT_LITERAL_PATHSPECS/u")};
3,696 ✔
122
  mergeIntoWslenv(env, wslenvVars);
462 ✔
123
}
462 ✔
124

125
void Pass::executeWrapper(PROCESS id, const QString &app,
2 ✔
126
                          const QStringList &args, bool readStdout,
127
                          bool readStderr) {
128
  executeWrapper(id, app, args, QString(), readStdout, readStderr);
2 ✔
129
}
2 ✔
130

131
void Pass::executeWrapper(PROCESS id, const QString &app,
371 ✔
132
                          const QStringList &args, QString input,
133
                          bool readStdout, bool readStderr) {
134
  beforeExecute(id);
371 ✔
135
  qCDebug(lcQtPass) << app << loggableArgs(args);
371 ✔
136
  exec.execute(id, m_settings.passStore, app, args, std::move(input),
371 ✔
137
               readStdout, readStderr);
138
}
371 ✔
139

140
auto Pass::loggableArgs(const QStringList &args) -> QStringList {
4 ✔
141
  // Secrets travel on stdin (Insert's content, KeygenDialog's batch file),
142
  // never in argv; this keeps the log honest should that ever change.
143
  static const QStringList secretOptions{
144
      QStringLiteral("--passphrase"), QStringLiteral("--override-session-key")};
26 ✔
145
  QStringList out;
4 ✔
146
  bool hide = false;
147
  for (const QString &arg : args) {
12 ✔
148
    if (hide) {
8 ✔
149
      out << QStringLiteral("<redacted>");
1 ✔
150
      hide = false;
151
      continue;
1 ✔
152
    }
153
    if (arg.startsWith(QStringLiteral("otpauth://"))) {
14 ✔
154
      out << QStringLiteral("<redacted>");
1 ✔
155
      continue;
1 ✔
156
    }
157
    if (arg.startsWith(QStringLiteral("--passphrase=")) ||
12 ✔
158
        arg.startsWith(QStringLiteral("--override-session-key="))) {
11 ✔
159
      out << arg.left(arg.indexOf(u'=') + 1) + QStringLiteral("<redacted>");
2 ✔
160
      continue;
1 ✔
161
    }
162
    hide = secretOptions.contains(arg);
163
    out << arg;
164
  }
165
  return out;
4 ✔
166
}
167

168
void Pass::beforeExecute(PROCESS /*id*/) {}
87 ✔
169

170
void Pass::init(const AppSettings &settings) {
920 ✔
171
  m_settings = settings;
920 ✔
172
#ifdef __APPLE__
173
  // If it exists, prepend gpgtools to PATH
174
  if (QFile(QStringLiteral("/usr/local/MacGPG2/bin")).exists())
175
    env.insert(QStringLiteral("PATH"),
176
               QStringLiteral("/usr/local/MacGPG2/bin:") +
177
                   env.value(QStringLiteral("PATH")));
178
  // Add missing /usr/local/bin (exact component match, no leading colon)
179
  const QString currentPath = env.value(QStringLiteral("PATH"));
180
  if (!currentPath.split(':', Qt::SkipEmptyParts)
181
           .contains(QStringLiteral("/usr/local/bin"))) {
182
    env.insert(QStringLiteral("PATH"),
183
               currentPath.isEmpty()
184
                   ? QStringLiteral("/usr/local/bin")
185
                   : QStringLiteral("/usr/local/bin:") + currentPath);
186
  }
187
#endif
188

189
  // The configured gpgHome wins over GNUPGHOME only when it exists: a stale
190
  // one (#1711) fails every gpg call with "No secret key". Clearing the
191
  // setting restores the inherited value rather than keeping the old path.
192
  const QString inheritedHome = QProcessEnvironment::systemEnvironment().value(
1,840 ✔
193
      QStringLiteral("GNUPGHOME"));
1,840 ✔
194
  const auto useInheritedHome = [this, &inheritedHome]() {
862 ✔
195
    if (inheritedHome.isEmpty()) {
862 ✔
196
      env.remove(QStringLiteral("GNUPGHOME"));
1,192 ✔
197
    } else {
198
      env.insert(QStringLiteral("GNUPGHOME"), inheritedHome);
532 ✔
199
    }
200
  };
1,782 ✔
201
  if (m_settings.gpgHome.isEmpty()) {
920 ✔
202
    useInheritedHome();
860 ✔
203
  } else {
204
    QDir absHome(m_settings.gpgHome);
60 ✔
205
    absHome.makeAbsolute();
60 ✔
206
    if (absHome.exists()) {
60 ✔
207
      env.insert(QStringLiteral("GNUPGHOME"), absHome.path());
116 ✔
208
    } else {
209
      if (inheritedHome.isEmpty()) {
2 ✔
210
        qCWarning(lcQtPass) << "gpgHome" << absHome.path()
2 ✔
211
                            << "does not exist; using the default GnuPG home";
1 ✔
212
        emit statusMsg(tr("Configured GPG home %1 does not exist, using the "
1 ✔
213
                          "default keyring")
214
                           .arg(absHome.path()),
2 ✔
215
                       5000);
216
      } else {
217
        qCWarning(lcQtPass)
2 ✔
218
            << "gpgHome" << absHome.path() << "does not exist; using GNUPGHOME"
2 ✔
219
            << inheritedHome << "from the environment";
1 ✔
220
        emit statusMsg(tr("Configured GPG home %1 does not exist, using "
1 ✔
221
                          "GNUPGHOME %2 from the environment")
222
                           .arg(absHome.path(), inheritedHome),
2 ✔
223
                       5000);
224
      }
225
      useInheritedHome();
2 ✔
226
    }
227
  }
60 ✔
228
}
920 ✔
229

230
auto Pass::generatePassword(unsigned int length, const QString &charset)
1,211 ✔
231
    -> QString {
232
  if (length == 0) {
1,211 ✔
233
    emit critical(tr("Invalid password length"),
2 ✔
234
                  tr("Can't generate password with zero length."));
1 ✔
235
    return {};
1 ✔
236
  }
237
  QString passwd;
1,210 ✔
238
  if (m_settings.usePwgen) {
1,210 ✔
239
    // --secure goes first as it overrides --no-* otherwise
240
    QStringList args;
3 ✔
241
    args.append("-1");
3 ✔
242
    if (!m_settings.lessRandom) {
3 ✔
243
      args.append("--secure");
4 ✔
244
    }
245
    args.append(m_settings.avoidCapitals ? "--no-capitalize" : "--capitalize");
5 ✔
246
    args.append(m_settings.avoidNumbers ? "--no-numerals" : "--numerals");
5 ✔
247
    if (m_settings.useSymbols) {
3 ✔
248
      args.append("--symbols");
2 ✔
249
    }
250
    args.append(QString::number(length));
3 ✔
251
    if (Executor::executeBlocking(m_settings.pwgenExecutable, args, &passwd) ==
3 ✔
252
        0) {
253
      static const QRegularExpression literalNewLines{"[\\n\\r]"};
3 ✔
254
      passwd.remove(literalNewLines);
2 ✔
255
    } else {
256
      passwd.clear();
1 ✔
257
      qCDebug(lcQtPass) << "pwgen fail";
1 ✔
258
      // Report it, as the other generation failures do: otherwise Generate
259
      // does nothing silently and OK then saves an empty (or, on Edit, the
260
      // old) password.
261
      emit critical(
1 ✔
262
          tr("Password generation failed"),
1 ✔
263
          tr("Could not run pwgen (\"%1\"). Check the pwgen program in the "
1 ✔
264
             "settings, or turn \"Use pwgen\" off.")
265
              .arg(m_settings.pwgenExecutable));
2 ✔
266
    }
267
  } else {
268
    // An empty CUSTOM charset falls back to ALLCHARS, not a weak password
269
    // (#780).
270
    const QString cs = fallbackCharset(
271
        charset, m_settings.passwordConfiguration
272
                     .Characters[PasswordConfiguration::ALLCHARS]);
1,207 ✔
273
    if (cs.length() > 0) {
1,207 ✔
274
      passwd = generateRandomPassword(cs, length);
2,412 ✔
275
    } else {
276
      emit critical(
1 ✔
277
          tr("No characters chosen"),
1 ✔
278
          tr("Can't generate password, there are no characters to choose from "
1 ✔
279
             "set in the configuration!"));
280
    }
281
  }
282
  return passwd;
283
}
284

285
bool Pass::gpgSupportsEd25519(const QString &gpgExecutable) {
41 ✔
286
  const QString exe =
287
      gpgExecutable.isEmpty() ? QStringLiteral("gpg") : gpgExecutable;
41 ✔
288
  QString out, err;
41 ✔
289
  if (Executor::executeBlocking(exe, {"--version"}, &out, &err) != 0) {
164 ✔
290
    return false;
291
  }
292
  QRegularExpression versionRegex(R"(gpg \(GnuPG\) (\d+)\.(\d+))");
39 ✔
293
  QRegularExpressionMatch match = versionRegex.match(out);
39 ✔
294
  if (!match.hasMatch()) {
39 ✔
295
    return false;
296
  }
297
  int major = match.captured(1).toInt();
38 ✔
298
  int minor = match.captured(2).toInt();
38 ✔
299
  return major > 2 || (major == 2 && minor >= 1);
38 ✔
300
}
39 ✔
301

302
// ed25519 (GnuPG 2.1+) generates much faster than RSA.
303
QString Pass::getDefaultKeyTemplate(const QString &gpgExecutable) {
37 ✔
304
  if (gpgSupportsEd25519(gpgExecutable)) {
37 ✔
305
    return QStringLiteral("%echo Generating a default key\n"
34 ✔
306
                          "Key-Type: EdDSA\n"
307
                          "Key-Curve: Ed25519\n"
308
                          "Subkey-Type: ECDH\n"
309
                          "Subkey-Curve: Curve25519\n"
310
                          "Name-Real: \n"
311
                          "Name-Comment: QtPass\n"
312
                          "Name-Email: \n"
313
                          "Expire-Date: 0\n"
314
                          "%no-protection\n"
315
                          "%commit\n"
316
                          "%echo done");
317
  }
318
  return QStringLiteral("%echo Generating a default key\n"
3 ✔
319
                        "Key-Type: RSA\n"
320
                        "Subkey-Type: RSA\n"
321
                        "Name-Real: \n"
322
                        "Name-Comment: QtPass\n"
323
                        "Name-Email: \n"
324
                        "Expire-Date: 0\n"
325
                        "%no-protection\n"
326
                        "%commit\n"
327
                        "%echo done");
328
}
329

330
namespace {
331
auto resolveWslGpgconfPath(const QString &lastPart) -> QString {
8 ✔
332
  qsizetype lastSep = lastPart.lastIndexOf('/');
8 ✔
333
  if (lastSep < 0) {
8 ✔
334
    lastSep = lastPart.lastIndexOf('\\');
5 ✔
335
  }
336
  if (lastSep >= 0) {
5 ✔
337
    return lastPart.left(lastSep + 1) + "gpgconf";
6 ✔
338
  }
339
  return QStringLiteral("gpgconf");
5 ✔
340
}
341

342
QString findGpgconfInGpgDir(const QString &gpgPath) {
8 ✔
343
  QFileInfo gpgInfo(gpgPath);
8 ✔
344
  if (!gpgInfo.isAbsolute()) {
8 ✔
345
    return {};
1 ✔
346
  }
347

348
  QDir dir(gpgInfo.absolutePath());
7 ✔
349

350
#ifdef Q_OS_WIN
351
  QFileInfo candidateExe(dir.filePath("gpgconf.exe"));
352
  if (candidateExe.isExecutable()) {
353
    return candidateExe.filePath();
354
  }
355
#endif
356

357
  QFileInfo candidate(dir.filePath("gpgconf"));
7 ✔
358
  if (candidate.isExecutable()) {
7 ✔
359
    return candidate.filePath();
5 ✔
360
  }
361
  return {};
2 ✔
362
}
8 ✔
363

364
} // namespace
365

366
auto Pass::resolveGpgconfCommand(const QString &gpgPath)
22 ✔
367
    -> ResolvedGpgconfCommand {
368
  if (gpgPath.trimmed().isEmpty()) {
22 ✔
369
    return {"gpgconf", {}};
370
  }
371

372
  // WSL: gpgconf next to the configured gpg, same distribution, via --exec
373
  // not the shell. An unparsed form (`wsl sh -c ...`, bare `wsl`) falls back
374
  // to gpgconf on the Windows PATH.
375
  if (const auto wsl = Executor::parseWslCommand(gpgPath)) {
21 ✔
376
    if (!QFileInfo(wsl->command).fileName().startsWith("gpg")) {
18 ✔
377
      return {"gpgconf", {}};
378
    }
379
    const auto gpgconf = wsl->with(resolveWslGpgconfPath(wsl->command));
16 ✔
380
    return {gpgconf.launcher, gpgconf.argv({})};
×
381
  }
8 ✔
382

383
  const QStringList parts = QProcess::splitCommand(gpgPath);
12 ✔
384
  if (parts.isEmpty()) {
12 ✔
385
    return {"gpgconf", {}};
386
  }
387
  const QString first = parts.first();
388
  if (QFileInfo(first).fileName().compare("wsl", Qt::CaseInsensitive) == 0 ||
33 ✔
389
      QFileInfo(first).fileName().compare("wsl.exe", Qt::CaseInsensitive) ==
30 ✔
390
          0) {
391
    return {"gpgconf", {}};
392
  }
393

394
  if (!first.contains('/') && !first.contains('\\')) {
9 ✔
395
    return {"gpgconf", {}};
396
  }
397

398
  QString gpgconfPath = findGpgconfInGpgDir(first);
8 ✔
399
  if (!gpgconfPath.isEmpty()) {
8 ✔
400
    return {gpgconfPath, {}};
5 ✔
401
  }
402

403
  return {"gpgconf", {}};
404
}
22 ✔
405

406
void Pass::GenerateGPGKeys(QString batch) {
12 ✔
407
  const QString gpgPath = m_settings.gpgExecutable;
408
  if (gpgPath.isEmpty()) {
12 ✔
409
    // The executor would fail an empty executable with a generic process
410
    // error; the keygen dialog waits for generateGPGKeysFailed and a reason
411
    // it can show. Queued so we do not re-enter KeygenDialog::done(), which
412
    // drives key generation synchronously.
413
    QMetaObject::invokeMethod(
10 ✔
414
        this,
415
        [this]() {
10 ✔
416
          emit generateGPGKeysFailed(tr("No GPG executable configured"));
5 ✔
417
          emit processErrorExit(1, tr("No GPG executable configured"));
5 ✔
418
        },
5 ✔
419
        Qt::QueuedConnection);
420
    return;
421
  }
422

423
  // A stale gpg-agent holding the key database lock causes "database locked"
424
  // timeouts during key generation.
425
  ResolvedGpgconfCommand resolvedGpgconf = resolveGpgconfCommand(gpgPath);
2 ✔
426
  QStringList killArgs = resolvedGpgconf.arguments;
427
  killArgs << "--kill";
2 ✔
428
  killArgs << "gpg-agent";
2 ✔
429
  // Use same environment as key generation to target correct gpg-agent
430
  if (Executor::executeBlocking(env, resolvedGpgconf.program, killArgs) != 0) {
2 ✔
431
    qCWarning(lcQtPass) << "Failed to kill gpg-agent";
2 ✔
432
  }
433

434
  executeWrapper(GPG_GENKEYS, gpgPath, {"--gen-key", "--no-tty", "--batch"},
16 ✔
435
                 std::move(batch), true, true);
436
}
437

438
auto Pass::encryptionReaches(const QStringList &recipients)
42 ✔
439
    -> std::optional<QStringList> {
440
  if (recipients.isEmpty()) {
42 ✔
NEW
441
    return std::nullopt;
×
442
  }
443
  QTemporaryDir scratch;
42 ✔
444
  if (!scratch.isValid()) {
42 ✔
NEW
445
    return std::nullopt;
×
446
  }
447
  const QString &gpg = m_settings.gpgExecutable;
42 ✔
448
  const QString probe = Executor::translatePathForWsl(
449
      scratch.filePath(QStringLiteral("probe.gpg")), gpg);
84 ✔
450
  // --no-throw-keyids: with throw-keyids in gpg.conf the probe would name
451
  // no one.
452
  QStringList args{QStringLiteral("--batch"),
84 ✔
453
                   QStringLiteral("--no-tty"),
42 ✔
454
                   QStringLiteral("--yes"),
42 ✔
455
                   QStringLiteral("--quiet"),
42 ✔
456
                   QStringLiteral("--no-throw-keyids"),
42 ✔
457
                   QStringLiteral("--no-auto-key-locate"),
42 ✔
458
                   QStringLiteral("--no-encrypt-to"),
42 ✔
459
                   QStringLiteral("--output"),
42 ✔
460
                   probe,
461
                   QStringLiteral("--encrypt")};
504 ✔
462
  for (const QString &recipient : recipients) {
6,156 ✔
463
    args << QStringLiteral("-r") << recipient;
6,114 ✔
464
  }
465
  if (Executor::executeBlocking(gpg, args, QStringLiteral("probe")) != 0) {
84 ✔
466
    return std::nullopt;
4 ✔
467
  }
468
  // As ImitatePass::getKeysFromFile(): --decrypt --list-only, capped.
469
  QString status;
38 ✔
470
  if (Executor::executeBlocking(
456 ✔
471
          gpg,
472
          {QStringLiteral("--batch"), QStringLiteral("--no-tty"),
38 ✔
473
           QStringLiteral("--decrypt"), QStringLiteral("--list-only"),
38 ✔
474
           QStringLiteral("--max-output"), QStringLiteral("1"),
38 ✔
475
           QStringLiteral("--status-fd=1"),
38 ✔
476
           QStringLiteral("--keyid-format=long"), QStringLiteral("--"), probe},
38 ✔
477
          QString(), &status) != 0) {
76 ✔
NEW
478
    return QStringList();
×
479
  }
480
  static const QRegularExpression encTo(
481
      QStringLiteral("^\\[GNUPG:\\] ENC_TO ([0-9A-Fa-f]{16})(?: |$)"));
44 ✔
482
  QStringList ids;
38 ✔
483
  for (const QString &line :
484
       status.split(Util::newLinesRegex(), Qt::SkipEmptyParts)) {
277 ✔
485
    const QRegularExpressionMatch match = encTo.match(line);
201 ✔
486
    if (match.hasMatch()) {
201 ✔
487
      ids << match.captured(1).toUpper();
8 ✔
488
    }
489
  }
201 ✔
490
  return ids;
491
}
42 ✔
492

493
auto Pass::listKeys(QStringList keystrings, bool secret) -> QList<UserInfo> {
196 ✔
494
  QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
1,372 ✔
495
  args.append(secret ? "--list-secret-keys" : "--list-keys");
519 ✔
496

497
  for (const QString &keystring : std::as_const(keystrings)) {
6,483 ✔
498
    if (!keystring.isEmpty()) {
6,287 ✔
499
      args.append(keystring);
500
    }
501
  }
502
  QString p_out;
196 ✔
503
  if (Executor::executeBlocking(m_settings.gpgExecutable, args, &p_out) != 0) {
196 ✔
504
    return {};
10 ✔
505
  }
506
  return parseGpgColonOutput(p_out, secret);
186 ✔
507
}
508

509
auto Pass::listKeys(const QString &keystring, bool secret) -> QList<UserInfo> {
151 ✔
510
  return listKeys(QStringList(keystring), secret);
302 ✔
511
}
512

513
namespace {
514

515
auto containsAny(const QString &str, const QStringList &patterns) -> bool {
127 ✔
516
  for (const QString &p : patterns) {
352 ✔
517
    if (str.contains(p)) {
246 ✔
518
      return true;
519
    }
520
  }
521
  return false;
522
}
523

524
// @p patterns must already be lowercase; only @p str is lowered.
525
auto containsAnyCaseInsensitive(const QString &str, const QStringList &patterns)
107 ✔
526
    -> bool {
527
  const QString lower = str.toLower();
528
  for (const QString &p : patterns) {
265 ✔
529
    if (lower.contains(p)) {
169 ✔
530
      return true;
531
    }
532
  }
533
  return false;
534
}
535

536
} // namespace
537

538
auto gpgErrorMessage(const QString &err) -> QString {
47 ✔
539
  // Machine-readable status tokens added by --status-fd 2
540
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYEXPIRED"),
235 ✔
541
                        QStringLiteral("[GNUPG:] INV_RECP 5 ")}))
47 ✔
542
    return QCoreApplication::translate(
543
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
544
                "replace it.");
5 ✔
545
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYREVOKED"),
210 ✔
546
                        QStringLiteral("[GNUPG:] INV_RECP 4 ")}))
42 ✔
547
    return QCoreApplication::translate(
548
        "Pass", "Encryption failed: GPG key has been revoked.");
4 ✔
549
  if (containsAny(err, {QStringLiteral("[GNUPG:] NO_PUBKEY"),
190 ✔
550
                        QStringLiteral("[GNUPG:] INV_RECP")}))
38 ✔
551
    return QCoreApplication::translate(
552
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
553
                "Check that the key ID in .gpg-id is correct and imported.");
12 ✔
554
  if (err.contains(QStringLiteral("[GNUPG:] FAILURE")))
26 ✔
555
    return QCoreApplication::translate(
556
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1 ✔
557

558
  // Locale-dependent fallbacks
559
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has expired"),
100 ✔
560
                                       QLatin1String("key expired")}))
561
    return QCoreApplication::translate(
562
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
563
                "replace it.");
1 ✔
564
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has been revoked"),
96 ✔
565
                                       QLatin1String("revoked")}))
566
    return QCoreApplication::translate(
567
        "Pass", "Encryption failed: GPG key has been revoked.");
1 ✔
568
  // pass passes no --status-fd, so this is all gpg says about a key that is
569
  // present but cannot encrypt: expired, revoked, without an encryption
570
  // subkey, or not trusted ("There is no assurance this key belongs to the
571
  // named user"). "Not found ... imported" would send the user the wrong
572
  // way; gpg's own lines, shown below this, say which it is.
573
  if (containsAnyCaseInsensitive(err, {QLatin1String("unusable public key")}))
69 ✔
574
    return QCoreApplication::translate(
575
        "Pass", "Encryption failed: a recipient's GPG key cannot be used. It "
576
                "may have expired or been revoked, have no encryption subkey, "
577
                "or not be trusted; gpg's message below says which.");
3 ✔
578
  if (containsAnyCaseInsensitive(err, {QLatin1String("no public key"),
80 ✔
579
                                       QLatin1String("no secret key")}))
580
    return QCoreApplication::translate(
581
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
582
                "Check that the key ID in .gpg-id is correct and imported.");
5 ✔
583
  if (containsAnyCaseInsensitive(err, {QLatin1String("encryption failed")}))
45 ✔
584
    return QCoreApplication::translate(
585
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1 ✔
586

587
  return {};
14 ✔
588
}
×
589

590
void Pass::finished(int id, int exitCode, const QString &out,
319 ✔
591
                    const QString &err) {
592
  auto pid = static_cast<PROCESS>(id);
319 ✔
593

594
  // Pop the Show() this completion belongs to whether it worked or not, or
595
  // the next result would be attributed to the wrong file.
596
  QString shownFile;
319 ✔
597
  if (pid == PASS_SHOW && !m_pendingShows.isEmpty()) {
319 ✔
598
    shownFile = m_pendingShows.dequeue();
80 ✔
599
  }
600
  // Count this insert off, success or failure, before its result goes out, so
601
  // insertsPending() tracks the inserts still awaiting a report. Each insert
602
  // reaches here once as PASS_INSERT.
603
  // Its entry is handed out (reportedInsert()) while the report goes out.
604
  QString reported;
319 ✔
605
  if (pid == PASS_INSERT && m_insertsPending > 0) {
319 ✔
606
    --m_insertsPending;
118 ✔
607
    if (!m_insertedEntries.isEmpty()) {
118 ✔
608
      reported = m_insertedEntries.dequeue();
118 ✔
609
    }
610
  }
611
  m_reportedInsert = reported;
319 ✔
612
  const auto reportedOut = qScopeGuard([this] { m_reportedInsert.clear(); });
319 ✔
613

614
  if (exitCode != 0) {
319 ✔
615
    handleProcessError(pid, exitCode, out, err);
62 ✔
616
    return;
617
  }
618

619
  if (pid == PASS_SHOW) {
257 ✔
620
    emit finishedShow(out, shownFile, exec.lastOutputLossless());
51 ✔
621
    return;
622
  }
623
  emitProcessFinishedSignal(pid, out, err);
206 ✔
624
}
625

626
void Pass::handleProcessError(PROCESS pid, int exitCode, const QString &out,
62 ✔
627
                              const QString &err) {
628
  Q_UNUSED(out);
629

630
  if (pid == PASS_INSERT) {
62 ✔
631
    const QString friendly = gpgErrorMessage(err);
19 ✔
632
    const QString why =
633
        friendly.isEmpty() ? err : formatInsertError(friendly, err);
19 ✔
634
    const bool written = insertWritten(err);
19 ✔
635
    emit insertFailed(why, written);
19 ✔
636
    if (written) {
19 ✔
637
      // The entry is in the store; a git step after it failed (a commit
638
      // that could not be signed, with pass.signcommits, say). The dialog
639
      // closes on this, so say it here rather than only in the output
640
      // panel.
641
      emit critical(tr("Saved, not committed"),
10 ✔
642
                    tr("The entry is saved in the store, but recording it "
5 ✔
643
                       "in git failed. What was reported:\n\n%1")
644
                        .arg(err.trimmed()));
10 ✔
645
    }
646
    emit processErrorExit(exitCode, why);
19 ✔
647
    return;
648
  }
649

650
  if (pid == GPG_GENKEYS) {
43 ✔
651
    emit generateGPGKeysFailed(err);
1 ✔
652
  }
653
  emit processErrorExit(exitCode, err);
43 ✔
654
}
655

656
auto Pass::withoutStatusLines(const QString &err) -> QString {
53 ✔
657
  QStringList humanLines;
53 ✔
658
  for (const QString &line : err.split('\n')) {
1,648 ✔
659
    QString cleanedLine = line;
660
    cleanedLine.remove('\r');
1,542 ✔
661
    if (!cleanedLine.startsWith(QLatin1String("[GNUPG:]")))
1,542 ✔
662
      humanLines.append(cleanedLine);
663
  }
664
  return humanLines.join('\n');
53 ✔
665
}
666

667
auto Pass::formatInsertError(const QString &friendly, const QString &err)
6 ✔
668
    -> QString {
669
  const QString humanErr = withoutStatusLines(err).trimmed();
12 ✔
670
  return humanErr.isEmpty() ? friendly : friendly + "\n\n" + humanErr;
12 ✔
671
}
672

673
void Pass::emitProcessFinishedSignal(PROCESS pid, const QString &out,
206 ✔
674
                                     const QString &err) {
675
  // Only output that cannot contain a secret reaches the generic listeners
676
  // (the output panel among them); Enums::processInfo is the one table.
677
  if (pid >= 0 && pid < Enums::PROCESS_COUNT &&
206 ✔
678
      !Enums::processInfo(pid).secret) {
204 ✔
679
    emit finishedAnyWithPid(out, err, pid);
98 ✔
680
  }
681

682
  // The kind-specific signal. PASS_SHOW is emitted by finished(), which
683
  // knows the file. Content search runs in-process (NativeGrep), not
684
  // through `pass grep`, and emits finishedGrep itself.
685
  using Signal = void (Pass::*)(const QString &, const QString &);
686
  static const QHash<int, Signal> kSignals{
687
      {GIT_INIT, &Pass::finishedGitInit},
688
      {GIT_PULL, &Pass::finishedGitPull},
689
      {GIT_PUSH, &Pass::finishedGitPush},
690
      {PASS_INSERT, &Pass::finishedInsert},
691
      {PASS_REMOVE, &Pass::finishedRemove},
692
      {PASS_INIT, &Pass::finishedInit},
693
      {PASS_MOVE, &Pass::finishedMove},
694
      {PASS_COPY, &Pass::finishedCopy},
695
      {GPG_GENKEYS, &Pass::finishedGenerateGPGKeys},
696
  };
212 ✔
697
  // A store that became a repository after updateEnv() gets its pin now,
698
  // before anything is staged in it.
699
  if (pid == GIT_INIT) {
206 ✔
700
    pinStoreGitAttributes();
3 ✔
701
  }
702
  if (const Signal signal = kSignals.value(pid, nullptr)) {
206 ✔
703
    (this->*signal)(out, err);
202 ✔
704
  }
705
}
206 ✔
706

707
void Pass::setEnvVar(const QString &name, const QString &value) {
4,285 ✔
708
  if (value.isEmpty())
4,285 ✔
709
    env.remove(name);
1,427 ✔
710
  else
711
    env.insert(name, value);
2,858 ✔
712
}
4,285 ✔
713

714
void Pass::updateEnv() {
475 ✔
715
  setEnvVar(QStringLiteral("PASSWORD_STORE_SIGNING_KEY"),
950 ✔
716
            m_settings.passSigningKey);
475 ✔
717
  setEnvVar(QStringLiteral("PASSWORD_STORE_DIR"), m_settings.passStore);
950 ✔
718
  // Every path QtPass hands git names one file or folder: an entry called
719
  // "a*.gpg" must not make `git rm -f -- a*.gpg` remove every entry that
720
  // matches. Also reaches the git that pass runs, which passes names the
721
  // same way.
722
  setEnvVar(QStringLiteral("GIT_LITERAL_PATHSPECS"), QStringLiteral("1"));
950 ✔
723

724
  const PasswordConfiguration &passConfig = m_settings.passwordConfiguration;
475 ✔
725
  setEnvVar(QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH"),
950 ✔
726
            QString::number(passConfig.length));
475 ✔
727

728
  setEnvVar(QStringLiteral("PASSWORD_STORE_CHARACTER_SET"),
950 ✔
729
            effectiveCharset(passConfig));
475 ✔
730

731
  // pass hands PASSWORD_STORE_GPG_OPTS to every gpg it runs: the user's own
732
  // options (split as pass's shell splits them: spaces, tabs, newlines),
733
  // then the output limit ImitatePass passes directly.
734
  QStringList gpgOpts = QProcessEnvironment::systemEnvironment()
475 ✔
735
                            .value(QStringLiteral("PASSWORD_STORE_GPG_OPTS"))
950 ✔
736
                            .split(QRegularExpression(QStringLiteral("\\s+")),
950 ✔
737
                                   Qt::SkipEmptyParts);
950 ✔
738
  gpgOpts << maxOutputArgs();
950 ✔
739
  setEnvVar(QStringLiteral("PASSWORD_STORE_GPG_OPTS"),
950 ✔
740
            gpgOpts.join(QLatin1Char(' ')));
475 ✔
741

742
  // As pass does: git never looks for a repository above the store's own
743
  // parent. A store that is not a repository itself but lies inside one (a
744
  // dotfiles repository in the home folder) would otherwise have its entries
745
  // committed and pushed there by native git mode. Only in the environment
746
  // of the processes QtPass runs for the store, never QtPass's own, which a
747
  // file manager or terminal it opens would inherit. pass sets its own
748
  // ceiling whatever this says. A store kept inside a larger repository on
749
  // purpose opts out (gitUseParentRepository), and then, as without a
750
  // store, whatever ceiling QtPass was started with applies.
751
  // A ceiling git cannot take as one entry (the parent's path holds the
752
  // list separator) is backed by GIT_DIR and GIT_WORK_TREE naming the
753
  // store's own repository (Util::gitStoreVariables()); pass unsets those
754
  // for itself and keeps its own ceiling.
755
  setEnvVar(QStringLiteral("GIT_DIR"), QString());
950 ✔
756
  setEnvVar(QStringLiteral("GIT_WORK_TREE"), QString());
950 ✔
757
  if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
475 ✔
758
    setEnvVar(QStringLiteral("GIT_CEILING_DIRECTORIES"),
40 ✔
759
              qEnvironmentVariable("GIT_CEILING_DIRECTORIES"));
40 ✔
760
  } else {
761
    for (const auto &[name, value] : Util::gitStoreVariables(
762
             m_settings.passStore, m_settings.gitExecutable)) {
1,369 ✔
763
      setEnvVar(name, value);
459 ✔
764
    }
765
  }
766

767
  // Refuse a repository pushed into the store: git started in a folder laid
768
  // out as a bare repository would read its pushed config and run a command
769
  // named there. This reaches the git that pass runs too, which inherits the
770
  // environment.
771
  Util::requireExplicitBareRepository(env);
475 ✔
772
  // pass under WSL needs them too: the count and every entry below it.
773
  QStringList gitConfig{QStringLiteral("GIT_CONFIG_COUNT/u")};
950 ✔
774
  if (env.contains(QStringLiteral("GIT_CONFIG_PARAMETERS"))) {
950 ✔
775
    gitConfig << QStringLiteral("GIT_CONFIG_PARAMETERS/u");
×
776
  }
777
  const int gitConfigCount =
778
      env.value(QStringLiteral("GIT_CONFIG_COUNT")).toInt();
950 ✔
779
  for (int i = 0; i < gitConfigCount; ++i) {
950 ✔
780
    gitConfig << QStringLiteral("GIT_CONFIG_KEY_%1/u").arg(i)
950 ✔
781
              << QStringLiteral("GIT_CONFIG_VALUE_%1/u").arg(i);
950 ✔
782
  }
783
  mergeIntoWslenv(env, gitConfig);
475 ✔
784

785
  exec.setEnvironment(env);
475 ✔
786

787
  pinStoreGitAttributes();
475 ✔
788
}
475 ✔
789

790
void Pass::pinStoreGitAttributes() {
478 ✔
791
  if (m_settings.passStore.isEmpty()) {
478 ✔
792
    return;
469 ✔
793
  }
794
  // Only the common layout, where the store is its own repository, is handled
795
  // by writing directly: a ".git" directory. A worktree ".git" file or a store
796
  // nested in a larger repository is left as-is rather than risk touching
797
  // another repository's attributes.
798
  const QString gitDir =
799
      QDir(m_settings.passStore).absoluteFilePath(QStringLiteral(".git"));
928 ✔
800
  if (!QFileInfo(gitDir).isDir()) {
464 ✔
801
    return;
802
  }
803

804
  // The marker lets us recognise and refresh our own block without disturbing
805
  // anything a user put in info/attributes by hand. Disabling text/eol,
806
  // working-tree-encoding, filter and ident keeps Git from rewriting the
807
  // bytes gpg produced for these paths - a co-writer can push a .gitattributes
808
  // ("*.gpg text", a working-tree-encoding, a filter) that otherwise corrupts
809
  // the ciphertext QtPass commits. info/attributes outranks the in-tree file.
810
  // diff is left alone: it only changes what Git shows, and pass's own
811
  // "*.gpg diff=gpg" gives decrypted diffs.
812
  static const QString marker =
813
      QStringLiteral("# QtPass: keep encrypted store files byte-for-byte");
53 ✔
814
  const QString block =
815
      marker + QStringLiteral("\n") +
98 ✔
816
      QStringLiteral(
98 ✔
817
          "*.gpg -text -filter -ident -working-tree-encoding\n"
818
          ".gpg-id -text -filter -ident -working-tree-encoding\n"
819
          ".gpg-id.sig -text -filter -ident -working-tree-encoding\n");
820

821
  const QString infoDir = gitDir + QStringLiteral("/info");
98 ✔
822
  const QString attrPath = infoDir + QStringLiteral("/attributes");
98 ✔
823

824
  QString existing;
49 ✔
825
  QFile attr(attrPath);
49 ✔
826
  if (attr.exists()) {
49 ✔
827
    // Unreadable: writing now would drop the user's own lines in it.
828
    if (!attr.open(QIODevice::ReadOnly | QIODevice::Text)) {
40 ✔
829
      qCWarning(lcQtPass) << "Cannot read" << attrPath
×
830
                          << "to pin attributes:" << attr.errorString();
×
831
      return;
×
832
    }
833
    existing = QString::fromUtf8(attr.readAll());
40 ✔
834
    attr.close();
40 ✔
835
    if (existing.contains(block)) {
40 ✔
836
      return; // already pinned and unchanged
837
    }
838
  }
839

840
  if (!QDir().mkpath(infoDir)) {
18 ✔
841
    qCWarning(lcQtPass) << "Cannot create" << infoDir << "to pin attributes";
×
842
    return;
×
843
  }
844

845
  // Keep any lines the user added themselves (outside our block), then append a
846
  // fresh copy of our block. A previous QtPass block is dropped so an updated
847
  // set of lines replaces an older one.
848
  QString preserved;
9 ✔
849
  if (!existing.isEmpty()) {
9 ✔
850
    const QStringList lines = existing.split(QLatin1Char('\n'));
×
851
    bool inBlock = false;
852
    for (const QString &line : lines) {
×
853
      if (line == marker) {
×
854
        inBlock = true;
855
        continue;
×
856
      }
857
      if (inBlock) {
×
858
        if (line.startsWith(QStringLiteral("*.gpg ")) ||
×
859
            line.startsWith(QStringLiteral(".gpg-id ")) ||
×
860
            line.startsWith(QStringLiteral(".gpg-id.sig "))) {
×
861
          continue;
×
862
        }
863
        inBlock = false;
864
      }
865
      preserved += line + QLatin1Char('\n');
×
866
    }
867
    while (preserved.endsWith(QStringLiteral("\n\n"))) {
×
868
      preserved.chop(1);
×
869
    }
870
  }
871

872
  QSaveFile out(attrPath);
9 ✔
873
  const QByteArray payload = (preserved + block).toUtf8();
9 ✔
874
  if (!out.open(QIODevice::WriteOnly | QIODevice::Text) ||
18 ✔
875
      out.write(payload) != payload.size() || !out.commit()) {
18 ✔
876
    qCWarning(lcQtPass) << "Cannot write" << attrPath
×
877
                        << "to pin attributes:" << out.errorString();
×
878
  }
879
}
58 ✔
880

881
auto Pass::withCurrentGitPin(QProcessEnvironment base) const
1,626 ✔
882
    -> QProcessEnvironment {
883
  if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
1,626 ✔
884
    return base;
16 ✔
885
  }
886
  base.remove(QStringLiteral("GIT_DIR"));
3,220 ✔
887
  base.remove(QStringLiteral("GIT_WORK_TREE"));
3,220 ✔
888
  for (const auto &[name, value] : Util::gitStoreVariables(
889
           m_settings.passStore, m_settings.gitExecutable)) {
4,840 ✔
890
    base.insert(name, value);
1,620 ✔
891
  }
892
  return base;
1,610 ✔
893
}
894

895
auto Pass::maxOutputArgs() -> QStringList {
1,179 ✔
896
  return {QStringLiteral("--max-output"), QString::number(kMaxPlaintextBytes)};
3,537 ✔
897
}
1,179 ✔
898

899
namespace {
900
/// File names compare the way the platform's file system compares them:
901
/// "C:/Store" and "c:/store" are the same directory on Windows.
902
#ifdef Q_OS_WIN
903
constexpr auto kPathCase = Qt::CaseInsensitive;
904
#else
905
constexpr auto kPathCase = Qt::CaseSensitive;
906
#endif
907

908
/// Whether @p path is @p dir or lies under it.
909
auto isAtOrUnder(const QString &path, const QString &dir,
4,109 ✔
910
                 const QString &dirPrefix) -> bool {
911
  return path.compare(dir, kPathCase) == 0 ||
7,346 ✔
912
         path.startsWith(dirPrefix, kPathCase);
3,237 ✔
913
}
914

915
/// Where the lookup of a .gpg-id starts and the store that bounds it.
916
struct GpgIdLookup {
917
  QDir start;
918
  /// The folder whose list is wanted, whether it exists or not.
919
  QString folder;
920
  QString storeDir;
921
  QString storePrefix;
922
};
923

924
/// The folder whose list @p for_file wants: its own for a folder, its
925
/// folder's for an entry.
926
auto gpgIdLookup(const QString &for_file, const QString &passStore)
1,294 ✔
927
    -> GpgIdLookup {
928
  const QString normalizedFile = QDir::fromNativeSeparators(for_file);
1,294 ✔
929
  // Inside the store means at a path boundary: "/store-other/x" is not
930
  // under "/store", however the prefix compares.
931
  const QString storeDir =
932
      QDir::cleanPath(QDir::fromNativeSeparators(passStore));
1,294 ✔
933
  const QString storePrefix = storeDir.endsWith(QLatin1Char('/'))
1,294 ✔
934
                                  ? storeDir
1,294 ✔
935
                                  : storeDir + QLatin1Char('/');
1,294 ✔
936
  const QString cleanFile = QDir::cleanPath(normalizedFile);
1,294 ✔
937
  const bool insideStore = isAtOrUnder(cleanFile, storeDir, storePrefix);
1,294 ✔
938
  // A relative name is one inside the store; an absolute path outside it
939
  // stays what it is and the walk stops at once.
940
  const QString fullPath =
941
      insideStore || (QDir::isAbsolutePath(cleanFile) &&
21 ✔
942
                      !cleanFile.startsWith(QLatin1Char(':')))
5 ✔
943
          ? cleanFile
1,294 ✔
944
          : storePrefix + cleanFile;
11 ✔
945
  // A folder (trailing separator, which cleanPath() dropped, or an existing
946
  // directory) wants its own list; an entry wants its folder's.
947
  const bool isFolder =
948
      normalizedFile.endsWith(QLatin1Char('/')) || QFileInfo(fullPath).isDir();
1,294 ✔
949
  // A folder that does not exist yet (an entry saved into a new folder, a
950
  // move to one) starts the walk at its nearest existing ancestor in the
951
  // store, as pass's set_gpg_recipients does: otherwise the walk ended at
952
  // once and the store root's list was taken over the one in between.
953
  const QString folder =
954
      QDir::cleanPath(isFolder ? fullPath : QFileInfo(fullPath).absolutePath());
3,275 ✔
955
  QString start = folder;
956
  while (!QFileInfo(start).exists() &&
1,328 ✔
957
         isAtOrUnder(QDir::cleanPath(start), storeDir, storePrefix) &&
2,639 ✔
958
         QDir::cleanPath(start) != storeDir) {
1,328 ✔
959
    start = QFileInfo(start).absolutePath();
34 ✔
960
  }
961
  return {QDir(start), folder, storeDir, storePrefix};
1,294 ✔
962
}
1,294 ✔
963

964
/// Whether @p candidate can be its folder's .gpg-id: a regular file, as
965
/// pass looks for (test -f), so a folder under the name is passed over as
966
/// pass passes it. A link under the name is not: whoever planted it chose
967
/// the recipients elsewhere.
968
auto isOwnGpgId(const QFileInfo &candidate) -> bool {
2,320 ✔
969
  return candidate.isFile() && !candidate.isSymLink() &&
3,009 ✔
970
         !candidate.isJunction();
689 ✔
971
}
972

973
/// Walk up from the lookup's start to the first folder inside the store
974
/// that has its own .gpg-id; nothing when none does. A link under the name
975
/// is skipped, so the parent's list applies instead.
976
auto nearestGpgId(const GpgIdLookup &lookup) -> std::optional<QString> {
710 ✔
977
  QDir dir = lookup.start;
710 ✔
978
  while (dir.exists() && isAtOrUnder(QDir::cleanPath(dir.absolutePath()),
4,056 ✔
979
                                     lookup.storeDir, lookup.storePrefix)) {
1,014 ✔
980
    const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
893 ✔
981
    if (isOwnGpgId(candidate)) {
893 ✔
982
      return candidate.absoluteFilePath();
589 ✔
983
    }
984
    if (!dir.cdUp()) {
304 ✔
985
      break;
986
    }
987
  }
893 ✔
988
  return std::nullopt;
121 ✔
989
}
710 ✔
990

991
} // namespace
992

993
auto Pass::heldScopes() -> QSet<QString> & {
271 ✔
994
  static QSet<QString> scopes;
277 ✔
995
  return scopes;
271 ✔
996
}
997

998
auto Pass::scopePath(const QString &path) const -> QString {
271 ✔
999
  return QDir::cleanPath(QDir(m_settings.passStore).absoluteFilePath(path));
542 ✔
1000
}
1001

1002
auto Pass::autoPushHeld() const -> bool {
68 ✔
1003
  const QString store = scopePath(QString());
68 ✔
1004
  const QSet<QString> &scopes = heldScopes();
68 ✔
1005
  return std::any_of(scopes.cbegin(), scopes.cend(),
68 ✔
1006
                     [&store](const QString &s) {
162 ✔
1007
                       return isAtOrUnder(s, store, store + QLatin1Char('/'));
324 ✔
1008
                     });
68 ✔
1009
}
1010

1011
void Pass::GitPushAutomatic() {
15 ✔
1012
  m_pushIsAutomatic = true;
15 ✔
1013
  GitPush();
15 ✔
1014
  m_pushIsAutomatic = false;
15 ✔
1015
}
15 ✔
1016

1017
auto Pass::pushIsAutomatic() const -> bool { return m_pushIsAutomatic; }
10 ✔
1018

1019
void Pass::holdAutoPush(const QString &scope) {
100 ✔
1020
  heldScopes().insert(scopePath(scope));
100 ✔
1021
}
100 ✔
1022

1023
void Pass::releaseAutoPush(const QString &folder) {
103 ✔
1024
  const QString root = scopePath(folder);
103 ✔
1025
  QSet<QString> &scopes = heldScopes();
103 ✔
1026
  for (auto it = scopes.begin(); it != scopes.end();) {
1027
    it = isAtOrUnder(*it, root, root + QLatin1Char('/')) ? scopes.erase(it)
970 ✔
1028
                                                         : std::next(it);
485 ✔
1029
  }
1030
}
103 ✔
1031

1032
auto Pass::refuseLinkedPath(const QString &path, LinkScope scope,
804 ✔
1033
                            PathSpelling spelling) -> bool {
1034
  const QString full = Util::joinPath(m_settings.passStore, path);
804 ✔
1035
  // The link check below walks only under the store as configured: a path
1036
  // spelled through the root's link target would get no more than the
1037
  // entry itself judged. No caller makes one; say so if one starts to.
1038
  if (spelling == PathSpelling::Configured &&
1,322 ✔
1039
      PathValidator::isTargetSpelled(m_settings.passStore, full)) {
518 ✔
1040
    qCWarning(lcQtPass)
4 ✔
1041
        << "Path spelled through the store root's link target, not as the "
1042
           "store is configured; Pass operations expect the configured "
1043
           "spelling:"
2 ✔
1044
        << full;
2 ✔
1045
  }
1046
  if (!Util::isUnderLink(full, m_settings.passStore,
804 ✔
1047
                         scope == LinkScope::EntryAndParents)) {
1048
    return false;
1049
  }
1050
  const QString why =
1051
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
×
1052
         "points to is not part of the password store and is left alone.")
1053
          .arg(QDir::toNativeSeparators(QDir::cleanPath(full)));
62 ✔
1054
  refuseAsNotPartOfStore(why);
31 ✔
1055
  return true;
1056
}
1057

1058
auto Pass::refuseFolderOutsideStore(const QString &folder, QString *relative)
93 ✔
1059
    -> bool {
1060
  if (const std::optional<QString> inStore =
93 ✔
1061
          PathValidator::storeRelativePath(m_settings.passStore, folder)) {
93 ✔
1062
    if (relative != nullptr) {
88 ✔
1063
      *relative = *inStore;
88 ✔
1064
    }
1065
    return false;
1066
  }
1067
  refuseAsNotPartOfStore(
5 ✔
1068
      tr("%1 is not inside the password store. Recipients are set for the "
5 ✔
1069
         "store or a folder in it.")
1070
          .arg(QDir::toNativeSeparators(QDir::cleanPath(folder))));
10 ✔
1071
  return true;
5 ✔
1072
}
1073

1074
auto Pass::unfinishedGitOperationReason() -> QString {
800 ✔
1075
  if (!m_settings.useGit) {
800 ✔
1076
    return {};
587 ✔
1077
  }
1078
  // One git call names the path of each marker file or directory, whether or
1079
  // not it exists; the backend runs it in the store (ImitatePass with
1080
  // `-C <store>`, RealPass through `pass git`). The markers, paired with the
1081
  // operation each one means, in the order git prints them back.
1082
  // The names are Git's own commands, which the user then runs with --abort or
1083
  // --continue; the translator comments say so.
1084
  const std::array<std::pair<QLatin1String, QString>, 6> markers{{
1085
      //: The Git command `git rebase`, inserted into "in the middle of a %1".
1086
      //: Best kept as Git's command name.
1087
      {QLatin1String("rebase-merge"), tr("rebase")},
213 ✔
1088
      //: The Git command `git rebase`, inserted into "in the middle of a %1".
1089
      //: Best kept as Git's command name.
1090
      {QLatin1String("rebase-apply"), tr("rebase")},
213 ✔
1091
      //: The Git command `git merge`, inserted into "in the middle of a %1".
1092
      //: Best kept as Git's command name.
1093
      {QLatin1String("MERGE_HEAD"), tr("merge")},
213 ✔
1094
      //: The Git command `git cherry-pick`, inserted into "in the middle of a
1095
      //: %1". Best kept as Git's command name.
1096
      {QLatin1String("CHERRY_PICK_HEAD"), tr("cherry-pick")},
213 ✔
1097
      //: The Git command `git revert`, inserted into "in the middle of a %1".
1098
      //: Best kept as Git's command name.
1099
      {QLatin1String("REVERT_HEAD"), tr("revert")},
213 ✔
1100
      // A multi-commit cherry-pick or revert keeps its sequencer state after a
1101
      // conflict resolution is committed, when CHERRY_PICK_HEAD/REVERT_HEAD is
1102
      // already gone but `--continue` has more commits to apply. Checked last,
1103
      // so the specific head above names the operation when it is still there.
1104
      //: The Git commands `git cherry-pick` and `git revert`, inserted into
1105
      //: "in the middle of a %1". Best kept as Git's command names.
1106
      {QLatin1String("sequencer"), tr("cherry-pick or revert")},
213 ✔
1107
  }};
×
1108
  QStringList args{QStringLiteral("rev-parse")};
426 ✔
1109
  for (const auto &marker : markers) {
1,491 ✔
1110
    args << QStringLiteral("--git-path") << marker.first;
1,278 ✔
1111
  }
1112
  QString out;
213 ✔
1113
  if (!storeGit(args, &out)) {
213 ✔
1114
    // Git is off, the store is not a repository, or git could not be asked:
1115
    // nothing is refused, as the operation would run anyway.
1116
    return {};
14 ✔
1117
  }
1118
  const QStringList paths = out.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
199 ✔
1119
  for (int i = 0; i < paths.size() && i < static_cast<int>(markers.size());
825 ✔
1120
       ++i) {
1121
    const QString path = paths.at(i).trimmed();
1122
    const QString full = QDir::isAbsolutePath(path)
1123
                             ? path
633 ✔
1124
                             : QDir(m_settings.passStore).filePath(path);
633 ✔
1125
    if (!QFileInfo::exists(full)) {
633 ✔
1126
      continue;
1127
    }
1128
    //: %1 is a Git command name: rebase, merge, cherry-pick, revert, or
1129
    //: "cherry-pick or revert".
1130
    return tr("The password store's Git repository is in the middle of a %1. "
7 ✔
1131
              "Finish or abort it with Git before changing the password store, "
1132
              "or what you change may be lost.")
1133
        .arg(markers.at(static_cast<size_t>(i)).second);
7 ✔
1134
  }
1135
  return {};
192 ✔
1136
}
1137

1138
auto Pass::refusePendingPull() -> bool {
201 ✔
1139
  if (!m_settings.useGit || !exec.hasQueued(Enums::GIT_PULL)) {
248 ✔
1140
    return false;
1141
  }
1142
  const QString why =
1143
      tr("The password store is being updated (a Git pull is in progress). "
1144
         "Wait until it has finished, then try again.");
1145
  // Like refuseAsNotPartOfStore(): the interface arms when an operation starts
1146
  // and is released by processErrorExit(); a refusal starts nothing.
1147
  emit startingExecuteWrapper();
3 ✔
1148
  emit critical(tr("Update in progress"), why);
3 ✔
1149
  emit processErrorExit(1, why);
3 ✔
1150
  return true;
1151
}
1152

1153
auto Pass::initIfUnchanged(const QString &path, const QList<UserInfo> &users,
11 ✔
1154
                           const QString &dir, const QString &passStore,
1155
                           const RecipientsForEditing &read) -> bool {
1156
  m_expectedList = ExpectedList{dir, passStore, read.state, read.recipients};
11 ✔
1157
  m_expectedListRefused = false;
11 ✔
1158
  const auto done = qScopeGuard([this] { m_expectedList.reset(); });
1159
  Init(path, users);
11 ✔
1160
  return !m_expectedListRefused;
11 ✔
1161
}
1162

1163
auto Pass::refuseChangedList() -> bool {
79 ✔
1164
  if (!m_expectedList) {
79 ✔
1165
    return false;
1166
  }
1167
  const RecipientsForEditing now =
1168
      recipientsForEditing(m_expectedList->dir, m_expectedList->passStore);
5 ✔
1169
  if (now.state == m_expectedList->state &&
5 ✔
1170
      now.recipients == m_expectedList->recipients) {
5 ✔
1171
    return false;
1172
  }
1173
  const QString why =
1174
      tr("The recipient list of this folder changed after the users dialog "
1175
         "read it, for example through an update from Git. Nothing was "
1176
         "written. Open the dialog again to see the new list.");
1177
  m_expectedListRefused = true;
3 ✔
1178
  emit startingExecuteWrapper();
3 ✔
1179
  emit critical(tr("Recipients not changed"), why);
3 ✔
1180
  emit processErrorExit(1, why);
3 ✔
1181
  return true;
1182
}
1183

1184
auto Pass::refuseBusyForExpectedList() -> bool {
38 ✔
1185
  if (!m_expectedList || exec.isIdle()) {
38 ✔
1186
    return false;
1187
  }
1188
  const QString why =
1189
      tr("Another operation is still running. Wait until it has finished, "
1190
         "then save the recipients again.");
1191
  m_expectedListRefused = true;
1 ✔
1192
  emit startingExecuteWrapper();
1 ✔
1193
  emit critical(tr("Recipients not changed"), why);
1 ✔
1194
  emit processErrorExit(1, why);
1 ✔
1195
  return true;
1196
}
1197

1198
auto Pass::refuseUnfinishedGitOperation() -> bool {
577 ✔
1199
  const QString why = unfinishedGitOperationReason();
577 ✔
1200
  if (why.isEmpty()) {
577 ✔
1201
    return false;
1202
  }
1203
  // Like refuseAsNotPartOfStore(): the interface arms when an operation starts
1204
  // and is released by finished()/processErrorExit(); a refusal starts
1205
  // nothing, so it emits both ends.
1206
  emit startingExecuteWrapper();
5 ✔
1207
  emit critical(tr("Unfinished Git operation"), why);
5 ✔
1208
  emit processErrorExit(1, why);
5 ✔
1209
  return true;
1210
}
1211

1212
void Pass::refuseAsNotPartOfStore(const QString &why) {
36 ✔
1213
  // The interface arms itself when an operation starts and is released by
1214
  // finished or processErrorExit; a refusal starts nothing, so emits both.
1215
  emit startingExecuteWrapper();
36 ✔
1216
  emit critical(tr("Not part of the store"), why);
36 ✔
1217
  emit processErrorExit(1, why);
36 ✔
1218
}
36 ✔
1219

1220
auto Pass::getGpgIdPath(const QString &for_file, const QString &passStore)
710 ✔
1221
    -> QString {
1222
  return nearestGpgId(gpgIdLookup(for_file, passStore))
1,420 ✔
1223
      .value_or(
1224
          QDir(QDir::fromNativeSeparators(passStore)).filePath(".gpg-id"));
2,840 ✔
1225
}
1226

1227
auto Pass::refuseSkippedGpgId(const QString &file, bool signing,
227 ✔
1228
                              const QString &except, SkippedWalks *walks)
1229
    -> bool {
1230
  // Without a signing key the parent's list applies, as it does for pass.
1231
  if (!signing) {
227 ✔
1232
    return false;
1233
  }
1234
  QString recordError;
51 ✔
1235
  const std::optional<QString> skipped =
1236
      skippedGpgId(file, m_settings.passStore, &recordError, walks);
51 ✔
1237
  if (!skipped || (!except.isEmpty() &&
51 ✔
1238
                   QDir::cleanPath(*skipped) == QDir::cleanPath(except))) {
53 ✔
1239
    return false;
1240
  }
1241
  // The strings keep the context they were translated in.
1242
  if (!recordError.isEmpty()) {
4 ✔
1243
    emit critical(QCoreApplication::translate(
×
1244
                      "ImitatePass", "Cannot check the recipient list"),
1245
                  QCoreApplication::translate(
×
1246
                      "ImitatePass", "%1 Whether %2 was removed cannot be "
1247
                                     "told, so nothing was encrypted.")
1248
                      .arg(recordError, QDir::toNativeSeparators(*skipped)));
×
1249
    return true;
×
1250
  }
1251
  emit critical(
4 ✔
1252
      QCoreApplication::translate("ImitatePass", "Recipient list missing"),
8 ✔
1253
      QCoreApplication::translate(
4 ✔
1254
          "ImitatePass",
1255
          "The signed recipient list %1 is missing or is not a regular file. "
1256
          "QtPass does not fall back to a parent folder's list for it: that "
1257
          "list was not signed for this folder. If a link is under that name, "
1258
          "remove it. Then open Users for that folder and save its "
1259
          "recipients, which writes and signs a fresh list.")
1260
          .arg(QDir::toNativeSeparators(*skipped)));
8 ✔
1261
  return true;
4 ✔
1262
}
1263

1264
auto Pass::verifySignedList(const GpgIdSigner &signer, const QString &gpgIdFile,
68 ✔
1265
                            QByteArray *contents, QString *why) const -> bool {
1266
  if (!signer.verifyFile(gpgIdFile, contents)) {
68 ✔
1267
    return false;
1268
  }
1269
  // Authentic and unmodified is not the same as current: an older signed
1270
  // list put back into the store is refused once this device has seen a
1271
  // newer one, and one signed for another folder is refused here.
1272
  QString reason;
52 ✔
1273
  if (GpgIdGeneration::accept(gpgIdFile, *contents, m_settings.passStore,
52 ✔
1274
                              &reason) != GpgIdGeneration::Verdict::Accepted) {
1275
    if (why != nullptr) {
19 ✔
1276
      *why = reason;
14 ✔
1277
    }
1278
    return false;
19 ✔
1279
  }
1280
  return true;
1281
}
1282

1283
auto Pass::skippedGpgId(const QString &forFile, const QString &passStore,
284 ✔
1284
                        QString *recordError, SkippedWalks *walks)
1285
    -> std::optional<QString> {
1286
  const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
284 ✔
1287
  // A folder's answer depends only on it and the folders above it: kept
1288
  // for every folder climbed, a tree check asks each one record lookup,
1289
  // where climbing again from every folder cost depth squared.
1290
  QStringList climbed;
284 ✔
1291
  // By value: on a hit they come out of walks, which the inserts below
1292
  // may rehash.
1293
  const auto answer = [&climbed, walks, recordError](
284 ✔
1294
                          std::optional<QString> skipped, QString why) {
1295
    if (walks != nullptr) {
284 ✔
1296
      for (const QString &folder : std::as_const(climbed)) {
430 ✔
1297
        walks->insert(folder, {skipped, why});
430 ✔
1298
      }
1299
    }
1300
    if (recordError != nullptr && !why.isEmpty()) {
284 ✔
1301
      *recordError = why;
1 ✔
1302
    }
1303
    return skipped;
284 ✔
1304
  };
284 ✔
1305
  // The same walk as nearestGpgId(), stopping at the list it finds, and
1306
  // short of the store root: the root's own list has no parent to fall
1307
  // back to, and the signature check refuses it when it is missing. It
1308
  // starts at the folder asked for, not at its nearest existing one: a
1309
  // folder removed together with its list is asked of the record too.
1310
  QString dir = lookup.folder;
1311
  while (dir.startsWith(lookup.storePrefix, kPathCase)) {
707 ✔
1312
    if (walks != nullptr) {
655 ✔
1313
      if (const auto known = walks->constFind(dir);
413 ✔
1314
          known != walks->constEnd()) {
1315
        return answer(known->skipped, known->recordError);
396 ✔
1316
      }
1317
    }
1318
    climbed << dir;
1319
    const QFileInfo candidate(dir + QStringLiteral("/.gpg-id"));
914 ✔
1320
    if (isOwnGpgId(candidate)) {
457 ✔
1321
      return answer(std::nullopt, QString());
32 ✔
1322
    }
1323
    // A link under the name (dangling or not), or nothing under it where
1324
    // this device accepted a list before: both are the folder's list gone,
1325
    // not a folder that never had one.
1326
    if (candidate.isSymLink() || candidate.isJunction()) {
441 ✔
1327
      return answer(candidate.absoluteFilePath(), QString());
10 ✔
1328
    }
1329
    // An unreadable record is not "never seen": whether a list was accepted
1330
    // here cannot be told, so this folder is refused too (fail closed), with
1331
    // the record's own reason for the caller to show.
1332
    QString why;
436 ✔
1333
    const std::optional<bool> seen =
1334
        GpgIdGeneration::seen(candidate.absoluteFilePath(), &why);
872 ✔
1335
    if (!seen) {
436 ✔
1336
      return answer(candidate.absoluteFilePath(),
2 ✔
1337
                    why.isEmpty()
1338
                        ? tr("The generation record of the recipient lists "
2 ✔
1339
                             "cannot be read.")
1340
                        : why);
1 ✔
1341
    }
1342
    if (*seen) {
435 ✔
1343
      return answer(candidate.absoluteFilePath(), QString());
24 ✔
1344
    }
1345
    const QString parent = QDir::cleanPath(QFileInfo(dir).absolutePath());
846 ✔
1346
    if (parent == dir) {
423 ✔
1347
      break;
1348
    }
1349
    dir = parent;
423 ✔
1350
  }
457 ✔
1351
  return answer(std::nullopt, QString());
104 ✔
1352
}
284 ✔
1353

1354
auto Pass::linkedGpgId(const QString &forFile, const QString &passStore,
300 ✔
1355
                       LinkedWalks *walks) -> std::optional<QString> {
1356
  const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
300 ✔
1357
  // As in skippedGpgId(): a folder's answer depends only on it and the
1358
  // folders above it, so a tree check climbs each folder once instead of
1359
  // once per folder below it.
1360
  QStringList climbed;
300 ✔
1361
  const auto answer = [&climbed, walks](std::optional<QString> linked) {
300 ✔
1362
    if (walks != nullptr) {
300 ✔
1363
      for (const QString &folder : std::as_const(climbed)) {
375 ✔
1364
        walks->insert(folder, linked);
215 ✔
1365
      }
1366
    }
1367
    return linked;
300 ✔
1368
  };
300 ✔
1369
  // The walk of nearestGpgId(), root included, stopping at the list it
1370
  // finds.
1371
  QDir dir = lookup.start;
300 ✔
1372
  while (dir.exists()) {
1,137 ✔
1373
    const QString here = QDir::cleanPath(dir.absolutePath());
1,137 ✔
1374
    if (!isAtOrUnder(here, lookup.storeDir, lookup.storePrefix)) {
1,137 ✔
1375
      break;
1376
    }
1377
    if (walks != nullptr) {
1,058 ✔
1378
      // By value: the inserts in answer() may rehash walks.
1379
      if (const auto known = walks->constFind(here);
303 ✔
1380
          known != walks->constEnd()) {
1381
        return answer(std::optional<QString>(*known));
176 ✔
1382
      }
1383
    }
1384
    climbed << here;
1385
    const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
970 ✔
1386
    if (isOwnGpgId(candidate)) {
970 ✔
1387
      return answer(std::nullopt);
168 ✔
1388
    }
1389
    if (candidate.isSymLink() || candidate.isJunction()) {
886 ✔
1390
      return answer(candidate.absoluteFilePath());
98 ✔
1391
    }
1392
    if (!dir.cdUp()) {
837 ✔
1393
      break;
1394
    }
1395
  }
970 ✔
1396
  return answer(std::nullopt);
158 ✔
1397
}
600 ✔
1398

1399
namespace {
1400

1401
/// What the Users dialog may preselect for a verified list, given what the
1402
/// generation record says about it.
1403
auto judgedRecipients(GpgIdGeneration::Verdict verdict,
7 ✔
1404
                      const QByteArray &contents, const QString &gpgIdPath,
1405
                      const QString &why) -> Pass::RecipientsForEditing {
1406
  using RecipientsForEditing = Pass::RecipientsForEditing;
1407
  RecipientsForEditing result;
7 ✔
1408
  switch (verdict) {
7 ✔
1409
  case GpgIdGeneration::Verdict::Accepted:
1 ✔
1410
    result.state = RecipientsForEditing::State::Verified;
1 ✔
1411
    result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1 ✔
1412
    break;
1 ✔
1413
  case GpgIdGeneration::Verdict::Rollback:
1 ✔
1414
    // Authentic and this folder's, only older: the recovery goes through
1415
    // this dialog, so it is preselected, with the reason in view.
1416
    result.state = RecipientsForEditing::State::VerifiedRollback;
1 ✔
1417
    result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1 ✔
1418
    result.warning = why;
1 ✔
1419
    break;
1 ✔
1420
  case GpgIdGeneration::Verdict::Unbound:
5 ✔
1421
  case GpgIdGeneration::Verdict::Conflict:
1422
  case GpgIdGeneration::Verdict::WrongFolder:
1423
  case GpgIdGeneration::Verdict::WrongStore:
1424
  case GpgIdGeneration::Verdict::Malformed:
1425
  case GpgIdGeneration::Verdict::RecordUnavailable:
1426
    // Signed, but not shown to be this folder's list, not a list to trust,
1427
    // or nothing to judge it by: preselecting it would sign it in.
1428
    result.state = RecipientsForEditing::State::Rejected;
5 ✔
1429
    result.warning =
1430
        Pass::tr("%1 Nothing is preselected: saving would sign whatever is "
5 ✔
1431
                 "in it. Select the recipients yourself.")
1432
            .arg(why);
10 ✔
1433
    break;
5 ✔
1434
  }
1435
  return result;
7 ✔
1436
}
1437

1438
} // namespace
1439

1440
auto Pass::recipientsForEditing(const QString &dir, const QString &passStore)
83 ✔
1441
    -> RecipientsForEditing {
1442
  RecipientsForEditing result;
83 ✔
1443
  const QString folder = dir.isEmpty() ? QString() : dir;
83 ✔
1444
  const QString gpgIdPath = getGpgIdPath(folder, passStore);
83 ✔
1445
  GpgIdSigner signer(m_settings.gpgExecutable,
1446
                     GpgIdSigner::keysFromSetting(m_settings.passSigningKey));
249 ✔
1447
  signer.setStoreRoot(passStore);
1448
  if (!signer.enabled()) {
83 ✔
1449
    // A list that is there but cannot be read as one (too large, not a
1450
    // regular file, unreadable) is not an empty list: preselecting nothing
1451
    // without a word would let OK write a new list over it, and later
1452
    // re-encryptions drop whoever it named.
1453
    // Read once and parsed from those bytes: a second read could find
1454
    // something else under the name. A link counts as there, dangling too.
1455
    const QFileInfo info(gpgIdPath);
73 ✔
1456
    if (!info.exists() && !info.isSymLink()) {
73 ✔
1457
      result.state = RecipientsForEditing::State::Unsigned;
1458
      return result;
18 ✔
1459
    }
1460
    const std::optional<QByteArray> bytes = Util::readRegularFileInStore(
1461
        passStore, gpgIdPath, Util::kMaxGpgIdBytes);
55 ✔
1462
    if (!bytes) {
55 ✔
1463
      result.state = RecipientsForEditing::State::Rejected;
2 ✔
1464
      result.warning =
1465
          tr("%1 cannot be read as a recipient list (a regular file of at "
2 ✔
1466
             "most %2), so nothing is preselected. Check it before choosing "
1467
             "recipients here: OK writes a new list over it.")
1468
              .arg(gpgIdPath,
2 ✔
1469
                   QLocale().formattedDataSize(Util::kMaxGpgIdBytes));
4 ✔
1470
      return result;
2 ✔
1471
    }
1472
    result.state = RecipientsForEditing::State::Unsigned;
1473
    result.recipients = parseRecipients(*bytes, gpgIdPath);
53 ✔
1474
    const QString misread = passReadsDifferently(*bytes);
53 ✔
1475
    if (!misread.isEmpty()) {
53 ✔
1476
      //: %1 is the list's path, %2 says what is wrong with it.
1477
      result.warning =
1478
          tr("pass reads %1 differently from this dialog (%2), so it may "
3 ✔
1479
             "encrypt to recipients not shown here. QtPass will not encrypt "
1480
             "with it through pass: check the recipients, then OK writes the "
1481
             "list anew.")
1482
              .arg(gpgIdPath, misread);
6 ✔
1483
    }
1484
    return result;
53 ✔
1485
  }
73 ✔
1486
  QString recordError;
10 ✔
1487
  if (const std::optional<QString> skipped =
10 ✔
1488
          skippedGpgId(folder, passStore, &recordError)) {
10 ✔
1489
    // The folder's own list was removed or replaced by a link (or the record
1490
    // that would tell cannot be read): the list the walk found further up
1491
    // was not signed for this folder, so preselecting it would sign it in
1492
    // here with one click.
1493
    result.state = RecipientsForEditing::State::Rejected;
1 ✔
1494
    result.warning =
1495
        recordError.isEmpty()
1496
            ? tr("The recipient list %1 is missing or is not a regular file, "
2 ✔
1497
                 "so nothing is preselected: the list of a parent folder was "
1498
                 "not signed for this one. Select this folder's recipients "
1499
                 "yourself; OK writes and signs a fresh list.")
1500
                  .arg(*skipped)
1501
            : tr("%1 Nothing is preselected: whether %2 was removed cannot "
1 ✔
1502
                 "be told.")
1503
                  .arg(recordError, *skipped);
1504
    return result;
1 ✔
1505
  }
1506
  if (!QFileInfo::exists(gpgIdPath)) {
9 ✔
1507
    // A folder without a list yet (new store, new profile): nothing to
1508
    // verify and nothing to preselect.
1509
    result.state = RecipientsForEditing::State::Verified;
1 ✔
1510
    return result;
1 ✔
1511
  }
1512
  QByteArray contents;
8 ✔
1513
  if (!signer.verifyFile(gpgIdPath, &contents)) {
8 ✔
1514
    result.state = RecipientsForEditing::State::Rejected;
1 ✔
1515
    result.warning =
1516
        tr("The recipient list %1 does not verify against the signing key, "
1 ✔
1517
           "so nothing is preselected: saving would sign whatever is in it. "
1518
           "Select the recipients yourself; OK writes and signs a fresh list.")
1519
            .arg(gpgIdPath);
2 ✔
1520
    return result;
1 ✔
1521
  }
1522
  QString why;
7 ✔
1523
  const GpgIdGeneration::Verdict verdict =
1524
      GpgIdGeneration::accept(gpgIdPath, contents, passStore, &why);
7 ✔
1525
  return judgedRecipients(verdict, contents, gpgIdPath, why);
7 ✔
1526
}
83 ✔
1527

1528
auto Pass::getRecipientList(const QString &for_file, const QString &passStore)
10 ✔
1529
    -> QStringList {
1530
  const QString gpgIdPath = getGpgIdPath(for_file, passStore);
10 ✔
1531
  // The root .gpg-id comes back whatever it is; a link is not a list.
1532
  if (Util::isLinkedFolder(gpgIdPath)) {
10 ✔
1533
    return {};
1 ✔
1534
  }
1535
  const std::optional<QByteArray> bytes =
1536
      Util::readRegularFileInStore(passStore, gpgIdPath, Util::kMaxGpgIdBytes);
9 ✔
1537
  if (!bytes) {
9 ✔
1538
    return {};
1 ✔
1539
  }
1540
  return parseRecipients(*bytes, gpgIdPath);
8 ✔
1541
}
1542

1543
auto Pass::parseRecipients(const QByteArray &contents,
272 ✔
1544
                           const QString &sourceName) -> QStringList {
1545
  QStringList recipients;
272 ✔
1546
  const QString text = QString::fromUtf8(contents);
1547
  for (const QString &line : text.split(QLatin1Char('\n'))) {
6,991 ✔
1548
    QString recipient = line.split(QLatin1Char('#')).first().trimmed();
13,438 ✔
1549
    if (recipient.isEmpty()) {
6,719 ✔
1550
      continue;
344 ✔
1551
    }
1552
    if (!Util::isValidKeyId(recipient)) {
6,375 ✔
1553
      // Never drop a recipient silently: the list is written back verbatim
1554
      // by UsersDialog, so a skipped line disappears from .gpg-id.
1555
      qCWarning(lcQtPass) << "Skipping unusable recipient in" << sourceName
4 ✔
1556
                          << ":" << recipient;
2 ✔
1557
      continue;
2 ✔
1558
    }
2 ✔
1559
    recipients += recipient;
1560
  }
1561
  return recipients;
272 ✔
1562
}
1563

1564
auto Pass::passReadsDifferently(const QByteArray &contents) -> QString {
97 ✔
1565
  if (contents.startsWith("\xEF\xBB\xBF")) {
97 ✔
1566
    return tr("it starts with a byte-order mark");
1567
  }
1568
  if (contents.contains('\0')) {
96 ✔
1569
    return tr("it holds a NUL byte");
1570
  }
1571
  if (contents.contains('\r')) {
94 ✔
1572
    return tr("it has Windows line ends (a carriage return)");
1573
  }
1574
  const QString text = QString::fromUtf8(contents);
1575
  if (text.toUtf8() != contents) {
93 ✔
1576
    return tr("it is not valid UTF-8");
1577
  }
1578
  const QStringList lines = text.split(QLatin1Char('\n'));
92 ✔
1579
  for (qsizetype i = 0; i < lines.size(); ++i) {
6,390 ✔
1580
    const QString &line = lines.at(i);
1581
    const QString recipient = line.left(line.indexOf(QLatin1Char('#')));
6,308 ✔
1582
    for (const QChar c : recipient) {
132,037 ✔
1583
      // read strips blanks and tabs; trimmed() strips every space.
1584
      if (c.isSpace() && c != QLatin1Char(' ') && c != QLatin1Char('\t')) {
125,736 ✔
1585
        return tr("line %1 holds whitespace other than blanks and tabs")
7 ✔
1586
            .arg(i + 1);
7 ✔
1587
      }
1588
    }
1589
    const QString trimmed = recipient.trimmed();
1590
    if (trimmed.startsWith(QLatin1Char('-'))) {
6,301 ✔
1591
      return tr("line %1 starts with a dash").arg(i + 1);
2 ✔
1592
    }
1593
    // The text after the last line feed: read hands it over but the loop
1594
    // ends without using it.
1595
    if (i == lines.size() - 1 && !trimmed.isEmpty()) {
6,299 ✔
1596
      return tr("its last line has no line end");
1597
    }
1598
  }
1599
  return {};
82 ✔
1600
}
1601

1602
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
1603
 */
1604

1605
auto Pass::boundedRandom(quint32 bound) -> quint32 {
7,620 ✔
1606
  if (bound < 2) {
7,620 ✔
1607
    return 0;
1608
  }
1609

1610
  quint32 randval;
1611
  // arc4random_uniform-style rejection against modulo bias: drop values
1612
  // below 2^32 % bound, which (1 + ~bound) % bound computes in quint32.
1613
  const quint32 rejectionThreshold = (1 + ~bound) % bound;
7,616 ✔
1614

1615
  do {
1616
    randval = QRandomGenerator::system()->generate();
1617
  } while (randval < rejectionThreshold);
7,616 ✔
1618

1619
  return randval % bound;
7,616 ✔
1620
}
1621

1622
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,209 ✔
1623
    -> QString {
1624
  if (charset.isEmpty() || length == 0U) {
1,209 ✔
1625
    return {};
2 ✔
1626
  }
1627
  QString out;
1,207 ✔
1628
  for (unsigned int i = 0; i < length; ++i) {
8,827 ✔
1629
    out.append(charset.at(static_cast<int>(
7,620 ✔
1630
        boundedRandom(static_cast<quint32>(charset.length())))));
7,620 ✔
1631
  }
1632
  return out;
1633
}
1634

1635
auto Pass::pullTimedOut(int timeoutMs) -> QString {
2 ✔
1636
  // The count in a variable first: older lupdate versions lose a tr() with
1637
  // template arguments among its arguments.
1638
  const int seconds = (timeoutMs + 999) / 1000;
2 ✔
1639
  return tr("Git pull did not finish within %n second(s); editing the entry "
1640
            "as it is here.",
1641
            nullptr, seconds);
2 ✔
1642
}
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