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

IJHack / QtPass / 43580310087

14 Nov 2026 09:23AM UTC coverage: 92.707% (-0.02%) from 92.726%
43580310087

Pull #2154

github

web-flow
Merge 5d01c8b89 into 2d489bbce
Pull Request #2154: Refuse store changes while git is mid-rebase, -merge, -cherry-pick or -revert

64 of 70 new or added lines in 4 files covered. (91.43%)

1 existing line in 1 file now uncovered.

10576 of 11408 relevant lines covered (92.71%)

405.87 hits per line

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

98.32
/src/pass.cpp
1
// SPDX-FileCopyrightText: 2016 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
#include "pass.h"
4

5
#include "gpgidgeneration.h"
6
#include "gpgidsigner.h"
7
#include "gpgkeystate.h"
8
#include "pathvalidator.h"
9
#include "processinfo.h"
10
#include "util.h"
11
#include <QCoreApplication>
12
#include <QDebug>
13
#include <QDir>
14
#include <QFile>
15
#include <QFileInfo>
16
#include <QHash>
17
#include <QLocale>
18
#include <QProcess>
19
#include <QRandomGenerator>
20
#include <QRegularExpression>
21
#include <QTextStream>
22
#include <array>
23
#include <optional>
24
#include <utility>
25

26
#include "qtpasslogging.h"
27

28
using Enums::GIT_INIT;
29
using Enums::GIT_PULL;
30
using Enums::GIT_PUSH;
31
using Enums::GPG_GENKEYS;
32
using Enums::PASS_COPY;
33
using Enums::PASS_INIT;
34
using Enums::PASS_INSERT;
35
using Enums::PASS_MOVE;
36
using Enums::PASS_REMOVE;
37
using Enums::PASS_SHOW;
38

39
namespace {
40
auto fallbackCharset(const QString &input, const QString &fallback) -> QString {
41
  return input.isEmpty() ? fallback : input;
1,519 ✔
42
}
43

44
auto effectiveCharset(const PasswordConfiguration &passConfig) -> QString {
312 ✔
45
  int sel = passConfig.selected;
312 ✔
46
  if (sel < 0 || sel >= PasswordConfiguration::CHARSETS_COUNT)
312 ✔
47
    sel = PasswordConfiguration::ALLCHARS;
48
  return fallbackCharset(
49
      passConfig.Characters[sel],
312 ✔
50
      passConfig.Characters[PasswordConfiguration::ALLCHARS]);
312 ✔
51
}
52
} // namespace
53

54
Pass::Pass() : env(QProcessEnvironment::systemEnvironment()) {
325 ✔
55
  connect(&exec, &Executor::finished, this, &Pass::finished);
325 ✔
56
  connect(&exec, &Executor::error, this, &Pass::finished);
325 ✔
57

58
  connect(&exec, &Executor::starting, this, &Pass::startingExecuteWrapper);
325 ✔
59
  connect(&exec, &Executor::drained, this, [this] {
325 ✔
60
    // Idle means the queue is empty and nothing runs, so no insert is in
61
    // flight: force the pending count to zero. A report that never arrived
62
    // (the "No such transaction" path in ImitatePass::finished(), or any
63
    // later change that drops an insert without reporting) would otherwise
64
    // leave the count one too high for the rest of the session, and every
65
    // later dialog would take its own report for an earlier one and wait for
66
    // ever. Idle cannot fall between a dialog's insertsPending() read and its
67
    // own report, since that insert keeps the executor busy.
68
    m_insertsPending = 0;
72 ✔
69
    emit idle();
72 ✔
70
  });
71
  // Each queued process starts in the environment as the store is then:
72
  // the Git pin is judged at that moment (dequeuing() comes just before the
73
  // start, on this thread).
74
  connect(&exec, &Executor::dequeuing, this, [this](int, bool completes) {
325 ✔
75
    if (completes) {
175 ✔
76
      exec.setEnvironment(withCurrentGitPin(env));
170 ✔
77
    }
78
  });
175 ✔
79
  // Merge our vars into WSLENV rather than blindly appending a duplicate
80
  // entry. WSLENV flags: /p translates the path, /u forwards from Windows
81
  // into WSL only; /w would be the other direction, from WSL out, and leaves
82
  // pass inside WSL without the value. Everything updateEnv() sets for pass
83
  // has to cross, the signing key above all: without it pass does not check
84
  // the .gpg-id signature.
85
  const QStringList wslenvVars = {
86
      QStringLiteral("PASSWORD_STORE_DIR/p"),
650 ✔
87
      QStringLiteral("PASSWORD_STORE_SIGNING_KEY/u"),
325 ✔
88
      QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH/u"),
325 ✔
89
      QStringLiteral("PASSWORD_STORE_CHARACTER_SET/u"),
325 ✔
90
      QStringLiteral("PASSWORD_STORE_GPG_OPTS/u"),
325 ✔
91
      QStringLiteral("GIT_CEILING_DIRECTORIES/p"),
325 ✔
92
      QStringLiteral("GIT_LITERAL_PATHSPECS/u")};
2,600 ✔
93
  const QString existing = env.value(QStringLiteral("WSLENV"));
650 ✔
94
  if (existing.isEmpty()) {
325 ✔
95
    env.insert(QStringLiteral("WSLENV"), wslenvVars.join(':'));
648 ✔
96
  } else {
97
    QStringList parts = existing.split(':', Qt::SkipEmptyParts);
1 ✔
98
    for (const QString &v : wslenvVars) {
8 ✔
99
      if (!parts.contains(v))
7 ✔
100
        parts.append(v);
101
    }
102
    env.insert(QStringLiteral("WSLENV"), parts.join(':'));
2 ✔
103
  }
104
}
325 ✔
105

106
void Pass::executeWrapper(PROCESS id, const QString &app,
2 ✔
107
                          const QStringList &args, bool readStdout,
108
                          bool readStderr) {
109
  executeWrapper(id, app, args, QString(), readStdout, readStderr);
2 ✔
110
}
2 ✔
111

112
void Pass::executeWrapper(PROCESS id, const QString &app,
175 ✔
113
                          const QStringList &args, QString input,
114
                          bool readStdout, bool readStderr) {
115
  beforeExecute(id);
175 ✔
116
  qCDebug(lcQtPass) << app << loggableArgs(args);
175 ✔
117
  exec.execute(id, m_settings.passStore, app, args, std::move(input),
175 ✔
118
               readStdout, readStderr);
119
}
175 ✔
120

121
auto Pass::loggableArgs(const QStringList &args) -> QStringList {
4 ✔
122
  // Secrets travel on stdin (Insert's content, KeygenDialog's batch file),
123
  // never in argv; this keeps the log honest should that ever change.
124
  static const QStringList secretOptions{
125
      QStringLiteral("--passphrase"), QStringLiteral("--override-session-key")};
13 ✔
126
  QStringList out;
4 ✔
127
  bool hide = false;
128
  for (const QString &arg : args) {
12 ✔
129
    if (hide) {
8 ✔
130
      out << QStringLiteral("<redacted>");
1 ✔
131
      hide = false;
132
      continue;
1 ✔
133
    }
134
    if (arg.startsWith(QStringLiteral("otpauth://"))) {
14 ✔
135
      out << QStringLiteral("<redacted>");
1 ✔
136
      continue;
1 ✔
137
    }
138
    if (arg.startsWith(QStringLiteral("--passphrase=")) ||
12 ✔
139
        arg.startsWith(QStringLiteral("--override-session-key="))) {
11 ✔
140
      out << arg.left(arg.indexOf(u'=') + 1) + QStringLiteral("<redacted>");
2 ✔
141
      continue;
1 ✔
142
    }
143
    hide = secretOptions.contains(arg);
144
    out << arg;
145
  }
146
  return out;
4 ✔
147
}
148

149
void Pass::beforeExecute(PROCESS /*id*/) {}
31 ✔
150

151
void Pass::init(const AppSettings &settings) {
607 ✔
152
  m_settings = settings;
607 ✔
153
#ifdef __APPLE__
154
  // If it exists, prepend gpgtools to PATH
155
  if (QFile(QStringLiteral("/usr/local/MacGPG2/bin")).exists())
156
    env.insert(QStringLiteral("PATH"),
157
               QStringLiteral("/usr/local/MacGPG2/bin:") +
158
                   env.value(QStringLiteral("PATH")));
159
  // Add missing /usr/local/bin (exact component match, no leading colon)
160
  const QString currentPath = env.value(QStringLiteral("PATH"));
161
  if (!currentPath.split(':', Qt::SkipEmptyParts)
162
           .contains(QStringLiteral("/usr/local/bin"))) {
163
    env.insert(QStringLiteral("PATH"),
164
               currentPath.isEmpty()
165
                   ? QStringLiteral("/usr/local/bin")
166
                   : QStringLiteral("/usr/local/bin:") + currentPath);
167
  }
168
#endif
169

170
  // The configured gpgHome wins over GNUPGHOME only when it exists: a stale
171
  // one (#1711) fails every gpg call with "No secret key". Clearing the
172
  // setting restores the inherited value rather than keeping the old path.
173
  const QString inheritedHome = QProcessEnvironment::systemEnvironment().value(
1,214 ✔
174
      QStringLiteral("GNUPGHOME"));
1,214 ✔
175
  const auto useInheritedHome = [this, &inheritedHome]() {
567 ✔
176
    if (inheritedHome.isEmpty()) {
567 ✔
177
      env.remove(QStringLiteral("GNUPGHOME"));
786 ✔
178
    } else {
179
      env.insert(QStringLiteral("GNUPGHOME"), inheritedHome);
348 ✔
180
    }
181
  };
1,174 ✔
182
  if (m_settings.gpgHome.isEmpty()) {
607 ✔
183
    useInheritedHome();
565 ✔
184
  } else {
185
    QDir absHome(m_settings.gpgHome);
42 ✔
186
    absHome.makeAbsolute();
42 ✔
187
    if (absHome.exists()) {
42 ✔
188
      env.insert(QStringLiteral("GNUPGHOME"), absHome.path());
80 ✔
189
    } else {
190
      if (inheritedHome.isEmpty()) {
2 ✔
191
        qCWarning(lcQtPass) << "gpgHome" << absHome.path()
2 ✔
192
                            << "does not exist; using the default GnuPG home";
1 ✔
193
        emit statusMsg(tr("Configured GPG home %1 does not exist, using the "
1 ✔
194
                          "default keyring")
195
                           .arg(absHome.path()),
2 ✔
196
                       5000);
197
      } else {
198
        qCWarning(lcQtPass)
2 ✔
199
            << "gpgHome" << absHome.path() << "does not exist; using GNUPGHOME"
2 ✔
200
            << inheritedHome << "from the environment";
1 ✔
201
        emit statusMsg(tr("Configured GPG home %1 does not exist, using "
1 ✔
202
                          "GNUPGHOME %2 from the environment")
203
                           .arg(absHome.path(), inheritedHome),
2 ✔
204
                       5000);
205
      }
206
      useInheritedHome();
2 ✔
207
    }
208
  }
42 ✔
209
}
607 ✔
210

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

266
bool Pass::gpgSupportsEd25519(const QString &gpgExecutable) {
33 ✔
267
  const QString exe =
268
      gpgExecutable.isEmpty() ? QStringLiteral("gpg") : gpgExecutable;
33 ✔
269
  QString out, err;
33 ✔
270
  if (Executor::executeBlocking(exe, {"--version"}, &out, &err) != 0) {
132 ✔
271
    return false;
272
  }
273
  QRegularExpression versionRegex(R"(gpg \(GnuPG\) (\d+)\.(\d+))");
31 ✔
274
  QRegularExpressionMatch match = versionRegex.match(out);
31 ✔
275
  if (!match.hasMatch()) {
31 ✔
276
    return false;
277
  }
278
  int major = match.captured(1).toInt();
30 ✔
279
  int minor = match.captured(2).toInt();
30 ✔
280
  return major > 2 || (major == 2 && minor >= 1);
30 ✔
281
}
31 ✔
282

283
// ed25519 (GnuPG 2.1+) generates much faster than RSA.
284
QString Pass::getDefaultKeyTemplate(const QString &gpgExecutable) {
29 ✔
285
  if (gpgSupportsEd25519(gpgExecutable)) {
29 ✔
286
    return QStringLiteral("%echo Generating a default key\n"
26 ✔
287
                          "Key-Type: EdDSA\n"
288
                          "Key-Curve: Ed25519\n"
289
                          "Subkey-Type: ECDH\n"
290
                          "Subkey-Curve: Curve25519\n"
291
                          "Name-Real: \n"
292
                          "Name-Comment: QtPass\n"
293
                          "Name-Email: \n"
294
                          "Expire-Date: 0\n"
295
                          "%no-protection\n"
296
                          "%commit\n"
297
                          "%echo done");
298
  }
299
  return QStringLiteral("%echo Generating a default key\n"
3 ✔
300
                        "Key-Type: RSA\n"
301
                        "Subkey-Type: RSA\n"
302
                        "Name-Real: \n"
303
                        "Name-Comment: QtPass\n"
304
                        "Name-Email: \n"
305
                        "Expire-Date: 0\n"
306
                        "%no-protection\n"
307
                        "%commit\n"
308
                        "%echo done");
309
}
310

311
namespace {
312
auto resolveWslGpgconfPath(const QString &lastPart) -> QString {
8 ✔
313
  qsizetype lastSep = lastPart.lastIndexOf('/');
8 ✔
314
  if (lastSep < 0) {
8 ✔
315
    lastSep = lastPart.lastIndexOf('\\');
5 ✔
316
  }
317
  if (lastSep >= 0) {
5 ✔
318
    return lastPart.left(lastSep + 1) + "gpgconf";
6 ✔
319
  }
320
  return QStringLiteral("gpgconf");
5 ✔
321
}
322

323
QString findGpgconfInGpgDir(const QString &gpgPath) {
8 ✔
324
  QFileInfo gpgInfo(gpgPath);
8 ✔
325
  if (!gpgInfo.isAbsolute()) {
8 ✔
326
    return {};
1 ✔
327
  }
328

329
  QDir dir(gpgInfo.absolutePath());
7 ✔
330

331
#ifdef Q_OS_WIN
332
  QFileInfo candidateExe(dir.filePath("gpgconf.exe"));
333
  if (candidateExe.isExecutable()) {
334
    return candidateExe.filePath();
335
  }
336
#endif
337

338
  QFileInfo candidate(dir.filePath("gpgconf"));
7 ✔
339
  if (candidate.isExecutable()) {
7 ✔
340
    return candidate.filePath();
5 ✔
341
  }
342
  return {};
2 ✔
343
}
8 ✔
344

345
} // namespace
346

347
auto Pass::resolveGpgconfCommand(const QString &gpgPath)
22 ✔
348
    -> ResolvedGpgconfCommand {
349
  if (gpgPath.trimmed().isEmpty()) {
22 ✔
350
    return {"gpgconf", {}};
351
  }
352

353
  // WSL: gpgconf next to the configured gpg, same distribution, via --exec
354
  // not the shell. An unparsed form (`wsl sh -c ...`, bare `wsl`) falls back
355
  // to gpgconf on the Windows PATH.
356
  if (const auto wsl = Executor::parseWslCommand(gpgPath)) {
21 ✔
357
    if (!QFileInfo(wsl->command).fileName().startsWith("gpg")) {
18 ✔
358
      return {"gpgconf", {}};
359
    }
360
    const auto gpgconf = wsl->with(resolveWslGpgconfPath(wsl->command));
16 ✔
361
    return {gpgconf.launcher, gpgconf.argv({})};
×
362
  }
8 ✔
363

364
  const QStringList parts = QProcess::splitCommand(gpgPath);
12 ✔
365
  if (parts.isEmpty()) {
12 ✔
366
    return {"gpgconf", {}};
367
  }
368
  const QString first = parts.first();
369
  if (QFileInfo(first).fileName().compare("wsl", Qt::CaseInsensitive) == 0 ||
33 ✔
370
      QFileInfo(first).fileName().compare("wsl.exe", Qt::CaseInsensitive) ==
30 ✔
371
          0) {
372
    return {"gpgconf", {}};
373
  }
374

375
  if (!first.contains('/') && !first.contains('\\')) {
9 ✔
376
    return {"gpgconf", {}};
377
  }
378

379
  QString gpgconfPath = findGpgconfInGpgDir(first);
8 ✔
380
  if (!gpgconfPath.isEmpty()) {
8 ✔
381
    return {gpgconfPath, {}};
5 ✔
382
  }
383

384
  return {"gpgconf", {}};
385
}
22 ✔
386

387
void Pass::GenerateGPGKeys(QString batch) {
11 ✔
388
  const QString gpgPath = m_settings.gpgExecutable;
389
  if (gpgPath.isEmpty()) {
11 ✔
390
    // The executor would fail an empty executable with a generic process
391
    // error; the keygen dialog waits for generateGPGKeysFailed and a reason
392
    // it can show. Queued so we do not re-enter KeygenDialog::done(), which
393
    // drives key generation synchronously.
394
    QMetaObject::invokeMethod(
9 ✔
395
        this,
396
        [this]() {
9 ✔
397
          emit generateGPGKeysFailed(tr("No GPG executable configured"));
5 ✔
398
          emit processErrorExit(1, tr("No GPG executable configured"));
5 ✔
399
        },
5 ✔
400
        Qt::QueuedConnection);
401
    return;
402
  }
403

404
  // A stale gpg-agent holding the key database lock causes "database locked"
405
  // timeouts during key generation.
406
  ResolvedGpgconfCommand resolvedGpgconf = resolveGpgconfCommand(gpgPath);
2 ✔
407
  QStringList killArgs = resolvedGpgconf.arguments;
408
  killArgs << "--kill";
2 ✔
409
  killArgs << "gpg-agent";
2 ✔
410
  // Use same environment as key generation to target correct gpg-agent
411
  if (Executor::executeBlocking(env, resolvedGpgconf.program, killArgs) != 0) {
2 ✔
412
    qCWarning(lcQtPass) << "Failed to kill gpg-agent";
2 ✔
413
  }
414

415
  executeWrapper(GPG_GENKEYS, gpgPath, {"--gen-key", "--no-tty", "--batch"},
16 ✔
416
                 std::move(batch), true, true);
417
}
418

419
auto Pass::listKeys(QStringList keystrings, bool secret) -> QList<UserInfo> {
134 ✔
420
  QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
938 ✔
421
  args.append(secret ? "--list-secret-keys" : "--list-keys");
358 ✔
422

423
  for (const QString &keystring : std::as_const(keystrings)) {
298 ✔
424
    if (!keystring.isEmpty()) {
164 ✔
425
      args.append(keystring);
426
    }
427
  }
428
  QString p_out;
134 ✔
429
  if (Executor::executeBlocking(m_settings.gpgExecutable, args, &p_out) != 0) {
134 ✔
430
    return {};
10 ✔
431
  }
432
  return parseGpgColonOutput(p_out, secret);
124 ✔
433
}
434

435
auto Pass::listKeys(const QString &keystring, bool secret) -> QList<UserInfo> {
111 ✔
436
  return listKeys(QStringList(keystring), secret);
222 ✔
437
}
438

439
namespace {
440

441
auto containsAny(const QString &str, const QStringList &patterns) -> bool {
94 ✔
442
  for (const QString &p : patterns) {
263 ✔
443
    if (str.contains(p)) {
180 ✔
444
      return true;
445
    }
446
  }
447
  return false;
448
}
449

450
// @p patterns must already be lowercase; only @p str is lowered.
451
auto containsAnyCaseInsensitive(const QString &str, const QStringList &patterns)
102 ✔
452
    -> bool {
453
  const QString lower = str.toLower();
454
  for (const QString &p : patterns) {
252 ✔
455
    if (lower.contains(p)) {
161 ✔
456
      return true;
457
    }
458
  }
459
  return false;
460
}
461

462
} // namespace
463

464
auto gpgErrorMessage(const QString &err) -> QString {
36 ✔
465
  // Machine-readable status tokens added by --status-fd 2
466
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYEXPIRED"),
180 ✔
467
                        QStringLiteral("[GNUPG:] INV_RECP 5 ")}))
36 ✔
468
    return QCoreApplication::translate(
469
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
470
                "replace it.");
5 ✔
471
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYREVOKED"),
155 ✔
472
                        QStringLiteral("[GNUPG:] INV_RECP 4 ")}))
31 ✔
473
    return QCoreApplication::translate(
474
        "Pass", "Encryption failed: GPG key has been revoked.");
4 ✔
475
  if (containsAny(err, {QStringLiteral("[GNUPG:] NO_PUBKEY"),
135 ✔
476
                        QStringLiteral("[GNUPG:] INV_RECP")}))
27 ✔
477
    return QCoreApplication::translate(
478
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
479
                "Check that the key ID in .gpg-id is correct and imported.");
2 ✔
480
  if (err.contains(QStringLiteral("[GNUPG:] FAILURE")))
25 ✔
481
    return QCoreApplication::translate(
482
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1 ✔
483

484
  // Locale-dependent fallbacks
485
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has expired"),
96 ✔
486
                                       QLatin1String("key expired")}))
487
    return QCoreApplication::translate(
488
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
489
                "replace it.");
1 ✔
490
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has been revoked"),
92 ✔
491
                                       QLatin1String("revoked")}))
492
    return QCoreApplication::translate(
493
        "Pass", "Encryption failed: GPG key has been revoked.");
1 ✔
494
  // pass passes no --status-fd, so this is all gpg says about a key that is
495
  // present but cannot encrypt: expired, revoked, without an encryption
496
  // subkey, or not trusted ("There is no assurance this key belongs to the
497
  // named user"). "Not found ... imported" would send the user the wrong
498
  // way; gpg's own lines, shown below this, say which it is.
499
  if (containsAnyCaseInsensitive(err, {QLatin1String("unusable public key")}))
66 ✔
500
    return QCoreApplication::translate(
501
        "Pass", "Encryption failed: a recipient's GPG key cannot be used. It "
502
                "may have expired or been revoked, have no encryption subkey, "
503
                "or not be trusted; gpg's message below says which.");
3 ✔
504
  if (containsAnyCaseInsensitive(err, {QLatin1String("no public key"),
76 ✔
505
                                       QLatin1String("no secret key")}))
506
    return QCoreApplication::translate(
507
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
508
                "Check that the key ID in .gpg-id is correct and imported.");
5 ✔
509
  if (containsAnyCaseInsensitive(err, {QLatin1String("encryption failed")}))
42 ✔
510
    return QCoreApplication::translate(
511
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1 ✔
512

513
  return {};
13 ✔
514
}
×
515

516
void Pass::finished(int id, int exitCode, const QString &out,
181 ✔
517
                    const QString &err) {
518
  auto pid = static_cast<PROCESS>(id);
181 ✔
519

520
  // Pop the Show() this completion belongs to whether it worked or not, or
521
  // the next result would be attributed to the wrong file.
522
  QString shownFile;
181 ✔
523
  if (pid == PASS_SHOW && !m_pendingShows.isEmpty()) {
181 ✔
524
    shownFile = m_pendingShows.dequeue();
48 ✔
525
  }
526
  // Count this insert off, success or failure, before its result goes out, so
527
  // insertsPending() tracks the inserts still awaiting a report. Each insert
528
  // reaches here once as PASS_INSERT.
529
  if (pid == PASS_INSERT && m_insertsPending > 0) {
181 ✔
530
    --m_insertsPending;
77 ✔
531
  }
532

533
  if (exitCode != 0) {
181 ✔
534
    handleProcessError(pid, exitCode, out, err);
39 ✔
535
    return;
536
  }
537

538
  if (pid == PASS_SHOW) {
142 ✔
539
    emit finishedShow(out, shownFile);
33 ✔
540
    return;
541
  }
542
  emitProcessFinishedSignal(pid, out, err);
109 ✔
543
}
544

545
void Pass::handleProcessError(PROCESS pid, int exitCode, const QString &out,
39 ✔
546
                              const QString &err) {
547
  Q_UNUSED(out);
548

549
  if (pid == PASS_INSERT) {
39 ✔
550
    const QString friendly = gpgErrorMessage(err);
18 ✔
551
    const QString why =
552
        friendly.isEmpty() ? err : formatInsertError(friendly, err);
18 ✔
553
    const bool written = insertWritten(err);
18 ✔
554
    emit insertFailed(why, written);
18 ✔
555
    if (written) {
18 ✔
556
      // The entry is in the store; a git step after it failed (a commit
557
      // that could not be signed, with pass.signcommits, say). The dialog
558
      // closes on this, so say it here rather than only in the output
559
      // panel.
560
      emit critical(tr("Saved, not committed"),
8 ✔
561
                    tr("The entry is saved in the store, but recording it "
4 ✔
562
                       "in git failed. What was reported:\n\n%1")
563
                        .arg(err.trimmed()));
8 ✔
564
    }
565
    emit processErrorExit(exitCode, why);
18 ✔
566
    return;
567
  }
568

569
  if (pid == GPG_GENKEYS) {
21 ✔
570
    emit generateGPGKeysFailed(err);
1 ✔
571
  }
572
  emit processErrorExit(exitCode, err);
21 ✔
573
}
574

575
auto Pass::formatInsertError(const QString &friendly, const QString &err)
6 ✔
576
    -> QString {
577
  QStringList humanLines;
6 ✔
578
  for (const QString &line : err.split('\n')) {
27 ✔
579
    QString cleanedLine = line;
580
    cleanedLine.remove('\r');
15 ✔
581
    if (!cleanedLine.startsWith(QLatin1String("[GNUPG:]")))
15 ✔
582
      humanLines.append(cleanedLine);
583
  }
584
  const QString humanErr = humanLines.join('\n').trimmed();
12 ✔
585
  return humanErr.isEmpty() ? friendly : friendly + "\n\n" + humanErr;
18 ✔
586
}
587

588
void Pass::emitProcessFinishedSignal(PROCESS pid, const QString &out,
109 ✔
589
                                     const QString &err) {
590
  // Only output that cannot contain a secret reaches the generic listeners
591
  // (the output panel among them); Enums::processInfo is the one table.
592
  if (pid >= 0 && pid < Enums::PROCESS_COUNT &&
109 ✔
593
      !Enums::processInfo(pid).secret) {
107 ✔
594
    emit finishedAnyWithPid(out, err, pid);
41 ✔
595
  }
596

597
  // The kind-specific signal. PASS_SHOW is emitted by finished(), which
598
  // knows the file. Content search runs in-process (NativeGrep), not
599
  // through `pass grep`, and emits finishedGrep itself.
600
  using Signal = void (Pass::*)(const QString &, const QString &);
601
  static const QHash<int, Signal> kSignals{
602
      {GIT_INIT, &Pass::finishedGitInit},
603
      {GIT_PULL, &Pass::finishedGitPull},
604
      {GIT_PUSH, &Pass::finishedGitPush},
605
      {PASS_INSERT, &Pass::finishedInsert},
606
      {PASS_REMOVE, &Pass::finishedRemove},
607
      {PASS_INIT, &Pass::finishedInit},
608
      {PASS_MOVE, &Pass::finishedMove},
609
      {PASS_COPY, &Pass::finishedCopy},
610
      {GPG_GENKEYS, &Pass::finishedGenerateGPGKeys},
611
  };
115 ✔
612
  if (const Signal signal = kSignals.value(pid, nullptr)) {
109 ✔
613
    (this->*signal)(out, err);
105 ✔
614
  }
615
}
109 ✔
616

617
void Pass::setEnvVar(const QString &name, const QString &value) {
2,818 ✔
618
  if (value.isEmpty())
2,818 ✔
619
    env.remove(name);
936 ✔
620
  else
621
    env.insert(name, value);
1,882 ✔
622
}
2,818 ✔
623

624
void Pass::updateEnv() {
312 ✔
625
  setEnvVar(QStringLiteral("PASSWORD_STORE_SIGNING_KEY"),
624 ✔
626
            m_settings.passSigningKey);
312 ✔
627
  setEnvVar(QStringLiteral("PASSWORD_STORE_DIR"), m_settings.passStore);
624 ✔
628
  // Every path QtPass hands git names one file or folder: an entry called
629
  // "a*.gpg" must not make `git rm -f -- a*.gpg` remove every entry that
630
  // matches. Also reaches the git that pass runs, which passes names the
631
  // same way.
632
  setEnvVar(QStringLiteral("GIT_LITERAL_PATHSPECS"), QStringLiteral("1"));
624 ✔
633

634
  const PasswordConfiguration &passConfig = m_settings.passwordConfiguration;
312 ✔
635
  setEnvVar(QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH"),
624 ✔
636
            QString::number(passConfig.length));
312 ✔
637

638
  setEnvVar(QStringLiteral("PASSWORD_STORE_CHARACTER_SET"),
624 ✔
639
            effectiveCharset(passConfig));
312 ✔
640

641
  // pass hands PASSWORD_STORE_GPG_OPTS to every gpg it runs: the user's own
642
  // options (split as pass's shell splits them: spaces, tabs, newlines),
643
  // then the output limit ImitatePass passes directly.
644
  QStringList gpgOpts = QProcessEnvironment::systemEnvironment()
312 ✔
645
                            .value(QStringLiteral("PASSWORD_STORE_GPG_OPTS"))
624 ✔
646
                            .split(QRegularExpression(QStringLiteral("\\s+")),
624 ✔
647
                                   Qt::SkipEmptyParts);
624 ✔
648
  gpgOpts << maxOutputArgs();
624 ✔
649
  setEnvVar(QStringLiteral("PASSWORD_STORE_GPG_OPTS"),
624 ✔
650
            gpgOpts.join(QLatin1Char(' ')));
312 ✔
651

652
  // As pass does: git never looks for a repository above the store's own
653
  // parent. A store that is not a repository itself but lies inside one (a
654
  // dotfiles repository in the home folder) would otherwise have its entries
655
  // committed and pushed there by native git mode. Only in the environment
656
  // of the processes QtPass runs for the store, never QtPass's own, which a
657
  // file manager or terminal it opens would inherit. pass sets its own
658
  // ceiling whatever this says. A store kept inside a larger repository on
659
  // purpose opts out (gitUseParentRepository), and then, as without a
660
  // store, whatever ceiling QtPass was started with applies.
661
  // A ceiling git cannot take as one entry (the parent's path holds the
662
  // list separator) is backed by GIT_DIR and GIT_WORK_TREE naming the
663
  // store's own repository (Util::gitStoreVariables()); pass unsets those
664
  // for itself and keeps its own ceiling.
665
  setEnvVar(QStringLiteral("GIT_DIR"), QString());
624 ✔
666
  setEnvVar(QStringLiteral("GIT_WORK_TREE"), QString());
624 ✔
667
  if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
312 ✔
668
    setEnvVar(QStringLiteral("GIT_CEILING_DIRECTORIES"),
34 ✔
669
              qEnvironmentVariable("GIT_CEILING_DIRECTORIES"));
34 ✔
670
  } else {
671
    for (const auto &[name, value] : Util::gitStoreVariables(
672
             m_settings.passStore, m_settings.gitExecutable)) {
889 ✔
673
      setEnvVar(name, value);
299 ✔
674
    }
675
  }
676

677
  exec.setEnvironment(env);
312 ✔
678
}
312 ✔
679

680
auto Pass::withCurrentGitPin(QProcessEnvironment base) const
832 ✔
681
    -> QProcessEnvironment {
682
  if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
832 ✔
683
    return base;
×
684
  }
685
  base.remove(QStringLiteral("GIT_DIR"));
1,664 ✔
686
  base.remove(QStringLiteral("GIT_WORK_TREE"));
1,664 ✔
687
  for (const auto &[name, value] : Util::gitStoreVariables(
688
           m_settings.passStore, m_settings.gitExecutable)) {
2,506 ✔
689
    base.insert(name, value);
842 ✔
690
  }
691
  return base;
832 ✔
692
}
693

694
auto Pass::maxOutputArgs() -> QStringList {
903 ✔
695
  return {QStringLiteral("--max-output"), QString::number(kMaxPlaintextBytes)};
2,709 ✔
696
}
903 ✔
697

698
namespace {
699
/// File names compare the way the platform's file system compares them:
700
/// "C:/Store" and "c:/store" are the same directory on Windows.
701
#ifdef Q_OS_WIN
702
constexpr auto kPathCase = Qt::CaseInsensitive;
703
#else
704
constexpr auto kPathCase = Qt::CaseSensitive;
705
#endif
706

707
/// Whether @p path is @p dir or lies under it.
708
auto isAtOrUnder(const QString &path, const QString &dir,
660 ✔
709
                 const QString &dirPrefix) -> bool {
710
  return path.compare(dir, kPathCase) == 0 ||
1,059 ✔
711
         path.startsWith(dirPrefix, kPathCase);
399 ✔
712
}
713

714
/// Where the lookup of a .gpg-id starts and the store that bounds it.
715
struct GpgIdLookup {
716
  QDir start;
717
  QString storeDir;
718
  QString storePrefix;
719
};
720

721
/// The folder whose list @p for_file wants: its own for a folder, its
722
/// folder's for an entry.
723
auto gpgIdLookup(const QString &for_file, const QString &passStore)
325 ✔
724
    -> GpgIdLookup {
725
  const QString normalizedFile = QDir::fromNativeSeparators(for_file);
325 ✔
726
  // Inside the store means at a path boundary: "/store-other/x" is not
727
  // under "/store", however the prefix compares.
728
  const QString storeDir =
729
      QDir::cleanPath(QDir::fromNativeSeparators(passStore));
325 ✔
730
  const QString storePrefix = storeDir.endsWith(QLatin1Char('/'))
325 ✔
731
                                  ? storeDir
325 ✔
732
                                  : storeDir + QLatin1Char('/');
325 ✔
733
  const QString cleanFile = QDir::cleanPath(normalizedFile);
325 ✔
734
  const bool insideStore = isAtOrUnder(cleanFile, storeDir, storePrefix);
325 ✔
735
  // A relative name is one inside the store; an absolute path outside it
736
  // stays what it is and the walk stops at once.
737
  const QString fullPath = insideStore || QDir::isAbsolutePath(cleanFile)
15 ✔
738
                               ? cleanFile
325 ✔
739
                               : storePrefix + cleanFile;
10 ✔
740
  // A folder (trailing separator, which cleanPath() dropped, or an existing
741
  // directory) wants its own list; an entry wants its folder's.
742
  const bool isFolder =
743
      normalizedFile.endsWith(QLatin1Char('/')) || QFileInfo(fullPath).isDir();
325 ✔
744
  // A folder that does not exist yet (an entry saved into a new folder, a
745
  // move to one) starts the walk at its nearest existing ancestor in the
746
  // store, as pass's set_gpg_recipients does: otherwise the walk ended at
747
  // once and the store root's list was taken over the one in between.
748
  QString start = isFolder ? fullPath : QFileInfo(fullPath).absolutePath();
325 ✔
749
  while (!QFileInfo(start).exists() &&
337 ✔
750
         isAtOrUnder(QDir::cleanPath(start), storeDir, storePrefix) &&
668 ✔
751
         QDir::cleanPath(start) != storeDir) {
337 ✔
752
    start = QFileInfo(start).absolutePath();
12 ✔
753
  }
754
  return {QDir(start), storeDir, storePrefix};
325 ✔
755
}
325 ✔
756

757
/// Whether @p candidate can be its folder's .gpg-id. A link under the name
758
/// is not: whoever planted it chose the recipients elsewhere.
759
auto isOwnGpgId(const QFileInfo &candidate) -> bool {
356 ✔
760
  return candidate.exists() && !candidate.isSymLink() &&
597 ✔
761
         !candidate.isJunction();
241 ✔
762
}
763

764
/// Walk up from the lookup's start to the first folder inside the store
765
/// that has its own .gpg-id; nothing when none does. A link under the name
766
/// is skipped, so the parent's list applies instead.
767
auto nearestGpgId(const GpgIdLookup &lookup) -> std::optional<QString> {
248 ✔
768
  QDir dir = lookup.start;
248 ✔
769
  while (dir.exists() && isAtOrUnder(QDir::cleanPath(dir.absolutePath()),
1,316 ✔
770
                                     lookup.storeDir, lookup.storePrefix)) {
329 ✔
771
    const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
304 ✔
772
    if (isOwnGpgId(candidate)) {
304 ✔
773
      return candidate.absoluteFilePath();
223 ✔
774
    }
775
    if (!dir.cdUp()) {
81 ✔
776
      break;
777
    }
778
  }
304 ✔
779
  return std::nullopt;
25 ✔
780
}
248 ✔
781

782
} // namespace
783

784
auto Pass::refuseLinkedPath(const QString &path, LinkScope scope,
435 ✔
785
                            PathSpelling spelling) -> bool {
786
  const QString full = QDir::isAbsolutePath(path)
787
                           ? path
435 ✔
788
                           : QDir(m_settings.passStore).filePath(path);
82 ✔
789
  // The link check below walks only under the store as configured: a path
790
  // spelled through the root's link target would get no more than the
791
  // entry itself judged. No caller makes one; say so if one starts to.
792
  if (spelling == PathSpelling::Configured &&
725 ✔
793
      PathValidator::isTargetSpelled(m_settings.passStore, full)) {
290 ✔
794
    qCWarning(lcQtPass)
4 ✔
795
        << "Path spelled through the store root's link target, not as the "
796
           "store is configured; Pass operations expect the configured "
797
           "spelling:"
2 ✔
798
        << full;
2 ✔
799
  }
800
  if (!Util::isUnderLink(full, m_settings.passStore,
435 ✔
801
                         scope == LinkScope::EntryAndParents)) {
802
    return false;
803
  }
804
  const QString why =
805
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
×
806
         "points to is not part of the password store and is left alone.")
807
          .arg(QDir::toNativeSeparators(QDir::cleanPath(full)));
54 ✔
808
  refuseAsNotPartOfStore(why);
27 ✔
809
  return true;
810
}
811

812
auto Pass::refuseFolderOutsideStore(const QString &folder, QString *relative)
46 ✔
813
    -> bool {
814
  if (const std::optional<QString> inStore =
46 ✔
815
          PathValidator::storeRelativePath(m_settings.passStore, folder)) {
46 ✔
816
    if (relative != nullptr) {
41 ✔
817
      *relative = *inStore;
41 ✔
818
    }
819
    return false;
820
  }
821
  refuseAsNotPartOfStore(
5 ✔
822
      tr("%1 is not inside the password store. Recipients are set for the "
5 ✔
823
         "store or a folder in it.")
824
          .arg(QDir::toNativeSeparators(QDir::cleanPath(folder))));
10 ✔
825
  return true;
5 ✔
826
}
827

828
auto Pass::unfinishedGitOperationReason() -> QString {
484 ✔
829
  if (!m_settings.useGit) {
484 ✔
830
    return {};
384 ✔
831
  }
832
  // One git call names the path of each marker file or directory, whether or
833
  // not it exists; the backend runs it in the store (ImitatePass with
834
  // `-C <store>`, RealPass through `pass git`). The markers, paired with the
835
  // operation each one means, in the order git prints them back.
836
  const std::array<std::pair<QLatin1String, QString>, 6> markers{{
837
      {QLatin1String("rebase-merge"), tr("rebase")},
100 ✔
838
      {QLatin1String("rebase-apply"), tr("rebase")},
100 ✔
839
      {QLatin1String("MERGE_HEAD"), tr("merge")},
100 ✔
840
      {QLatin1String("CHERRY_PICK_HEAD"), tr("cherry-pick")},
100 ✔
841
      {QLatin1String("REVERT_HEAD"), tr("revert")},
100 ✔
842
      // A multi-commit cherry-pick or revert keeps its sequencer state after a
843
      // conflict resolution is committed, when CHERRY_PICK_HEAD/REVERT_HEAD is
844
      // already gone but `--continue` has more commits to apply. Checked last,
845
      // so the specific head above names the operation when it is still there.
846
      {QLatin1String("sequencer"), tr("cherry-pick or revert")},
100 ✔
NEW
847
  }};
×
848
  QStringList args{QStringLiteral("rev-parse")};
200 ✔
849
  for (const auto &marker : markers) {
700 ✔
850
    args << QStringLiteral("--git-path") << marker.first;
600 ✔
851
  }
852
  QString out;
100 ✔
853
  if (!storeGit(args, &out)) {
100 ✔
854
    // Git is off, the store is not a repository, or git could not be asked:
855
    // nothing is refused, as the operation would run anyway.
856
    return {};
14 ✔
857
  }
858
  const QStringList paths = out.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
86 ✔
859
  for (int i = 0; i < paths.size() && i < static_cast<int>(markers.size());
221 ✔
860
       ++i) {
861
    const QString path = paths.at(i).trimmed();
862
    const QString full = QDir::isAbsolutePath(path)
863
                             ? path
141 ✔
864
                             : QDir(m_settings.passStore).filePath(path);
141 ✔
865
    if (!QFileInfo::exists(full)) {
141 ✔
866
      continue;
867
    }
868
    return tr("The store's Git repository is in the middle of a %1. Finish or "
6 ✔
869
              "abort it with git before changing the store, or what you change "
870
              "may be lost.")
871
        .arg(markers.at(static_cast<size_t>(i)).second);
6 ✔
872
  }
873
  return {};
80 ✔
874
}
875

876
auto Pass::refuseUnfinishedGitOperation() -> bool {
342 ✔
877
  const QString why = unfinishedGitOperationReason();
342 ✔
878
  if (why.isEmpty()) {
342 ✔
879
    return false;
880
  }
881
  // Like refuseAsNotPartOfStore(): the interface arms when an operation starts
882
  // and is released by finished()/processErrorExit(); a refusal starts
883
  // nothing, so it emits both ends.
884
  emit startingExecuteWrapper();
4 ✔
885
  emit critical(tr("Unfinished Git operation"), why);
4 ✔
886
  emit processErrorExit(1, why);
4 ✔
887
  return true;
888
}
889

890
void Pass::refuseAsNotPartOfStore(const QString &why) {
32 ✔
891
  // The interface arms itself when an operation starts and is released by
892
  // finished or processErrorExit; a refusal starts nothing, so emits both.
893
  emit startingExecuteWrapper();
32 ✔
894
  emit critical(tr("Not part of the store"), why);
32 ✔
895
  emit processErrorExit(1, why);
32 ✔
896
}
32 ✔
897

898
auto Pass::getGpgIdPath(const QString &for_file, const QString &passStore)
248 ✔
899
    -> QString {
900
  return nearestGpgId(gpgIdLookup(for_file, passStore))
496 ✔
901
      .value_or(
902
          QDir(QDir::fromNativeSeparators(passStore)).filePath(".gpg-id"));
992 ✔
903
}
904

905
auto Pass::refuseSkippedGpgId(const QString &file, bool signing,
158 ✔
906
                              const QString &except) -> bool {
907
  // Without a signing key the parent's list applies, as it does for pass.
908
  if (!signing) {
158 ✔
909
    return false;
910
  }
911
  QString recordError;
56 ✔
912
  const std::optional<QString> skipped =
913
      skippedGpgId(file, m_settings.passStore, &recordError);
56 ✔
914
  if (!skipped || (!except.isEmpty() &&
56 ✔
915
                   QDir::cleanPath(*skipped) == QDir::cleanPath(except))) {
58 ✔
916
    return false;
917
  }
918
  // The strings keep the context they were translated in.
919
  if (!recordError.isEmpty()) {
5 ✔
920
    emit critical(QCoreApplication::translate(
×
921
                      "ImitatePass", "Cannot check the recipient list"),
922
                  QCoreApplication::translate(
×
923
                      "ImitatePass", "%1 Whether %2 was removed cannot be "
924
                                     "told, so nothing was encrypted.")
925
                      .arg(recordError, QDir::toNativeSeparators(*skipped)));
×
926
    return true;
×
927
  }
928
  emit critical(
5 ✔
929
      QCoreApplication::translate("ImitatePass", "Recipient list missing"),
10 ✔
930
      QCoreApplication::translate(
5 ✔
931
          "ImitatePass",
932
          "The signed recipient list %1 is missing or is not a regular file. "
933
          "QtPass does not fall back to a parent folder's list for it: that "
934
          "list was not signed for this folder. If a link is under that name, "
935
          "remove it. Then open Users for that folder and save its "
936
          "recipients, which writes and signs a fresh list.")
937
          .arg(QDir::toNativeSeparators(*skipped)));
10 ✔
938
  return true;
5 ✔
939
}
940

941
auto Pass::verifySignedList(const GpgIdSigner &signer, const QString &gpgIdFile,
44 ✔
942
                            QByteArray *contents, QString *why) const -> bool {
943
  if (!signer.verifyFile(gpgIdFile, contents)) {
44 ✔
944
    return false;
945
  }
946
  // Authentic and unmodified is not the same as current: an older signed
947
  // list put back into the store is refused once this device has seen a
948
  // newer one, and one signed for another folder is refused here.
949
  QString reason;
43 ✔
950
  if (GpgIdGeneration::accept(gpgIdFile, *contents, m_settings.passStore,
43 ✔
951
                              &reason) != GpgIdGeneration::Verdict::Accepted) {
952
    if (why != nullptr) {
16 ✔
953
      *why = reason;
16 ✔
954
    }
955
    return false;
16 ✔
956
  }
957
  return true;
958
}
959

960
auto Pass::skippedGpgId(const QString &forFile, const QString &passStore,
77 ✔
961
                        QString *recordError) -> std::optional<QString> {
962
  const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
77 ✔
963
  QDir dir = lookup.start;
77 ✔
964
  // The same walk as nearestGpgId(), stopping at the list it finds, and
965
  // short of the store root: the root's own list has no parent to fall
966
  // back to, and the signature check refuses it when it is missing.
967
  while (dir.exists() && QDir::cleanPath(dir.absolutePath())
300 ✔
968
                             .startsWith(lookup.storePrefix, kPathCase)) {
100 ✔
969
    const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
52 ✔
970
    if (isOwnGpgId(candidate)) {
52 ✔
971
      return std::nullopt;
18 ✔
972
    }
973
    // A link under the name (dangling or not), or nothing under it where
974
    // this device accepted a list before: both are the folder's list gone,
975
    // not a folder that never had one.
976
    if (candidate.isSymLink() || candidate.isJunction()) {
34 ✔
977
      return candidate.absoluteFilePath();
12 ✔
978
    }
979
    // An unreadable record is not "never seen": whether a list was accepted
980
    // here cannot be told, so this folder is refused too (fail closed), with
981
    // the record's own reason for the caller to show.
982
    QString why;
28 ✔
983
    const std::optional<qint64> seen =
984
        GpgIdGeneration::remembered(candidate.absoluteFilePath(), &why);
56 ✔
985
    if (!seen) {
28 ✔
986
      if (recordError != nullptr) {
1 ✔
987
        *recordError =
988
            why.isEmpty()
989
                ? tr("The generation record of the recipient lists cannot "
2 ✔
990
                     "be read.")
991
                : why;
992
      }
993
      return candidate.absoluteFilePath();
2 ✔
994
    }
995
    if (*seen > 0) {
27 ✔
996
      return candidate.absoluteFilePath();
8 ✔
997
    }
998
    if (!dir.cdUp()) {
23 ✔
999
      break;
1000
    }
1001
  }
52 ✔
1002
  return std::nullopt;
48 ✔
1003
}
77 ✔
1004

1005
namespace {
1006

1007
/// What the Users dialog may preselect for a verified list, given what the
1008
/// generation record says about it.
1009
auto judgedRecipients(GpgIdGeneration::Verdict verdict,
7 ✔
1010
                      const QByteArray &contents, const QString &gpgIdPath,
1011
                      const QString &why) -> Pass::RecipientsForEditing {
1012
  using RecipientsForEditing = Pass::RecipientsForEditing;
1013
  RecipientsForEditing result;
7 ✔
1014
  switch (verdict) {
7 ✔
1015
  case GpgIdGeneration::Verdict::Accepted:
1 ✔
1016
    result.state = RecipientsForEditing::State::Verified;
1 ✔
1017
    result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1 ✔
1018
    break;
1 ✔
1019
  case GpgIdGeneration::Verdict::Rollback:
1 ✔
1020
    // Authentic and this folder's, only older: the recovery goes through
1021
    // this dialog, so it is preselected, with the reason in view.
1022
    result.state = RecipientsForEditing::State::VerifiedRollback;
1 ✔
1023
    result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1 ✔
1024
    result.warning = why;
1 ✔
1025
    break;
1 ✔
1026
  case GpgIdGeneration::Verdict::Unbound:
5 ✔
1027
  case GpgIdGeneration::Verdict::Conflict:
1028
  case GpgIdGeneration::Verdict::WrongFolder:
1029
  case GpgIdGeneration::Verdict::WrongStore:
1030
  case GpgIdGeneration::Verdict::Malformed:
1031
  case GpgIdGeneration::Verdict::RecordUnavailable:
1032
    // Signed, but not shown to be this folder's list, not a list to trust,
1033
    // or nothing to judge it by: preselecting it would sign it in.
1034
    result.state = RecipientsForEditing::State::Rejected;
5 ✔
1035
    result.warning =
1036
        Pass::tr("%1 Nothing is preselected: saving would sign whatever is "
5 ✔
1037
                 "in it. Select the recipients yourself.")
1038
            .arg(why);
10 ✔
1039
    break;
5 ✔
1040
  }
1041
  return result;
7 ✔
1042
}
1043

1044
} // namespace
1045

1046
auto Pass::recipientsForEditing(const QString &dir, const QString &passStore)
44 ✔
1047
    -> RecipientsForEditing {
1048
  RecipientsForEditing result;
44 ✔
1049
  const QString folder = dir.isEmpty() ? QString() : dir;
44 ✔
1050
  const QString gpgIdPath = getGpgIdPath(folder, passStore);
44 ✔
1051
  const GpgIdSigner signer(
1052
      m_settings.gpgExecutable,
1053
      GpgIdSigner::keysFromSetting(m_settings.passSigningKey));
132 ✔
1054
  if (!signer.enabled()) {
44 ✔
1055
    // A list that is there but cannot be read as one (too large, not a
1056
    // regular file, unreadable) is not an empty list: preselecting nothing
1057
    // without a word would let OK write a new list over it, and later
1058
    // re-encryptions drop whoever it named.
1059
    // Read once and parsed from those bytes: a second read could find
1060
    // something else under the name. A link counts as there, dangling too.
1061
    const QFileInfo info(gpgIdPath);
34 ✔
1062
    if (!info.exists() && !info.isSymLink()) {
34 ✔
1063
      result.state = RecipientsForEditing::State::Unsigned;
1064
      return result;
13 ✔
1065
    }
1066
    const std::optional<QByteArray> bytes =
1067
        Util::readRegularFile(gpgIdPath, Util::kMaxGpgIdBytes);
21 ✔
1068
    if (!bytes) {
21 ✔
1069
      result.state = RecipientsForEditing::State::Rejected;
2 ✔
1070
      result.warning =
1071
          tr("%1 cannot be read as a recipient list (a regular file of at "
2 ✔
1072
             "most %2), so nothing is preselected. Check it before choosing "
1073
             "recipients here: OK writes a new list over it.")
1074
              .arg(gpgIdPath,
2 ✔
1075
                   QLocale().formattedDataSize(Util::kMaxGpgIdBytes));
4 ✔
1076
      return result;
2 ✔
1077
    }
1078
    result.state = RecipientsForEditing::State::Unsigned;
1079
    result.recipients = parseRecipients(*bytes, gpgIdPath);
19 ✔
1080
    return result;
19 ✔
1081
  }
34 ✔
1082
  QString recordError;
10 ✔
1083
  if (const std::optional<QString> skipped =
10 ✔
1084
          skippedGpgId(folder, passStore, &recordError)) {
10 ✔
1085
    // The folder's own list was removed or replaced by a link (or the record
1086
    // that would tell cannot be read): the list the walk found further up
1087
    // was not signed for this folder, so preselecting it would sign it in
1088
    // here with one click.
1089
    result.state = RecipientsForEditing::State::Rejected;
1 ✔
1090
    result.warning =
1091
        recordError.isEmpty()
1092
            ? tr("The recipient list %1 is missing or is not a regular file, "
2 ✔
1093
                 "so nothing is preselected: the list of a parent folder was "
1094
                 "not signed for this one. Select this folder's recipients "
1095
                 "yourself; OK writes and signs a fresh list.")
1096
                  .arg(*skipped)
1097
            : tr("%1 Nothing is preselected: whether %2 was removed cannot "
1 ✔
1098
                 "be told.")
1099
                  .arg(recordError, *skipped);
1100
    return result;
1 ✔
1101
  }
1102
  if (!QFileInfo::exists(gpgIdPath)) {
9 ✔
1103
    // A folder without a list yet (new store, new profile): nothing to
1104
    // verify and nothing to preselect.
1105
    result.state = RecipientsForEditing::State::Verified;
1 ✔
1106
    return result;
1 ✔
1107
  }
1108
  QByteArray contents;
8 ✔
1109
  if (!signer.verifyFile(gpgIdPath, &contents)) {
8 ✔
1110
    result.state = RecipientsForEditing::State::Rejected;
1 ✔
1111
    result.warning =
1112
        tr("The recipient list %1 does not verify against the signing key, "
1 ✔
1113
           "so nothing is preselected: saving would sign whatever is in it. "
1114
           "Select the recipients yourself; OK writes and signs a fresh list.")
1115
            .arg(gpgIdPath);
2 ✔
1116
    return result;
1 ✔
1117
  }
1118
  QString why;
7 ✔
1119
  const GpgIdGeneration::Verdict verdict =
1120
      GpgIdGeneration::accept(gpgIdPath, contents, passStore, &why);
7 ✔
1121
  return judgedRecipients(verdict, contents, gpgIdPath, why);
7 ✔
1122
}
44 ✔
1123

1124
auto Pass::getRecipientList(const QString &for_file, const QString &passStore)
18 ✔
1125
    -> QStringList {
1126
  const QString gpgIdPath = getGpgIdPath(for_file, passStore);
18 ✔
1127
  // The root .gpg-id comes back whatever it is; a link is not a list.
1128
  if (Util::isLinkedFolder(gpgIdPath)) {
18 ✔
1129
    return {};
1 ✔
1130
  }
1131
  const std::optional<QByteArray> bytes =
1132
      Util::readRegularFile(gpgIdPath, Util::kMaxGpgIdBytes);
17 ✔
1133
  if (!bytes) {
17 ✔
1134
    return {};
1 ✔
1135
  }
1136
  return parseRecipients(*bytes, gpgIdPath);
16 ✔
1137
}
1138

1139
auto Pass::parseRecipients(const QByteArray &contents,
154 ✔
1140
                           const QString &sourceName) -> QStringList {
1141
  QStringList recipients;
154 ✔
1142
  const QString text = QString::fromUtf8(contents);
1143
  for (const QString &line : text.split(QLatin1Char('\n'))) {
565 ✔
1144
    QString recipient = line.split(QLatin1Char('#')).first().trimmed();
822 ✔
1145
    if (recipient.isEmpty()) {
411 ✔
1146
      continue;
213 ✔
1147
    }
1148
    if (!Util::isValidKeyId(recipient)) {
198 ✔
1149
      // Never drop a recipient silently: the list is written back verbatim
1150
      // by UsersDialog, so a skipped line disappears from .gpg-id.
1151
      qCWarning(lcQtPass) << "Skipping unusable recipient in" << sourceName
4 ✔
1152
                          << ":" << recipient;
2 ✔
1153
      continue;
2 ✔
1154
    }
2 ✔
1155
    recipients += recipient;
1156
  }
1157
  return recipients;
154 ✔
1158
}
1159

1160
auto Pass::seedGpgIdFile(const QString &newDir, const QString &passStore)
8 ✔
1161
    -> bool {
1162
  const QString gpgIdFile = QDir(newDir).absoluteFilePath(".gpg-id");
16 ✔
1163
  if (QFileInfo::exists(gpgIdFile)) {
8 ✔
1164
    return false;
1165
  }
1166
  // Resolving from the file to be created finds the parent's .gpg-id whether
1167
  // or not newDir has a trailing separator.
1168
  const QStringList recipients = getRecipientList(gpgIdFile, passStore);
7 ✔
1169
  if (recipients.isEmpty()) {
7 ✔
1170
    return false;
1171
  }
1172
  // Only reached without a signing key, so no generation header: a plain
1173
  // list stays readable for clients that take a comment for a recipient.
1174
  // Staged and replacing nothing: a link planted after the exists() above
1175
  // (a dangling one passes it) fails the seed instead of being written through.
1176
  return Util::writeFileReplacing(
4 ✔
1177
      gpgIdFile,
1178
      (recipients.join(QLatin1Char('\n')) + QLatin1Char('\n')).toUtf8(), false);
8 ✔
1179
}
1180

1181
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
1182
 */
1183

1184
auto Pass::boundedRandom(quint32 bound) -> quint32 {
7,620 ✔
1185
  if (bound < 2) {
7,620 ✔
1186
    return 0;
1187
  }
1188

1189
  quint32 randval;
1190
  // arc4random_uniform-style rejection against modulo bias: drop values
1191
  // below 2^32 % bound, which (1 + ~bound) % bound computes in quint32.
1192
  const quint32 rejectionThreshold = (1 + ~bound) % bound;
7,616 ✔
1193

1194
  do {
1195
    randval = QRandomGenerator::system()->generate();
1196
  } while (randval < rejectionThreshold);
7,616 ✔
1197

1198
  return randval % bound;
7,616 ✔
1199
}
1200

1201
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,209 ✔
1202
    -> QString {
1203
  if (charset.isEmpty() || length == 0U) {
1,209 ✔
1204
    return {};
2 ✔
1205
  }
1206
  QString out;
1,207 ✔
1207
  for (unsigned int i = 0; i < length; ++i) {
8,827 ✔
1208
    out.append(charset.at(static_cast<int>(
7,620 ✔
1209
        boundedRandom(static_cast<quint32>(charset.length())))));
7,620 ✔
1210
  }
1211
  return out;
1212
}
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